Skip to content

An AI-powered search engine with a generative UI

Add account usage budgets (#1027)

Yoshiki Miura26b5dc47b019
diff --git a/app/api/chat/route.ts b/app/api/chat/route.ts
index 767033d6..9e7c6128 100644
--- a/app/api/chat/route.ts
+++ b/app/api/chat/route.ts
@@ -1,5 +1,6 @@
import { revalidateTag } from 'next/cache'
import { cookies } from 'next/headers'
+import { after } from 'next/server'
import {
calculateConversationTurn,
@@ -7,7 +8,7 @@ import {
deriveQueryShape,
trackChatEvent
} from '@/lib/analytics'
-import { getCurrentUserId } from '@/lib/auth/get-current-user'
+import { getCurrentUser, getCurrentUserId } from '@/lib/auth/get-current-user'
import { getUserMessageIds } from '@/lib/db/actions'
import { generateId } from '@/lib/db/schema'
import { checkAndEnforceAdaptiveLimit } from '@/lib/rate-limit/adaptive-limit'
@@ -20,6 +21,18 @@ import {
import { createChatStreamResponse } from '@/lib/streaming/create-chat-stream-response'
import { createEphemeralChatStreamResponse } from '@/lib/streaming/create-ephemeral-chat-stream-response'
import { SearchMode } from '@/lib/types/search'
+import {
+ consumeUsage,
+ createUsageRefundHandler,
+ ENFORCEMENT,
+ isUsageBudgetAvailable,
+ isValidUsageAttemptId,
+ recordUsageEvent,
+ refundUsage,
+ trackUsageConsumed,
+ trackUsageLimitReached,
+ usageLimitResponse
+} from '@/lib/usage-budget'
import { getTextFromParts } from '@/lib/utils/message-utils'
import { selectModel } from '@/lib/utils/model-selection'
import { perfLog, perfTime } from '@/lib/utils/perf-logging'
@@ -28,9 +41,20 @@ import { isProviderEnabled } from '@/lib/utils/registry'
export const maxDuration = 300
+type UsageSettlementSlot = {
+ spend?: { amount: number; remaining: number }
+ refund?: { amount: number; remaining: number }
+ limitReached?: {
+ amount: number
+ remaining: number
+ reason: 'monthly' | 'hourly'
+ }
+}
+
export async function POST(req: Request) {
const startTime = performance.now()
const abortSignal = req.signal
+ let refundUsageOnce: (() => Promise<void>) | undefined
// Reset counters for new request (development only)
if (process.env.ENABLE_PERF_LOGGING === 'true') {
@@ -41,6 +65,7 @@ export async function POST(req: Request) {
const body = await req.json()
const { message, messages, chatId, trigger, messageId, isNewChat } = body
const analyticsId: unknown = body.analyticsId
+ const usageAttemptId: unknown = body.usageAttemptId
// Normalize the message id up front so persistence and analytics agree on it.
if (message && !message.id) {
@@ -72,7 +97,13 @@ export async function POST(req: Request) {
const isSharePage = referer?.includes('/share/')
const authStart = performance.now()
- const userId = await getCurrentUserId()
+ const currentUser =
+ process.env.ENABLE_AUTH === 'false' ? null : await getCurrentUser()
+ const userId =
+ currentUser?.id ??
+ (process.env.ENABLE_AUTH === 'false'
+ ? await getCurrentUserId()
+ : undefined)
perfTime('Auth completed', authStart)
if (isSharePage) {
@@ -112,6 +143,26 @@ export async function POST(req: Request) {
if (guestLimitResponse) return guestLimitResponse
}
+ const usageBudgetAvailable = !isGuest && isUsageBudgetAvailable()
+ if (
+ usageBudgetAvailable &&
+ ENFORCEMENT === 'on' &&
+ !isValidUsageAttemptId(usageAttemptId)
+ ) {
+ return new Response(
+ JSON.stringify({
+ error: 'A valid usage attempt ID is required.',
+ type: 'general',
+ code: 'bad_request',
+ retryable: false
+ }),
+ {
+ status: 400,
+ headers: { 'Content-Type': 'application/json' }
+ }
+ )
+ }
+
const cookieStore = await cookies()
// Get search mode from cookie
@@ -171,6 +222,140 @@ export async function POST(req: Request) {
const adaptiveLimitResponse = await checkAndEnforceAdaptiveLimit(userId)
if (adaptiveLimitResponse) return adaptiveLimitResponse
}
+
+ if (usageBudgetAvailable && isValidUsageAttemptId(usageAttemptId)) {
+ const usageNow = new Date()
+ const usage = await consumeUsage({
+ userId,
+ mode: searchMode,
+ attemptId: usageAttemptId,
+ messageId: message?.id ?? messageId,
+ userCreatedAt: currentUser?.created_at,
+ now: usageNow
+ })
+
+ if (usage.duplicate) {
+ if (!usage.allowed && ENFORCEMENT === 'on') {
+ return usageLimitResponse(usage)
+ }
+
+ return new Response(
+ JSON.stringify({
+ error: 'This usage attempt was already processed.',
+ type: 'general',
+ code: 'duplicate_attempt',
+ retryable: false
+ }),
+ {
+ status: 409,
+ headers: { 'Content-Type': 'application/json' }
+ }
+ )
+ }
+
+ const charged =
+ usage.enforced && (usage.allowed || ENFORCEMENT === 'shadow')
+ const settlement: UsageSettlementSlot = {}
+
+ if (charged) {
+ settlement.spend = {
+ amount: usage.cost,
+ remaining: usage.remaining
+ }
+ }
+ if (!usage.allowed && usage.reason) {
+ settlement.limitReached = {
+ amount: usage.cost,
+ remaining: usage.remaining,
+ reason: usage.reason
+ }
+ }
+
+ refundUsageOnce = createUsageRefundHandler({
+ charged,
+ refund: () =>
+ refundUsage({
+ userId,
+ attemptId: usageAttemptId,
+ now: usageNow
+ }),
+ onRefunded: refund => {
+ settlement.refund = {
+ amount: refund.amount,
+ remaining: refund.remaining
+ }
+ },
+ onError: error => {
+ console.error('Failed to refund usage attempt:', error)
+ }
+ })
+
+ if (usage.enforced) {
+ after(async () => {
+ const work: Promise<void>[] = []
+
+ if (settlement.spend) {
+ work.push(
+ recordUsageEvent({
+ userId,
+ eventType: 'spend',
+ amount: settlement.spend.amount,
+ mode: searchMode,
+ attemptId: usageAttemptId,
+ messageId: message?.id ?? messageId,
+ remaining: settlement.spend.remaining
+ }),
+ trackUsageConsumed({
+ userId,
+ mode: searchMode,
+ remaining: settlement.spend.remaining,
+ enforcement: ENFORCEMENT
+ })
+ )
+ }
+
+ if (settlement.limitReached) {
+ work.push(
+ recordUsageEvent({
+ userId,
+ eventType: 'limit_reached',
+ amount: settlement.limitReached.amount,
+ mode: searchMode,
+ attemptId: usageAttemptId,
+ messageId: message?.id ?? messageId,
+ remaining: settlement.limitReached.remaining
+ }),
+ trackUsageLimitReached({
+ userId,
+ mode: searchMode,
+ reason: settlement.limitReached.reason,
+ enforcement: ENFORCEMENT
+ })
+ )
+ }
+
+ if (settlement.refund) {
+ work.push(
+ recordUsageEvent({
+ userId,
+ eventType: 'refund',
+ amount: settlement.refund.amount,
+ mode: searchMode,
+ attemptId: usageAttemptId,
+ messageId: message?.id ?? messageId,
+ remaining: settlement.refund.remaining
+ })
+ )
+ }
+
+ await Promise.allSettled(work)
+ })
+ }
+
+ if (!usage.allowed && ENFORCEMENT === 'on') {
+ return usageLimitResponse(usage)
+ }
+ }
}
if (keylessFilePartCount > 0) {
@@ -197,15 +382,18 @@ export async function POST(req: Request) {
`createChatStreamResponse - Start: model=${selectedModel.providerId}:${selectedModel.id}, searchMode=${searchMode}`
)
- const response = isGuest
- ? await createEphemeralChatStreamResponse({
- messages: Array.isArray(messages) ? messages : [],
- model: selectedModel,
- abortSignal,
- searchMode,
- chatId
- })
- : await createChatStreamResponse({
+ let response: Response
+ if (isGuest) {
+ response = await createEphemeralChatStreamResponse({
+ messages: Array.isArray(messages) ? messages : [],
+ model: selectedModel,
+ abortSignal,
+ searchMode,
+ chatId
+ })
+ } else {
+ try {
+ response = await createChatStreamResponse({
message,
model: selectedModel,
chatId,
@@ -214,8 +402,16 @@ export async function POST(req: Request) {
messageId,
abortSignal,
isNewChat,
- searchMode
+ searchMode,
+ onZeroPartError: refundUsageOnce
})
+ } catch (error) {
+ await refundUsageOnce?.()
+ throw error
+ }
+
+ if (!response.ok) await refundUsageOnce?.()
+ }
perfTime('createChatStreamResponse resolved', streamStart)
@@ -284,6 +480,7 @@ export async function POST(req: Request) {
return response
} catch (error) {
+ await refundUsageOnce?.()
console.error('API route error:', error)
return new Response('Error processing your request', {
status: 500,
diff --git a/app/api/usage/interest/route.ts b/app/api/usage/interest/route.ts
new file mode 100644
index 00000000..52b2f87f
--- /dev/null
+++ b/app/api/usage/interest/route.ts
@@ -0,0 +1,31 @@
+import { NextResponse } from 'next/server'
+
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import {
+ ENFORCEMENT,
+ isUsageBudgetAvailable,
+ recordAdditionalUsageInterest,
+ UI_ENABLED
+} from '@/lib/usage-budget'
+
+export async function POST() {
+ if (!isUsageBudgetAvailable() || ENFORCEMENT !== 'on' || !UI_ENABLED) {
+ return NextResponse.json({ error: 'Not found' }, { status: 404 })
+ }
+
+ const user = await getCurrentUser()
+ if (!user) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
+ }
+
+ try {
+ await recordAdditionalUsageInterest(user.id)
+ return NextResponse.json({ recorded: true })
+ } catch (error) {
+ console.error('Failed to record additional usage interest:', error)
+ return NextResponse.json(
+ { error: 'Failed to record interest' },
+ { status: 500 }
+ )
+ }
+}
diff --git a/app/api/usage/route.ts b/app/api/usage/route.ts
new file mode 100644
index 00000000..6704f412
--- /dev/null
+++ b/app/api/usage/route.ts
@@ -0,0 +1,39 @@
+import { NextResponse } from 'next/server'
+
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import {
+ ENFORCEMENT,
+ getUsageBudget,
+ isUsageBudgetAvailable,
+ UI_ENABLED
+} from '@/lib/usage-budget'
+
+export async function GET() {
+ if (!isUsageBudgetAvailable() || ENFORCEMENT !== 'on' || !UI_ENABLED) {
+ return NextResponse.json({ error: 'Not found' }, { status: 404 })
+ }
+
+ const user = await getCurrentUser()
+ if (!user) {
+ return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
+ }
+
+ const usage = await getUsageBudget({
+ userId: user.id,
+ userCreatedAt: user.created_at
+ })
+ if (!usage) {
+ return NextResponse.json(
+ { error: 'Usage is temporarily unavailable' },
+ { status: 503 }
+ )
+ }
+
+ return NextResponse.json({
+ ...usage,
+ resetAt: new Date(usage.resetAt).toISOString(),
+ ...(usage.refreshAt && {
+ refreshAt: new Date(usage.refreshAt).toISOString()
+ })
+ })
+}
diff --git a/app/layout.tsx b/app/layout.tsx
index 9da1ac88..f815f59f 100644
--- a/app/layout.tsx
+++ b/app/layout.tsx
@@ -7,6 +7,12 @@ import { getCurrentUserId } from '@/lib/auth/get-current-user'
import { UserProvider } from '@/lib/contexts/user-context'
import { hasSupabasePublicConfig } from '@/lib/supabase/keys'
import { createClient } from '@/lib/supabase/server'
+import {
+ ENFORCEMENT,
+ getUsageBudget,
+ isUsageBudgetAvailable,
+ UI_ENABLED
+} from '@/lib/usage-budget'
import { cn } from '@/lib/utils'
import { SidebarProvider } from '@/components/ui/sidebar'
@@ -19,6 +25,7 @@ import { KeyboardShortcutHandler } from '@/components/keyboard-shortcut-handler'
import { LibraryProvider } from '@/components/library/library-context'
import { PostHogProvider } from '@/components/posthog-provider'
import { ThemeProvider } from '@/components/theme-provider'
+import { UsageBudgetProvider } from '@/components/usage-budget-provider'
import './globals.css'
@@ -70,6 +77,31 @@ export default async function RootLayout({
}
const userId = user?.id ?? (await getCurrentUserId())
+ const usageBudgetEnabled = Boolean(
+ user &&
+ process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true' &&
+ isUsageBudgetAvailable() &&
+ ENFORCEMENT === 'on' &&
+ UI_ENABLED
+ )
+ const usageSnapshot =
+ usageBudgetEnabled && user
+ ? await getUsageBudget({
+ userId: user.id,
+ userCreatedAt: user.created_at
+ })
+ : null
+ const initialUsage = usageSnapshot
+ ? {
+ remaining: usageSnapshot.remaining,
+ limit: usageSnapshot.limit,
+ costs: usageSnapshot.costs,
+ resetAt: new Date(usageSnapshot.resetAt).toISOString(),
+ ...(usageSnapshot.refreshAt && {
+ refreshAt: new Date(usageSnapshot.refreshAt).toISOString()
+ })
+ }
+ : null
return (
<html lang="en" suppressHydrationWarning>
@@ -89,14 +121,20 @@ export default async function RootLayout({
<UserProvider hasUser={!!userId}>
<SidebarProvider defaultOpen={false}>
<LibraryProvider>
- {userId && <AppSidebar />}
- <KeyboardShortcutHandler />
- <div className="flex flex-col flex-1 min-w-0">
- <Header user={user} />
- <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
- <ArtifactRoot>{children}</ArtifactRoot>
- </main>
- </div>
+ <UsageBudgetProvider
+ key={user?.id ?? 'guest'}
+ initialUsage={initialUsage}
+ enabled={usageBudgetEnabled}
+ >
+ {userId && <AppSidebar />}
+ <KeyboardShortcutHandler />
+ <div className="flex flex-col flex-1 min-w-0">
+ <Header user={user} />
+ <main className="flex flex-1 min-h-0 min-w-0 overflow-hidden">
+ <ArtifactRoot>{children}</ArtifactRoot>
+ </main>
+ </div>
+ </UsageBudgetProvider>
</LibraryProvider>
</SidebarProvider>
</UserProvider>
diff --git a/components/__tests__/usage-budget.test.tsx b/components/__tests__/usage-budget.test.tsx
new file mode 100644
index 00000000..7bdddd88
--- /dev/null
+++ b/components/__tests__/usage-budget.test.tsx
@@ -0,0 +1,280 @@
+import React from 'react'
+
+import type { User } from '@supabase/supabase-js'
+import { fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { beforeEach, describe, expect, test, vi } from 'vitest'
+
+import {
+ UsageBudgetProvider,
+ UsageBudgetWarning,
+ useUsageBudget
+} from '@/components/usage-budget-provider'
+import { UsageDialog } from '@/components/usage-dialog'
+import { UsageLimitDialog } from '@/components/usage-limit-dialog'
+import UserMenu from '@/components/user-menu'
+
+vi.mock('next/navigation', () => ({
+ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() })
+}))
+
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({ auth: { signOut: vi.fn() } })
+}))
+
+vi.mock('@/components/account-settings-dialog', () => ({
+ AccountSettingsDialog: () => null
+}))
+
+vi.mock('@/components/external-link-items', () => ({
+ ExternalLinkItems: () => null
+}))
+
+vi.mock('@/components/ui/dropdown-menu', () => ({
+ DropdownMenu: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuContent: ({ children }: { children: React.ReactNode }) => (
+ <div role="menu">{children}</div>
+ ),
+ DropdownMenuItem: ({
+ children,
+ onSelect,
+ onClick
+ }: {
+ children: React.ReactNode
+ onSelect?: (event: { preventDefault: () => void }) => void
+ onClick?: () => void
+ }) => (
+ <button
+ role="menuitem"
+ onClick={() => {
+ onSelect?.({ preventDefault: vi.fn() })
+ onClick?.()
+ }}
+ >
+ {children}
+ </button>
+ ),
+ DropdownMenuLabel: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuSeparator: () => <hr />,
+ DropdownMenuSub: ({ children }: { children: React.ReactNode }) => children,
+ DropdownMenuSubContent: ({ children }: { children: React.ReactNode }) =>
+ children,
+ DropdownMenuSubTrigger: ({ children }: { children: React.ReactNode }) => (
+ <div>{children}</div>
+ ),
+ DropdownMenuTrigger: ({ children }: { children: React.ReactNode }) => children
+}))
+
+const user = {
+ id: 'user-1',
+ email: '[email protected]',
+ user_metadata: { full_name: 'Test Person' }
+} as unknown as User
+
+const initialUsage = {
+ remaining: 82,
+ limit: 100,
+ resetAt: '2026-10-01T00:00:00.000Z'
+}
+
+function UsageHarness() {
+ const { usage, consume, showUsageLimit } = useUsageBudget()
+
+ return (
+ <>
+ <output>{usage?.remaining ?? 'hidden'}</output>
+ <button onClick={() => consume(2)}>Consume</button>
+ <button onClick={() => showUsageLimit()}>Show limit</button>
+ </>
+ )
+}
+
+describe('usage budget UI', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.stubGlobal('fetch', vi.fn())
+ })
+
+ test('optimistically updates usage and exposes the limit dialog', () => {
+ render(
+ <UsageBudgetProvider initialUsage={initialUsage}>
+ <UsageHarness />
+ </UsageBudgetProvider>
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Consume' }))
+ expect(screen.getByText('80')).toBeInTheDocument()
+
+ fireEvent.click(screen.getByRole('button', { name: 'Show limit' }))
+ expect(
+ screen.getByRole('heading', {
+ name: "You've reached your monthly usage limit"
+ })
+ ).toBeInTheDocument()
+ })
+
+ test('keeps usage UI disabled when the provider is disabled', () => {
+ render(
+ <UsageBudgetProvider initialUsage={initialUsage} enabled={false}>
+ <UsageHarness />
+ </UsageBudgetProvider>
+ )
+
+ expect(screen.getByText('hidden')).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'Show limit' }))
+ expect(
+ screen.queryByText("You've reached your monthly usage limit")
+ ).not.toBeInTheDocument()
+ })
+
+ test('clears one account usage and adopts the next account snapshot', () => {
+ const { rerender } = render(
+ <UsageBudgetProvider initialUsage={initialUsage} enabled>
+ <UsageHarness />
+ </UsageBudgetProvider>
+ )
+
+ expect(screen.getByText('82')).toBeInTheDocument()
+
+ rerender(
+ <UsageBudgetProvider initialUsage={null} enabled={false}>
+ <UsageHarness />
+ </UsageBudgetProvider>
+ )
+ expect(screen.getByText('hidden')).toBeInTheDocument()
+
+ rerender(
+ <UsageBudgetProvider
+ initialUsage={{ ...initialUsage, remaining: 47 }}
+ enabled
+ >
+ <UsageHarness />
+ </UsageBudgetProvider>
+ )
+ expect(screen.getByText('47')).toBeInTheDocument()
+ })
+
+ test('does not sync when the account menu merely opens and syncs on Usage selection', async () => {
+ const fetchMock = vi.mocked(fetch)
+ fetchMock.mockResolvedValue(
+ new Response(
+ JSON.stringify({
+ remaining: 80,
+ limit: 100,
+ resetAt: initialUsage.resetAt
+ }),
+ { status: 200, headers: { 'Content-Type': 'application/json' } }
+ )
+ )
+
+ render(
+ <UsageBudgetProvider initialUsage={initialUsage}>
+ <UserMenu user={user} />
+ </UsageBudgetProvider>
+ )
+
+ fireEvent.click(screen.getByRole('button', { name: 'Open account menu' }))
+
+ expect(screen.getByText('Usage')).toBeInTheDocument()
+ expect(screen.getByText('82 / 100')).toBeInTheDocument()
+ expect(fetchMock).not.toHaveBeenCalled()
+
+ fireEvent.click(screen.getByText('Usage'))
+
+ await waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith('/api/usage', {
+ method: 'GET',
+ headers: { Accept: 'application/json' }
+ })
+ })
+ expect(
+ screen.getByRole('heading', { name: 'Monthly usage' })
+ ).toBeInTheDocument()
+ })
+
+ test.each([
+ [20, 'Open account menu. Monthly usage is running low.'],
+ [0, 'Open account menu. Monthly usage limit reached.']
+ ])('shows a persistent status dot at %i remaining', (remaining, label) => {
+ render(
+ <UsageBudgetProvider initialUsage={{ ...initialUsage, remaining }}>
+ <UserMenu user={user} />
+ </UsageBudgetProvider>
+ )
+
+ expect(screen.getByRole('button', { name: label })).toBeInTheDocument()
+ expect(screen.getByTestId('usage-status-dot')).toBeInTheDocument()
+ })
+
+ test('shows the English composer warning only when usage is low', () => {
+ const { rerender } = render(
+ <UsageBudgetProvider initialUsage={{ ...initialUsage, remaining: 21 }}>
+ <UsageBudgetWarning />
+ </UsageBudgetProvider>
+ )
+
+ expect(
+ screen.queryByText(/running low on monthly usage/i)
+ ).not.toBeInTheDocument()
+
+ rerender(
+ <UsageBudgetProvider
+ key="low-usage"
+ initialUsage={{ ...initialUsage, remaining: 18 }}
+ >
+ <UsageBudgetWarning />
+ </UsageBudgetProvider>
+ )
+
+ expect(screen.getByRole('status')).toHaveTextContent(
+ "You're running low on monthly usage. 18 remaining."
+ )
+ })
+
+ test('shows configured per-mode costs', () => {
+ render(
+ <UsageDialog
+ open
+ onOpenChange={vi.fn()}
+ usage={{
+ ...initialUsage,
+ costs: { quick: 3, adaptive: 5 }
+ }}
+ />
+ )
+
+ expect(screen.getByText('Adaptive')).toBeInTheDocument()
+ expect(screen.getByText(/Renews October 1/)).toBeInTheDocument()
+ expect(
+ screen.getByText(
+ 'Usage renews monthly based on when your account was created.'
+ )
+ ).toBeInTheDocument()
+ expect(screen.getByText('3 per message')).toBeInTheDocument()
+ expect(screen.getByText('5 per message')).toBeInTheDocument()
+ })
+
+ test('records interest from the limit dialog', async () => {
+ const fetchMock = vi.mocked(fetch)
+ fetchMock.mockResolvedValue(new Response(null, { status: 204 }))
+
+ render(
+ <UsageLimitDialog
+ open
+ onOpenChange={vi.fn()}
+ resetAt={initialUsage.resetAt}
+ />
+ )
+
+ expect(
+ screen.getByText(/Your usage renews on October 1/)
+ ).toBeInTheDocument()
+ fireEvent.click(screen.getByRole('button', { name: 'I need more usage' }))
+
+ await waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith('/api/usage/interest', {
+ method: 'POST'
+ })
+ })
+ expect(screen.getByRole('button', { name: 'Recorded' })).toBeDisabled()
+ })
+})
diff --git a/components/chat.tsx b/components/chat.tsx
index 15182d2b..92e63a51 100644
--- a/components/chat.tsx
+++ b/components/chat.tsx
@@ -39,6 +39,7 @@ import { ChatMessages } from './chat-messages'
import { ChatPanel } from './chat-panel'
import { DragOverlay } from './drag-overlay'
import { ErrorModal } from './error-modal'
+import { UsageBudgetWarning, useUsageBudget } from './usage-budget-provider'
// Define section structure
interface ChatSection {
@@ -65,6 +66,13 @@ export function Chat({
modelSelectorData?: ModelSelectorData
}) {
const router = useRouter()
+ const {
+ enabled: usageBudgetEnabled,
+ costs: usageCosts,
+ consume: consumeUsage,
+ refreshUsage,
+ showUsageLimit
+ } = useUsageBudget()
// Generate a stable chatId on the client side
// - If providedId exists (e.g., /search/[id]), use it for existing chats
@@ -142,7 +150,7 @@ export function Chat({
id: chatId, // use the client-generated or provided chatId
transport: new DefaultChatTransport({
api: '/api/chat',
- prepareSendMessagesRequest: ({ messages, trigger, messageId }) => {
+ prepareSendMessagesRequest: ({ messages, trigger, messageId, body }) => {
// Simplify by passing AI SDK's default trigger values directly
const lastMessage = messages[messages.length - 1]
const messageToRegenerate =
@@ -152,6 +160,7 @@ export function Chat({
return {
body: {
+ ...body,
trigger, // Use AI SDK's default trigger value directly
chatId: chatId,
messageId,
@@ -176,6 +185,7 @@ export function Chat({
messages: savedMessages,
onFinish: ({ message }) => {
isStreamingRef.current = false
+ if (usageBudgetEnabled) void refreshUsage()
window.dispatchEvent(new CustomEvent('chat-history-updated'))
const summary = summarizeGenui(getTextFromParts(message.parts))
@@ -187,7 +197,19 @@ export function Chat({
isStreamingRef.current = false
const publicError = toPublicErrorPayload(error)
- if (publicError.type === 'rate-limit') {
+ if (
+ usageBudgetEnabled &&
+ publicError.code === 'usage_limit' &&
+ publicError.reason !== 'hourly'
+ ) {
+ const resetAt = publicError.resetAt
+ ? new Date(publicError.resetAt).toISOString()
+ : undefined
+ void refreshUsage().then(usage => {
+ showUsageLimit(usage?.resetAt ?? resetAt)
+ })
+ } else if (publicError.type === 'rate-limit') {
+ if (usageBudgetEnabled) void refreshUsage()
setErrorModal({
open: true,
type: 'rate-limit',
@@ -195,18 +217,21 @@ export function Chat({
details: getPublicRateLimitDetails(publicError)
})
} else if (publicError.type === 'auth') {
+ if (usageBudgetEnabled) void refreshUsage()
setErrorModal({
open: true,
type: 'auth',
message: publicError.error
})
} else if (publicError.type === 'forbidden') {
+ if (usageBudgetEnabled) void refreshUsage()
setErrorModal({
open: true,
type: 'forbidden',
message: publicError.error
})
} else {
+ if (usageBudgetEnabled) void refreshUsage()
toast.error(publicError.error)
}
},
@@ -217,7 +242,7 @@ export function Chat({
// Keep all request entry points reflected in isStreamingRef so downstream
// action handlers can reliably reject overlapping sends.
const safeSendMessage = useCallback<typeof sendMessage>(
- (...args) => {
+ (message, options) => {
if (isCurrentAdaptiveModeAuthBlocked()) {
showAdaptiveModeAuthModal()
return Promise.resolve()
@@ -225,17 +250,48 @@ export function Chat({
isStreamingRef.current = true
try {
- return sendMessage(...args)
+ const tracksUsage = isCloudDeployment && !isGuest
+ const request = sendMessage(
+ message,
+ tracksUsage
+ ? {
+ ...options,
+ body: {
+ ...options?.body,
+ usageAttemptId: generateId()
+ }
+ }
+ : options
+ )
+
+ if (tracksUsage && usageBudgetEnabled) {
+ consumeUsage(
+ getCookie('searchMode') === 'adaptive'
+ ? usageCosts.adaptive
+ : usageCosts.quick
+ )
+ }
+
+ return request
} catch (error) {
isStreamingRef.current = false
throw error
}
},
- [sendMessage, isCurrentAdaptiveModeAuthBlocked, showAdaptiveModeAuthModal]
+ [
+ consumeUsage,
+ isCloudDeployment,
+ isCurrentAdaptiveModeAuthBlocked,
+ isGuest,
+ sendMessage,
+ showAdaptiveModeAuthModal,
+ usageBudgetEnabled,
+ usageCosts
+ ]
)
const safeRegenerate = useCallback(
- async (...args: Parameters<typeof regenerate>) => {
+ async (options?: Parameters<typeof regenerate>[0]) => {
if (isCurrentAdaptiveModeAuthBlocked()) {
showAdaptiveModeAuthModal()
return
@@ -243,13 +299,43 @@ export function Chat({
isStreamingRef.current = true
try {
- return await regenerate(...args)
+ const tracksUsage = isCloudDeployment && !isGuest
+ const request = regenerate(
+ tracksUsage
+ ? {
+ ...options,
+ body: {
+ ...options?.body,
+ usageAttemptId: generateId()
+ }
+ }
+ : options
+ )
+
+ if (tracksUsage && usageBudgetEnabled) {
+ consumeUsage(
+ getCookie('searchMode') === 'adaptive'
+ ? usageCosts.adaptive
+ : usageCosts.quick
+ )
+ }
+
+ return await request
} catch (error) {
isStreamingRef.current = false
throw error
}
},
- [regenerate, isCurrentAdaptiveModeAuthBlocked, showAdaptiveModeAuthModal]
+ [
+ consumeUsage,
+ isCloudDeployment,
+ isCurrentAdaptiveModeAuthBlocked,
+ isGuest,
+ regenerate,
+ showAdaptiveModeAuthModal,
+ usageBudgetEnabled,
+ usageCosts
+ ]
)
const handleInputChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
@@ -592,6 +678,7 @@ export function Chat({
error={error}
onQuoteContext={handleQuoteContext}
/>
+ <UsageBudgetWarning />
<ChatPanel
chatId={chatId}
input={input}
diff --git a/components/usage-budget-provider.tsx b/components/usage-budget-provider.tsx
new file mode 100644
index 00000000..a45e1c4b
--- /dev/null
+++ b/components/usage-budget-provider.tsx
@@ -0,0 +1,255 @@
+'use client'
+
+import {
+ createContext,
+ type ReactNode,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState
+} from 'react'
+
+import { UsageLimitDialog } from '@/components/usage-limit-dialog'
+
+export interface UsageBudget {
+ remaining: number
+ limit: number
+ resetAt: string
+ refreshAt?: string
+ costs?: {
+ quick: number
+ adaptive: number
+ }
+}
+
+interface UsageBudgetContextValue {
+ enabled: boolean
+ usage: UsageBudget | null
+ isLow: boolean
+ isExhausted: boolean
+ costs: { quick: number; adaptive: number }
+ refreshUsage: () => Promise<UsageBudget | null>
+ consume: (amount: number) => void
+ setUsage: (usage: UsageBudget | null) => void
+ showUsageLimit: (resetAt?: string) => void
+}
+
+const noop = () => undefined
+const noopAsync = async () => null
+
+const UsageBudgetContext = createContext<UsageBudgetContextValue>({
+ enabled: false,
+ usage: null,
+ isLow: false,
+ isExhausted: false,
+ costs: { quick: 1, adaptive: 2 },
+ refreshUsage: noopAsync,
+ consume: noop,
+ setUsage: noop,
+ showUsageLimit: noop
+})
+
+function isUsageBudget(value: unknown): value is UsageBudget {
+ if (!value || typeof value !== 'object') return false
+
+ const candidate = value as Partial<UsageBudget>
+ return (
+ typeof candidate.remaining === 'number' &&
+ Number.isFinite(candidate.remaining) &&
+ typeof candidate.limit === 'number' &&
+ Number.isFinite(candidate.limit) &&
+ typeof candidate.resetAt === 'string' &&
+ (candidate.refreshAt === undefined ||
+ typeof candidate.refreshAt === 'string') &&
+ (candidate.costs === undefined ||
+ (typeof candidate.costs.quick === 'number' &&
+ Number.isFinite(candidate.costs.quick) &&
+ typeof candidate.costs.adaptive === 'number' &&
+ Number.isFinite(candidate.costs.adaptive)))
+ )
+}
+
+export function UsageBudgetProvider({
+ initialUsage,
+ enabled = initialUsage !== null,
+ children
+}: {
+ initialUsage: UsageBudget | null
+ enabled?: boolean
+ children: ReactNode
+}) {
+ const [usage, setUsage] = useState<UsageBudget | null>(
+ enabled ? initialUsage : null
+ )
+ const [limitDialogOpen, setLimitDialogOpen] = useState(false)
+ const [limitResetAt, setLimitResetAt] = useState<string | undefined>()
+ const refreshedBoundaryRef = useRef<string | null>(null)
+ const refreshingBoundaryRef = useRef(false)
+
+ const refreshUsage = useCallback(async () => {
+ if (!enabled) return null
+
+ try {
+ const response = await fetch('/api/usage', {
+ method: 'GET',
+ headers: { Accept: 'application/json' }
+ })
+
+ if (!response.ok) return null
+
+ const body: unknown = await response.json()
+ const nextUsage = isUsageBudget(body)
+ ? body
+ : body && typeof body === 'object' && 'usage' in body
+ ? (body as { usage: unknown }).usage
+ : null
+
+ if (!isUsageBudget(nextUsage)) return null
+
+ setUsage(nextUsage)
+ return nextUsage
+ } catch {
+ return null
+ }
+ }, [enabled])
+
+ useEffect(() => {
+ setUsage(enabled ? initialUsage : null)
+ if (!enabled) {
+ setLimitDialogOpen(false)
+ setLimitResetAt(undefined)
+ refreshedBoundaryRef.current = null
+ }
+ }, [enabled, initialUsage])
+
+ useEffect(() => {
+ if (!enabled || initialUsage !== null) return
+ void refreshUsage()
+ }, [enabled, initialUsage, refreshUsage])
+
+ useEffect(() => {
+ if (!enabled || !usage?.refreshAt) return
+
+ const refreshAt = usage.refreshAt
+ const refreshAtMs = new Date(refreshAt).getTime()
+ if (!Number.isFinite(refreshAtMs)) return
+
+ let timeout: number | undefined
+ let cancelled = false
+ const refreshAtBoundary = async () => {
+ if (
+ refreshedBoundaryRef.current === refreshAt ||
+ refreshingBoundaryRef.current
+ ) {
+ return
+ }
+
+ refreshingBoundaryRef.current = true
+ const refreshed = await refreshUsage()
+ refreshingBoundaryRef.current = false
+ if (cancelled) return
+
+ if (refreshed) {
+ refreshedBoundaryRef.current = refreshAt
+ } else {
+ timeout = window.setTimeout(() => {
+ void refreshAtBoundary()
+ }, 60_000)
+ }
+ }
+
+ const scheduleRefresh = () => {
+ const delay = refreshAtMs - Date.now()
+ if (delay <= 0) {
+ void refreshAtBoundary()
+ return
+ }
+
+ timeout = window.setTimeout(
+ scheduleRefresh,
+ Math.min(delay + 1000, 2_147_483_647)
+ )
+ }
+
+ scheduleRefresh()
+ return () => {
+ cancelled = true
+ if (timeout !== undefined) window.clearTimeout(timeout)
+ }
+ }, [enabled, refreshUsage, usage?.refreshAt])
+
+ const consume = useCallback(
+ (amount: number) => {
+ if (!enabled) return
+ if (!Number.isFinite(amount) || amount <= 0) return
+
+ setUsage(current =>
+ current
+ ? { ...current, remaining: Math.max(0, current.remaining - amount) }
+ : null
+ )
+ },
+ [enabled]
+ )
+
+ const showUsageLimit = useCallback(
+ (resetAt?: string) => {
+ if (!enabled) return
+ setLimitResetAt(resetAt)
+ setLimitDialogOpen(true)
+ },
+ [enabled]
+ )
+
+ const value = useMemo<UsageBudgetContextValue>(
+ () => ({
+ enabled,
+ usage,
+ isLow: usage !== null && usage.remaining <= 20,
+ isExhausted: usage !== null && usage.remaining <= 0,
+ costs: usage?.costs ?? { quick: 1, adaptive: 2 },
+ refreshUsage,
+ consume,
+ setUsage,
+ showUsageLimit
+ }),
+ [consume, enabled, refreshUsage, showUsageLimit, usage]
+ )
+
+ return (
+ <UsageBudgetContext.Provider value={value}>
+ {children}
+ {enabled && (
+ <UsageLimitDialog
+ open={limitDialogOpen}
+ onOpenChange={setLimitDialogOpen}
+ resetAt={limitResetAt ?? usage?.resetAt}
+ />
+ )}
+ </UsageBudgetContext.Provider>
+ )
+}
+
+export function useUsageBudget() {
+ return useContext(UsageBudgetContext)
+}
+
+export function UsageBudgetWarning() {
+ const { enabled, usage, isLow } = useUsageBudget()
+
+ if (!enabled || !usage || !isLow) return null
+
+ return (
+ <p
+ className="mx-auto w-full max-w-3xl px-4 pb-2 text-sm text-destructive"
+ role="status"
+ aria-live="polite"
+ >
+ You&apos;re running low on monthly usage.{' '}
+ <span className="tabular-nums">{Math.max(0, usage.remaining)}</span>{' '}
+ remaining.
+ </p>
+ )
+}
diff --git a/components/usage-dialog.tsx b/components/usage-dialog.tsx
new file mode 100644
index 00000000..1ab816b6
--- /dev/null
+++ b/components/usage-dialog.tsx
@@ -0,0 +1,94 @@
+'use client'
+
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+
+import type { UsageBudget } from '@/components/usage-budget-provider'
+
+interface UsageDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ usage: UsageBudget
+}
+
+export function formatUsageRenewal(resetAt: string) {
+ const date = new Date(resetAt)
+ if (Number.isNaN(date.getTime())) return 'Renewal date unavailable'
+
+ return `Renews ${new Intl.DateTimeFormat('en-US', {
+ month: 'long',
+ day: 'numeric',
+ hour: 'numeric',
+ minute: '2-digit'
+ }).format(date)}`
+}
+
+export function UsageDialog({ open, onOpenChange, usage }: UsageDialogProps) {
+ const percentage =
+ usage.limit > 0
+ ? Math.min(100, Math.max(0, (usage.remaining / usage.limit) * 100))
+ : 0
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>Monthly usage</DialogTitle>
+ <DialogDescription className="sr-only">
+ Your remaining monthly usage and renewal date.
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-5">
+ <div className="space-y-2">
+ <p className="text-2xl font-semibold tracking-tight tabular-nums">
+ {usage.remaining} of {usage.limit} remaining
+ </p>
+ <div
+ className="h-2 overflow-hidden rounded-full bg-muted"
+ role="progressbar"
+ aria-label="Monthly usage remaining"
+ aria-valuemin={0}
+ aria-valuemax={Math.max(0, usage.limit)}
+ aria-valuenow={Math.max(0, usage.remaining)}
+ >
+ <div
+ className="h-full rounded-full bg-primary transition-transform duration-200 ease-out motion-reduce:transition-none"
+ style={{
+ width: '100%',
+ transform: `translateX(-${100 - percentage}%)`
+ }}
+ />
+ </div>
+ <p className="text-sm text-muted-foreground">
+ {formatUsageRenewal(usage.resetAt)}
+ </p>
+ <p className="text-sm text-muted-foreground">
+ Usage renews monthly based on when your account was created.
+ </p>
+ </div>
+
+ <div className="rounded-lg bg-muted/60 px-4 py-3 text-sm">
+ <div className="flex items-center justify-between gap-4 py-1">
+ <span>Quick</span>
+ <span className="text-muted-foreground tabular-nums">
+ {usage.costs?.quick ?? 1} per message
+ </span>
+ </div>
+ <div className="flex items-center justify-between gap-4 py-1">
+ <span>Adaptive</span>
+ <span className="text-muted-foreground tabular-nums">
+ {usage.costs?.adaptive ?? 2} per message
+ </span>
+ </div>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/usage-limit-dialog.tsx b/components/usage-limit-dialog.tsx
new file mode 100644
index 00000000..ee02fd61
--- /dev/null
+++ b/components/usage-limit-dialog.tsx
@@ -0,0 +1,92 @@
+'use client'
+
+import { useEffect, useState } from 'react'
+
+import { Button } from '@/components/ui/button'
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle
+} from '@/components/ui/dialog'
+
+import { formatUsageRenewal } from '@/components/usage-dialog'
+
+interface UsageLimitDialogProps {
+ open: boolean
+ onOpenChange: (open: boolean) => void
+ resetAt?: string
+}
+
+export function UsageLimitDialog({
+ open,
+ onOpenChange,
+ resetAt
+}: UsageLimitDialogProps) {
+ const [interestRecorded, setInterestRecorded] = useState(false)
+ const [submitting, setSubmitting] = useState(false)
+ const [error, setError] = useState(false)
+
+ useEffect(() => {
+ if (!open) {
+ setInterestRecorded(false)
+ setSubmitting(false)
+ setError(false)
+ }
+ }, [open])
+
+ const recordInterest = async () => {
+ setSubmitting(true)
+ setError(false)
+
+ try {
+ const response = await fetch('/api/usage/interest', { method: 'POST' })
+ if (!response.ok) throw new Error('Request failed')
+ setInterestRecorded(true)
+ } catch {
+ setError(true)
+ } finally {
+ setSubmitting(false)
+ }
+ }
+
+ const resetCopy = resetAt
+ ? `${formatUsageRenewal(resetAt).replace(/^Renews /, 'Your usage renews on ')}.`
+ : 'Your usage will renew at the start of your next monthly period.'
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-md">
+ <DialogHeader>
+ <DialogTitle>{"You've reached your monthly usage limit"}</DialogTitle>
+ <DialogDescription>{resetCopy}</DialogDescription>
+ </DialogHeader>
+
+ <p className="text-sm text-muted-foreground">
+ {"Additional usage isn't available yet."}
+ </p>
+
+ {error && (
+ <p className="text-sm text-destructive" role="alert">
+ {"Couldn't record your request. Please try again."}
+ </p>
+ )}
+
+ <DialogFooter>
+ <Button
+ onClick={recordInterest}
+ disabled={submitting || interestRecorded}
+ >
+ {interestRecorded
+ ? 'Recorded'
+ : submitting
+ ? 'Recording…'
+ : 'I need more usage'}
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/components/user-menu.tsx b/components/user-menu.tsx
index df546d35..243827ac 100644
--- a/components/user-menu.tsx
+++ b/components/user-menu.tsx
@@ -5,6 +5,7 @@ import { useRouter } from 'next/navigation'
import type { User } from '@supabase/supabase-js'
import {
+ IconChartBar as ChartBar,
IconLink as Link2,
IconLogout as LogOut,
IconUserCircle as UserRound
@@ -26,6 +27,8 @@ import {
} from '@/components/ui/dropdown-menu'
import { AccountSettingsDialog } from '@/components/account-settings-dialog'
+import { useUsageBudget } from '@/components/usage-budget-provider'
+import { UsageDialog } from '@/components/usage-dialog'
import { Button } from './ui/button'
import { ExternalLinkItems } from './external-link-items'
@@ -38,6 +41,8 @@ export default function UserMenu({ user }: UserMenuProps) {
const router = useRouter()
const [menuOpen, setMenuOpen] = useState(false)
const [accountOpen, setAccountOpen] = useState(false)
+ const [usageOpen, setUsageOpen] = useState(false)
+ const { usage, isLow, isExhausted, refreshUsage } = useUsageBudget()
const userName =
user.user_metadata?.full_name || user.user_metadata?.name || 'User'
const avatarUrl =
@@ -69,17 +74,42 @@ export default function UserMenu({ user }: UserMenuProps) {
window.setTimeout(() => setAccountOpen(true), 0)
}
+ const handleOpenUsage = () => {
+ setMenuOpen(false)
+ window.setTimeout(() => {
+ setUsageOpen(true)
+ void refreshUsage()
+ }, 0)
+ }
+
+ const accountMenuLabel = isExhausted
+ ? 'Open account menu. Monthly usage limit reached.'
+ : isLow
+ ? 'Open account menu. Monthly usage is running low.'
+ : 'Open account menu'
+
return (
<>
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen} modal={false}>
<DropdownMenuTrigger asChild>
- <Button variant="ghost" className="relative size-6 rounded-full">
+ <Button
+ variant="ghost"
+ className="relative size-6 rounded-full"
+ aria-label={accountMenuLabel}
+ >
<Avatar className="size-6">
<AvatarImage src={avatarUrl} alt={userName} />
<AvatarFallback>
{getInitials(userName, user.email)}
</AvatarFallback>
</Avatar>
+ {isLow && (
+ <span
+ className="absolute -right-0.5 -top-0.5 size-2 rounded-full bg-destructive ring-2 ring-background"
+ aria-hidden="true"
+ data-testid="usage-status-dot"
+ />
+ )}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent className="w-60" align="end" forceMount>
@@ -103,6 +133,20 @@ export default function UserMenu({ user }: UserMenuProps) {
<UserRound className="size-4" />
<span>Account</span>
</DropdownMenuItem>
+ {usage && (
+ <DropdownMenuItem
+ onSelect={event => {
+ event.preventDefault()
+ handleOpenUsage()
+ }}
+ >
+ <ChartBar className="size-4" />
+ <span>Usage</span>
+ <span className="ml-auto text-xs text-muted-foreground tabular-nums">
+ {usage.remaining} / {usage.limit}
+ </span>
+ </DropdownMenuItem>
+ )}
<DropdownMenuSub>
<DropdownMenuSubTrigger>
<Link2 className="size-4" />
@@ -124,6 +168,13 @@ export default function UserMenu({ user }: UserMenuProps) {
onOpenChange={setAccountOpen}
user={user}
/>
+ {usage && (
+ <UsageDialog
+ open={usageOpen}
+ onOpenChange={setUsageOpen}
+ usage={usage}
+ />
+ )}
</>
)
}
diff --git a/drizzle/0017_usage_budget.sql b/drizzle/0017_usage_budget.sql
new file mode 100644
index 00000000..cc29238e
--- /dev/null
+++ b/drizzle/0017_usage_budget.sql
@@ -0,0 +1,99 @@
+-- Durable grant authority and best-effort usage analytics. Runtime balances
+-- remain in Redis; these tables do not determine whether a request is allowed.
+CREATE TABLE IF NOT EXISTS "usage_grants" (
+ "id" varchar(191) PRIMARY KEY NOT NULL,
+ "user_id" varchar(255) NOT NULL,
+ "idempotency_key" varchar(256) NOT NULL,
+ "kind" varchar(256) NOT NULL,
+ "amount" integer NOT NULL,
+ "granted_at" timestamp DEFAULT now() NOT NULL,
+ "expires_at" timestamp NOT NULL,
+ "created_at" timestamp DEFAULT now() NOT NULL
+);--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "usage_grants_user_idempotency_idx" ON "usage_grants" USING btree ("user_id", "idempotency_key");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "usage_grants_user_expires_idx" ON "usage_grants" USING btree ("user_id", "expires_at");--> statement-breakpoint
+ALTER TABLE "usage_grants" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint
+
+CREATE TABLE IF NOT EXISTS "usage_events" (
+ "id" varchar(191) PRIMARY KEY NOT NULL,
+ "user_id" varchar(255) NOT NULL,
+ "event_type" varchar(256) NOT NULL,
+ "amount" integer NOT NULL,
+ "mode" varchar(256),
+ "attempt_id" varchar(191) NOT NULL,
+ "message_id" varchar(191),
+ "remaining" integer,
+ "created_at" timestamp DEFAULT now() NOT NULL
+);--> statement-breakpoint
+CREATE UNIQUE INDEX IF NOT EXISTS "usage_events_user_type_attempt_idx" ON "usage_events" USING btree ("user_id", "event_type", "attempt_id");--> statement-breakpoint
+CREATE INDEX IF NOT EXISTS "usage_events_user_created_idx" ON "usage_events" USING btree ("user_id", "created_at");--> statement-breakpoint
+ALTER TABLE "usage_events" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint
+
+CREATE TABLE IF NOT EXISTS "additional_usage_interest" (
+ "user_id" varchar(255) PRIMARY KEY NOT NULL,
+ "count" integer DEFAULT 1 NOT NULL,
+ "first_clicked_at" timestamp DEFAULT now() NOT NULL,
+ "last_clicked_at" timestamp DEFAULT now() NOT NULL
+);--> statement-breakpoint
+ALTER TABLE "additional_usage_interest" ENABLE ROW LEVEL SECURITY;--> statement-breakpoint
+
+DO $$
+BEGIN
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'usage_grants' AND policyname = 'users_read_own_usage_grants'
+ ) THEN
+ CREATE POLICY "users_read_own_usage_grants" ON "usage_grants"
+ AS PERMISSIVE FOR SELECT TO public
+ USING (user_id = (select current_setting('app.current_user_id', true)));
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'usage_grants' AND policyname = 'users_insert_own_usage_grants'
+ ) THEN
+ CREATE POLICY "users_insert_own_usage_grants" ON "usage_grants"
+ AS PERMISSIVE FOR INSERT TO public
+ WITH CHECK (user_id = (select current_setting('app.current_user_id', true)));
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'usage_events' AND policyname = 'users_read_own_usage_events'
+ ) THEN
+ CREATE POLICY "users_read_own_usage_events" ON "usage_events"
+ AS PERMISSIVE FOR SELECT TO public
+ USING (user_id = (select current_setting('app.current_user_id', true)));
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'usage_events' AND policyname = 'users_insert_own_usage_events'
+ ) THEN
+ CREATE POLICY "users_insert_own_usage_events" ON "usage_events"
+ AS PERMISSIVE FOR INSERT TO public
+ WITH CHECK (user_id = (select current_setting('app.current_user_id', true)));
+ END IF;
+
+ IF NOT EXISTS (
+ SELECT 1 FROM pg_policies
+ WHERE schemaname = 'public' AND tablename = 'additional_usage_interest' AND policyname = 'users_write_own_additional_usage_interest'
+ ) THEN
+ CREATE POLICY "users_write_own_additional_usage_interest" ON "additional_usage_interest"
+ AS PERMISSIVE FOR ALL TO public
+ USING (user_id = (select current_setting('app.current_user_id', true)))
+ WITH CHECK (user_id = (select current_setting('app.current_user_id', true)));
+ END IF;
+END $$;--> statement-breakpoint
+
+-- The production restricted connection uses app_user. Keep local databases
+-- without that role migratable while granting the minimum runtime privileges
+-- when it is present.
+DO $$
+BEGIN
+ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'app_user') THEN
+ GRANT SELECT, INSERT ON TABLE "usage_grants" TO app_user;
+ GRANT SELECT, INSERT ON TABLE "usage_events" TO app_user;
+ GRANT SELECT, INSERT, UPDATE ON TABLE "additional_usage_interest" TO app_user;
+ END IF;
+END $$;
diff --git a/drizzle/0018_reconcile_usage_budget_snapshot.sql b/drizzle/0018_reconcile_usage_budget_snapshot.sql
new file mode 100644
index 00000000..f71afa7c
--- /dev/null
+++ b/drizzle/0018_reconcile_usage_budget_snapshot.sql
@@ -0,0 +1,8 @@
+-- Snapshot-only migration.
+--
+-- Raw SQL migrations 0012-0017 introduced notes, files, and usage-budget
+-- tables without Drizzle snapshots. The generated 0018 snapshot reconciles
+-- that history with lib/db/schema.ts so future `drizzle-kit generate` runs do
+-- not try to recreate those tables. Their SQL changes have already been
+-- applied by the earlier migrations, so this migration intentionally does no
+-- database work.
diff --git a/drizzle/meta/0018_snapshot.json b/drizzle/meta/0018_snapshot.json
new file mode 100644
index 00000000..178a9526
--- /dev/null
+++ b/drizzle/meta/0018_snapshot.json
@@ -0,0 +1,1341 @@
+{
+ "id": "a2e83481-f715-4745-9be8-b349abc10e34",
+ "prevId": "8de1c7d9-aa51-4b93-93f1-1fc46f7aec0c",
+ "version": "7",
+ "dialect": "postgresql",
+ "tables": {
+ "public.additional_usage_interest": {
+ "name": "additional_usage_interest",
+ "schema": "",
+ "columns": {
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "count": {
+ "name": "count",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true,
+ "default": 1
+ },
+ "first_clicked_at": {
+ "name": "first_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "last_clicked_at": {
+ "name": "last_clicked_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {},
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_write_own_additional_usage_interest": {
+ "name": "users_write_own_additional_usage_interest",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.chats": {
+ "name": "chats",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "visibility": {
+ "name": "visibility",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "'private'"
+ }
+ },
+ "indexes": {
+ "chats_user_id_idx": {
+ "name": "chats_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_user_id_created_at_idx": {
+ "name": "chats_user_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_created_at_idx": {
+ "name": "chats_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "chats_id_user_id_idx": {
+ "name": "chats_id_user_id_idx",
+ "columns": [
+ {
+ "expression": "id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_chats": {
+ "name": "users_manage_own_chats",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "public_chats_readable": {
+ "name": "public_chats_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "visibility = 'public'"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.feedback": {
+ "name": "feedback",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "sentiment": {
+ "name": "sentiment",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message": {
+ "name": "message",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "page_url": {
+ "name": "page_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "user_agent": {
+ "name": "user_agent",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "feedback_user_id_idx": {
+ "name": "feedback_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "feedback_created_at_idx": {
+ "name": "feedback_created_at_idx",
+ "columns": [
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "feedback_select_policy": {
+ "name": "feedback_select_policy",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "true"
+ },
+ "anyone_can_insert_feedback": {
+ "name": "anyone_can_insert_feedback",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "true"
+ },
+ "users_anonymize_own_feedback": {
+ "name": "users_anonymize_own_feedback",
+ "as": "PERMISSIVE",
+ "for": "UPDATE",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id IS NULL"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.files": {
+ "name": "files",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "filename": {
+ "name": "filename",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "object_key": {
+ "name": "object_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "media_type": {
+ "name": "media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "size": {
+ "name": "size",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "files_user_id_idx": {
+ "name": "files_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_user_id_updated_at_idx": {
+ "name": "files_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_chat_id_idx": {
+ "name": "files_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_media_type_idx": {
+ "name": "files_media_type_idx",
+ "columns": [
+ {
+ "expression": "media_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "files_object_key_idx": {
+ "name": "files_object_key_idx",
+ "columns": [
+ {
+ "expression": "object_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "files_chat_id_chats_id_fk": {
+ "name": "files_chat_id_chats_id_fk",
+ "tableFrom": "files",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_files": {
+ "name": "users_manage_own_files",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.messages": {
+ "name": "messages",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "role": {
+ "name": "role",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "metadata": {
+ "name": "metadata",
+ "type": "jsonb",
+ "primaryKey": false,
+ "notNull": false
+ }
+ },
+ "indexes": {
+ "messages_chat_id_idx": {
+ "name": "messages_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "messages_chat_id_created_at_idx": {
+ "name": "messages_chat_id_created_at_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "messages_chat_id_chats_id_fk": {
+ "name": "messages_chat_id_chats_id_fk",
+ "tableFrom": "messages",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_chat_messages": {
+ "name": "users_manage_chat_messages",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_messages_readable": {
+ "name": "public_chat_messages_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"chats\"\n WHERE \"chats\".id = chat_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.notes": {
+ "name": "notes",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "chat_id": {
+ "name": "chat_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_message_id": {
+ "name": "source_message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "title": {
+ "name": "title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "content": {
+ "name": "content",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "updated_at": {
+ "name": "updated_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "notes_user_id_idx": {
+ "name": "notes_user_id_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_user_id_updated_at_idx": {
+ "name": "notes_user_id_updated_at_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "updated_at",
+ "isExpression": false,
+ "asc": false,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_chat_id_idx": {
+ "name": "notes_chat_id_idx",
+ "columns": [
+ {
+ "expression": "chat_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "notes_source_message_id_idx": {
+ "name": "notes_source_message_id_idx",
+ "columns": [
+ {
+ "expression": "source_message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "notes_chat_id_chats_id_fk": {
+ "name": "notes_chat_id_chats_id_fk",
+ "tableFrom": "notes",
+ "tableTo": "chats",
+ "columnsFrom": ["chat_id"],
+ "columnsTo": ["id"],
+ "onDelete": "set null",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_own_notes": {
+ "name": "users_manage_own_notes",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))",
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.parts": {
+ "name": "parts",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "order": {
+ "name": "order",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "type": {
+ "name": "type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "text_text": {
+ "name": "text_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "reasoning_text": {
+ "name": "reasoning_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_media_type": {
+ "name": "file_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_filename": {
+ "name": "file_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_url": {
+ "name": "file_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "file_key": {
+ "name": "file_key",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_source_id": {
+ "name": "source_url_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_url": {
+ "name": "source_url_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_url_title": {
+ "name": "source_url_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_source_id": {
+ "name": "source_document_source_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_media_type": {
+ "name": "source_document_media_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_title": {
+ "name": "source_document_title",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_filename": {
+ "name": "source_document_filename",
+ "type": "varchar(1024)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_url": {
+ "name": "source_document_url",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "source_document_snippet": {
+ "name": "source_document_snippet",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_tool_call_id": {
+ "name": "tool_tool_call_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_state": {
+ "name": "tool_state",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_error_text": {
+ "name": "tool_error_text",
+ "type": "text",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_input": {
+ "name": "tool_search_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_search_output": {
+ "name": "tool_search_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_input": {
+ "name": "tool_fetch_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_fetch_output": {
+ "name": "tool_fetch_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_input": {
+ "name": "tool_question_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_question_output": {
+ "name": "tool_question_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_input": {
+ "name": "tool_todoWrite_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoWrite_output": {
+ "name": "tool_todoWrite_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_input": {
+ "name": "tool_todoRead_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_todoRead_output": {
+ "name": "tool_todoRead_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_input": {
+ "name": "tool_dynamic_input",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_output": {
+ "name": "tool_dynamic_output",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_name": {
+ "name": "tool_dynamic_name",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "tool_dynamic_type": {
+ "name": "tool_dynamic_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_prefix": {
+ "name": "data_prefix",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_content": {
+ "name": "data_content",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "data_id": {
+ "name": "data_id",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "provider_metadata": {
+ "name": "provider_metadata",
+ "type": "json",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "parts_message_id_idx": {
+ "name": "parts_message_id_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "parts_message_id_order_idx": {
+ "name": "parts_message_id_order_idx",
+ "columns": [
+ {
+ "expression": "message_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "order",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {
+ "parts_message_id_messages_id_fk": {
+ "name": "parts_message_id_messages_id_fk",
+ "tableFrom": "parts",
+ "tableTo": "messages",
+ "columnsFrom": ["message_id"],
+ "columnsTo": ["id"],
+ "onDelete": "cascade",
+ "onUpdate": "no action"
+ }
+ },
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_manage_message_parts": {
+ "name": "users_manage_message_parts",
+ "as": "PERMISSIVE",
+ "for": "ALL",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )",
+ "withCheck": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".user_id = current_setting('app.current_user_id', true)\n )"
+ },
+ "public_chat_parts_readable": {
+ "name": "public_chat_parts_readable",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "EXISTS (\n SELECT 1 FROM \"messages\"\n INNER JOIN \"chats\" ON \"chats\".id = \"messages\".chat_id\n WHERE \"messages\".id = message_id\n AND \"chats\".visibility = 'public'\n )"
+ }
+ },
+ "checkConstraints": {
+ "text_text_required": {
+ "name": "text_text_required",
+ "value": "(type != 'text' OR text_text IS NOT NULL)"
+ },
+ "reasoning_text_required": {
+ "name": "reasoning_text_required",
+ "value": "(type != 'reasoning' OR reasoning_text IS NOT NULL)"
+ },
+ "file_fields_required": {
+ "name": "file_fields_required",
+ "value": "(type != 'file' OR (file_media_type IS NOT NULL AND file_filename IS NOT NULL AND (file_key IS NOT NULL OR file_url IS NOT NULL)))"
+ },
+ "tool_state_valid": {
+ "name": "tool_state_valid",
+ "value": "(tool_state IS NULL OR tool_state IN ('input-streaming', 'input-available', 'output-available', 'output-error'))"
+ },
+ "tool_fields_required": {
+ "name": "tool_fields_required",
+ "value": "(type NOT LIKE 'tool-%' OR (tool_tool_call_id IS NOT NULL AND tool_state IS NOT NULL))"
+ }
+ },
+ "isRLSEnabled": true
+ },
+ "public.usage_events": {
+ "name": "usage_events",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "event_type": {
+ "name": "event_type",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "mode": {
+ "name": "mode",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "attempt_id": {
+ "name": "attempt_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "message_id": {
+ "name": "message_id",
+ "type": "varchar(191)",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "remaining": {
+ "name": "remaining",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": false
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_events_user_type_attempt_idx": {
+ "name": "usage_events_user_type_attempt_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "event_type",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "attempt_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_events_user_created_idx": {
+ "name": "usage_events_user_created_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "created_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_events": {
+ "name": "users_read_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_events": {
+ "name": "users_insert_own_usage_events",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ },
+ "public.usage_grants": {
+ "name": "usage_grants",
+ "schema": "",
+ "columns": {
+ "id": {
+ "name": "id",
+ "type": "varchar(191)",
+ "primaryKey": true,
+ "notNull": true
+ },
+ "user_id": {
+ "name": "user_id",
+ "type": "varchar(255)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "idempotency_key": {
+ "name": "idempotency_key",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "kind": {
+ "name": "kind",
+ "type": "varchar(256)",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "amount": {
+ "name": "amount",
+ "type": "integer",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "granted_at": {
+ "name": "granted_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ },
+ "expires_at": {
+ "name": "expires_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true
+ },
+ "created_at": {
+ "name": "created_at",
+ "type": "timestamp",
+ "primaryKey": false,
+ "notNull": true,
+ "default": "now()"
+ }
+ },
+ "indexes": {
+ "usage_grants_user_idempotency_idx": {
+ "name": "usage_grants_user_idempotency_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "idempotency_key",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": true,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ },
+ "usage_grants_user_expires_idx": {
+ "name": "usage_grants_user_expires_idx",
+ "columns": [
+ {
+ "expression": "user_id",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ },
+ {
+ "expression": "expires_at",
+ "isExpression": false,
+ "asc": true,
+ "nulls": "last"
+ }
+ ],
+ "isUnique": false,
+ "concurrently": false,
+ "method": "btree",
+ "with": {}
+ }
+ },
+ "foreignKeys": {},
+ "compositePrimaryKeys": {},
+ "uniqueConstraints": {},
+ "policies": {
+ "users_read_own_usage_grants": {
+ "name": "users_read_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "SELECT",
+ "to": ["public"],
+ "using": "user_id = (select current_setting('app.current_user_id', true))"
+ },
+ "users_insert_own_usage_grants": {
+ "name": "users_insert_own_usage_grants",
+ "as": "PERMISSIVE",
+ "for": "INSERT",
+ "to": ["public"],
+ "withCheck": "user_id = (select current_setting('app.current_user_id', true))"
+ }
+ },
+ "checkConstraints": {},
+ "isRLSEnabled": true
+ }
+ },
+ "enums": {},
+ "schemas": {},
+ "sequences": {},
+ "roles": {},
+ "policies": {},
+ "views": {},
+ "_meta": {
+ "columns": {},
+ "schemas": {},
+ "tables": {}
+ }
+}
diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json
index 7ee9b94b..4dcd1fcd 100644
--- a/drizzle/meta/_journal.json
+++ b/drizzle/meta/_journal.json
@@ -120,6 +120,20 @@
"when": 1782604800001,
"tag": "0016_wrap_rls_current_setting",
"breakpoints": true
+ },
+ {
+ "idx": 17,
+ "version": "7",
+ "when": 1789527361000,
+ "tag": "0017_usage_budget",
+ "breakpoints": true
+ },
+ {
+ "idx": 18,
+ "version": "7",
+ "when": 1789527844631,
+ "tag": "0018_reconcile_usage_budget_snapshot",
+ "breakpoints": true
}
]
}
diff --git a/lib/db/schema.ts b/lib/db/schema.ts
index 177131de..7ad997d6 100644
--- a/lib/db/schema.ts
+++ b/lib/db/schema.ts
@@ -10,6 +10,7 @@ import {
pgTable,
text,
timestamp,
+ uniqueIndex,
varchar
} from 'drizzle-orm/pg-core'
@@ -392,3 +393,117 @@ export const feedback = pgTable(
).enableRLS()
export type Feedback = InferSelectModel<typeof feedback>
+
+// Usage grants are the durable authority for allowances. Redis remains the
+// runtime authority for spend and remaining usage.
+export const usageGrants = pgTable(
+ 'usage_grants',
+ {
+ id: varchar('id', { length: ID_LENGTH })
+ .primaryKey()
+ .$defaultFn(() => generateId()),
+ userId: varchar('user_id', { length: USER_ID_LENGTH }).notNull(),
+ idempotencyKey: varchar('idempotency_key', {
+ length: VARCHAR_LENGTH
+ }).notNull(),
+ kind: varchar('kind', {
+ length: VARCHAR_LENGTH,
+ enum: ['period', 'adjustment']
+ }).notNull(),
+ amount: integer('amount').notNull(),
+ grantedAt: timestamp('granted_at').notNull().defaultNow(),
+ expiresAt: timestamp('expires_at').notNull(),
+ createdAt: timestamp('created_at').notNull().defaultNow()
+ },
+ table => [
+ uniqueIndex('usage_grants_user_idempotency_idx').on(
+ table.userId,
+ table.idempotencyKey
+ ),
+ index('usage_grants_user_expires_idx').on(table.userId, table.expiresAt),
+ pgPolicy('users_read_own_usage_grants', {
+ as: 'permissive',
+ for: 'select',
+ to: 'public',
+ using: sql`user_id = (select current_setting('app.current_user_id', true))`
+ }),
+ pgPolicy('users_insert_own_usage_grants', {
+ as: 'permissive',
+ for: 'insert',
+ to: 'public',
+ withCheck: sql`user_id = (select current_setting('app.current_user_id', true))`
+ })
+ ]
+).enableRLS()
+
+export type UsageGrant = InferSelectModel<typeof usageGrants>
+
+// Usage events are best-effort analytics. They must never be used to rebuild
+// balances or decide whether a request is allowed.
+export const usageEvents = pgTable(
+ 'usage_events',
+ {
+ id: varchar('id', { length: ID_LENGTH })
+ .primaryKey()
+ .$defaultFn(() => generateId()),
+ userId: varchar('user_id', { length: USER_ID_LENGTH }).notNull(),
+ eventType: varchar('event_type', {
+ length: VARCHAR_LENGTH,
+ enum: ['spend', 'refund', 'limit_reached']
+ }).notNull(),
+ amount: integer('amount').notNull(),
+ mode: varchar('mode', {
+ length: VARCHAR_LENGTH,
+ enum: ['quick', 'adaptive']
+ }),
+ attemptId: varchar('attempt_id', { length: ID_LENGTH }).notNull(),
+ messageId: varchar('message_id', { length: ID_LENGTH }),
+ remaining: integer('remaining'),
+ createdAt: timestamp('created_at').notNull().defaultNow()
+ },
+ table => [
+ uniqueIndex('usage_events_user_type_attempt_idx').on(
+ table.userId,
+ table.eventType,
+ table.attemptId
+ ),
+ index('usage_events_user_created_idx').on(table.userId, table.createdAt),
+ pgPolicy('users_read_own_usage_events', {
+ as: 'permissive',
+ for: 'select',
+ to: 'public',
+ using: sql`user_id = (select current_setting('app.current_user_id', true))`
+ }),
+ pgPolicy('users_insert_own_usage_events', {
+ as: 'permissive',
+ for: 'insert',
+ to: 'public',
+ withCheck: sql`user_id = (select current_setting('app.current_user_id', true))`
+ })
+ ]
+).enableRLS()
+
+export type UsageEvent = InferSelectModel<typeof usageEvents>
+
+export const additionalUsageInterest = pgTable(
+ 'additional_usage_interest',
+ {
+ userId: varchar('user_id', { length: USER_ID_LENGTH }).primaryKey(),
+ count: integer('count').notNull().default(1),
+ firstClickedAt: timestamp('first_clicked_at').notNull().defaultNow(),
+ lastClickedAt: timestamp('last_clicked_at').notNull().defaultNow()
+ },
+ () => [
+ pgPolicy('users_write_own_additional_usage_interest', {
+ as: 'permissive',
+ for: 'all',
+ to: 'public',
+ using: sql`user_id = (select current_setting('app.current_user_id', true))`,
+ withCheck: sql`user_id = (select current_setting('app.current_user_id', true))`
+ })
+ ]
+).enableRLS()
+
+export type AdditionalUsageInterest = InferSelectModel<
+ typeof additionalUsageInterest
+>
diff --git a/lib/errors/__tests__/public-error.test.ts b/lib/errors/__tests__/public-error.test.ts
index c1b25820..88125b64 100644
--- a/lib/errors/__tests__/public-error.test.ts
+++ b/lib/errors/__tests__/public-error.test.ts
@@ -89,6 +89,58 @@ describe('public error mapping', () => {
)
})
+ it('preserves monthly usage-limit payloads for the dedicated dialog', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ error: 'You have reached your monthly usage limit.',
+ code: 'usage_limit',
+ type: 'rate-limit',
+ remaining: 0,
+ resetAt: 1790784000000,
+ limit: 100,
+ reason: 'monthly',
+ retryable: false
+ })
+ )
+
+ expect(payload).toMatchObject({
+ error: 'You have reached your monthly usage limit.',
+ code: 'usage_limit',
+ type: 'rate-limit',
+ remaining: 0,
+ resetAt: 1790784000000,
+ limit: 100,
+ reason: 'monthly',
+ retryable: false
+ })
+ expect(getPublicRateLimitDetails(payload)).toBe(
+ 'Your monthly usage renews at the end of your current usage period.'
+ )
+ })
+
+ it('preserves hourly usage-limit context without zeroing monthly usage', () => {
+ const payload = toPublicErrorPayload(
+ JSON.stringify({
+ error: 'You have reached the hourly usage limit.',
+ code: 'usage_limit',
+ type: 'rate-limit',
+ remaining: 80,
+ resetAt: 1790812800000,
+ retryAt: 1790730000000,
+ reason: 'hourly',
+ retryable: true
+ })
+ )
+
+ expect(payload).toMatchObject({
+ code: 'usage_limit',
+ remaining: 80,
+ reason: 'hourly',
+ retryAt: 1790730000000,
+ retryable: true
+ })
+ })
+
it('maps guest limit payloads to the auth modal path', () => {
const payload = toPublicErrorPayload(
JSON.stringify({
diff --git a/lib/errors/public-error.ts b/lib/errors/public-error.ts
index 1d94d4ae..47f7c1e4 100644
--- a/lib/errors/public-error.ts
+++ b/lib/errors/public-error.ts
@@ -7,6 +7,7 @@ export type PublicErrorCode =
| 'auth_required'
| 'bad_request'
| 'context_length'
+ | 'duplicate_attempt'
| 'forbidden'
| 'malformed_request'
| 'model_unavailable'
@@ -18,6 +19,7 @@ export type PublicErrorCode =
| 'rate_limit'
| 'tool_failed'
| 'unknown'
+ | 'usage_limit'
export type PublicErrorPayload = {
error: string
@@ -30,6 +32,8 @@ export type PublicErrorPayload = {
remaining?: number
limit?: number
mode?: string
+ reason?: 'monthly' | 'hourly'
+ retryAt?: number
}
type PublicErrorOptions = {
@@ -57,6 +61,7 @@ const PUBLIC_ERROR_CODES: ReadonlySet<string> = new Set([
'auth_required',
'bad_request',
'context_length',
+ 'duplicate_attempt',
'forbidden',
'malformed_request',
'model_unavailable',
@@ -67,7 +72,8 @@ const PUBLIC_ERROR_CODES: ReadonlySet<string> = new Set([
'provider_unavailable',
'rate_limit',
'tool_failed',
- 'unknown'
+ 'unknown',
+ 'usage_limit'
])
const PUBLIC_ERROR_TYPES: ReadonlySet<string> = new Set([
@@ -175,6 +181,10 @@ function getNumber(value: unknown): number | undefined {
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
}
+function getUsageLimitReason(value: unknown): 'monthly' | 'hourly' | undefined {
+ return value === 'monthly' || value === 'hourly' ? value : undefined
+}
+
function matchesAny(value: string, patterns: RegExp[]): boolean {
return patterns.some(pattern => pattern.test(value))
}
@@ -271,6 +281,7 @@ function typeForCode(code: PublicErrorCode): PublicErrorType {
return 'forbidden'
case 'provider_rate_limit':
case 'rate_limit':
+ case 'usage_limit':
return 'rate-limit'
default:
return 'general'
@@ -477,7 +488,9 @@ function fromParsedPayload(
resetAt: getNumber(value.resetAt),
remaining: getNumber(value.remaining),
limit: getNumber(value.limit),
- mode: getString(value.mode)
+ mode: getString(value.mode),
+ reason: getUsageLimitReason(value.reason),
+ retryAt: getNumber(value.retryAt)
}
}
@@ -554,6 +567,14 @@ export function createPublicErrorResponse(
}
export function getPublicRateLimitDetails(error: PublicErrorPayload): string {
+ if (error.code === 'usage_limit' && error.reason === 'hourly') {
+ return 'The hourly usage guard resets at the start of the next UTC hour.'
+ }
+
+ if (error.code === 'usage_limit') {
+ return 'Your monthly usage renews at the end of your current usage period.'
+ }
+
if (error.mode === 'adaptive') {
return 'The limit resets at midnight UTC. You can continue using Quick mode without restrictions.'
}
diff --git a/lib/streaming/__tests__/create-chat-stream-response.test.ts b/lib/streaming/__tests__/create-chat-stream-response.test.ts
index 2bb2dfb5..2e64df96 100644
--- a/lib/streaming/__tests__/create-chat-stream-response.test.ts
+++ b/lib/streaming/__tests__/create-chat-stream-response.test.ts
@@ -582,4 +582,17 @@ describe('createChatStreamResponse', () => {
statusMessage: EMPTY_RESPONSE_STATUS_MESSAGE
})
})
+
+ it('refunds a non-aborted stream that finishes without an answer', async () => {
+ const onZeroPartError = vi.fn(async () => undefined)
+ mocks.stream.mockResolvedValue(createFakeResult(false, []))
+
+ await createChatStreamResponse({
+ ...createConfig(),
+ onZeroPartError
+ })
+ await mocks.finishPromise
+
+ expect(onZeroPartError).toHaveBeenCalledOnce()
+ })
})
diff --git a/lib/streaming/create-chat-stream-response.ts b/lib/streaming/create-chat-stream-response.ts
index 1d34adc8..6dd91bea 100644
--- a/lib/streaming/create-chat-stream-response.ts
+++ b/lib/streaming/create-chat-stream-response.ts
@@ -34,6 +34,7 @@ import { convertDataPart } from './helpers/convert-data-part'
import { assignDataPartNonces } from './helpers/data-part-nonce'
import { dedupeAttachments } from './helpers/dedupe-attachments'
import { describeTurnInput } from './helpers/describe-turn-input'
+import { hasResponseContentPart } from './helpers/has-response-content'
import {
EMPTY_RESPONSE_STATUS_MESSAGE,
isEmptyResponse
@@ -72,7 +73,8 @@ export async function createChatStreamResponse(
messageId,
abortSignal,
isNewChat,
- searchMode
+ searchMode,
+ onZeroPartError
} = config
// Verify that chatId is provided
@@ -343,10 +345,20 @@ export async function createChatStreamResponse(
onEnd: async ({ responseMessage, isAborted }) => {
try {
perfTime('researchAgent.stream completed', llmStart)
- if (isAborted || !responseMessage) return
+ if (isAborted) return
+ if (!responseMessage) {
+ if (hasStreamError) await onZeroPartError?.()
+ return
+ }
rootOutput = getTextFromParts(responseMessage.parts) || undefined
hasEmptyResponse = isEmptyResponse(responseMessage)
+ if (
+ hasEmptyResponse ||
+ (hasStreamError && !hasResponseContentPart(responseMessage))
+ ) {
+ await onZeroPartError?.()
+ }
// Persist stream results to database
await persistStreamResults(
@@ -365,6 +377,11 @@ export async function createChatStreamResponse(
}
},
onError: (error: unknown) => {
+ hasStreamError = true
+ streamError = error
+ streamErrorWasCancelled = abortSignal?.aborted ?? false
+ streamErrorPhase = 'generation'
+
if (isToolFailureError(error)) {
console.error('Tool failure:', error)
return serializeToolFailure(error)
diff --git a/lib/streaming/helpers/__tests__/has-response-content.test.ts b/lib/streaming/helpers/__tests__/has-response-content.test.ts
new file mode 100644
index 00000000..7b639afd
--- /dev/null
+++ b/lib/streaming/helpers/__tests__/has-response-content.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from 'vitest'
+
+import { hasResponseContentPart } from '../has-response-content'
+
+describe('hasResponseContentPart', () => {
+ it.each([
+ undefined,
+ null,
+ { parts: [] },
+ { parts: [{ type: 'step-start' }] }
+ ])('treats %j as zero content', response => {
+ expect(hasResponseContentPart(response)).toBe(false)
+ })
+
+ it.each(['text', 'reasoning', 'source-url', 'tool-search'])(
+ 'counts %s as delivered content',
+ type => {
+ expect(
+ hasResponseContentPart({
+ parts: [{ type: 'step-start' }, { type }]
+ })
+ ).toBe(true)
+ }
+ )
+})
diff --git a/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts b/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts
index b21602a6..657e1ffb 100644
--- a/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts
+++ b/lib/streaming/helpers/__tests__/trim-cold-start-history.test.ts
@@ -263,7 +263,7 @@ describe('trimColdStartHistory', () => {
trimColdStartHistory(messages, { ...options, modelId: 'gpt-4o-mini' })
.trimmedAtCurrentTurn
).toBe(true)
- })
+ }, 10_000)
it('counts gpt-5.6-luna history with its own tokenizer', () => {
const arabicText = 'مرحبا بك في هذا البحث'.repeat(20)
diff --git a/lib/streaming/helpers/has-response-content.ts b/lib/streaming/helpers/has-response-content.ts
new file mode 100644
index 00000000..974fbc61
--- /dev/null
+++ b/lib/streaming/helpers/has-response-content.ts
@@ -0,0 +1,14 @@
+type ResponseWithParts = {
+ parts?: Array<{ type?: string }>
+}
+
+/**
+ * AI SDK emits a step-start marker before any observable model output. Treat
+ * that marker alone as a zero-content response, while counting every other
+ * part (text, reasoning, source, or tool) as delivered work.
+ */
+export function hasResponseContentPart(
+ response: ResponseWithParts | null | undefined
+): boolean {
+ return response?.parts?.some(part => part.type !== 'step-start') ?? false
+}
diff --git a/lib/streaming/types.ts b/lib/streaming/types.ts
index e3361008..3c068cf9 100644
--- a/lib/streaming/types.ts
+++ b/lib/streaming/types.ts
@@ -13,4 +13,5 @@ export interface BaseStreamConfig {
abortSignal?: AbortSignal
isNewChat?: boolean
searchMode?: SearchMode
+ onZeroPartError?: () => Promise<void>
}
diff --git a/lib/usage-budget/__tests__/attempt-id.test.ts b/lib/usage-budget/__tests__/attempt-id.test.ts
new file mode 100644
index 00000000..02249aed
--- /dev/null
+++ b/lib/usage-budget/__tests__/attempt-id.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+
+import { isValidUsageAttemptId } from '../attempt-id'
+
+describe('usage attempt IDs', () => {
+ it.each([
+ 'abcdefghijklmnop',
+ 'tz4p8x1n6m2k9c5v7b3q0w4r',
+ '550e8400-e29b-41d4-a716-446655440000'
+ ])('accepts a bounded opaque ID: %s', value => {
+ expect(isValidUsageAttemptId(value)).toBe(true)
+ })
+
+ it.each([
+ undefined,
+ null,
+ '',
+ 'too-short',
+ 'contains spaces and punctuation!',
+ 'a'.repeat(192)
+ ])('rejects an invalid ID: %j', value => {
+ expect(isValidUsageAttemptId(value)).toBe(false)
+ })
+})
diff --git a/lib/usage-budget/__tests__/config.test.ts b/lib/usage-budget/__tests__/config.test.ts
new file mode 100644
index 00000000..d9faa8bf
--- /dev/null
+++ b/lib/usage-budget/__tests__/config.test.ts
@@ -0,0 +1,36 @@
+import { afterEach, describe, expect, it, vi } from 'vitest'
+
+describe('usage budget config', () => {
+ const originalEnv = { ...process.env }
+
+ afterEach(() => {
+ process.env = { ...originalEnv }
+ vi.resetModules()
+ })
+
+ it('uses the phase-one defaults', async () => {
+ delete process.env.USAGE_COST_QUICK
+ delete process.env.USAGE_COST_ADAPTIVE
+ delete process.env.MONTHLY_USAGE_ALLOWANCE
+ delete process.env.HOURLY_USAGE_GUARD
+
+ const config = await import('../config')
+
+ expect(config.USAGE_COST).toEqual({ quick: 1, adaptive: 2 })
+ expect(config.MONTHLY_ALLOWANCE).toBe(100)
+ expect(config.HOURLY_GUARD).toBe(30)
+ })
+
+ it('accepts positive integer overrides and rejects invalid values', async () => {
+ process.env.USAGE_COST_QUICK = '3'
+ process.env.USAGE_COST_ADAPTIVE = '2.5'
+ process.env.MONTHLY_USAGE_ALLOWANCE = '-1'
+ process.env.HOURLY_USAGE_GUARD = 'not-a-number'
+
+ const config = await import('../config')
+
+ expect(config.USAGE_COST).toEqual({ quick: 3, adaptive: 2 })
+ expect(config.MONTHLY_ALLOWANCE).toBe(100)
+ expect(config.HOURLY_GUARD).toBe(30)
+ })
+})
diff --git a/lib/usage-budget/__tests__/gate.test.ts b/lib/usage-budget/__tests__/gate.test.ts
new file mode 100644
index 00000000..58476134
--- /dev/null
+++ b/lib/usage-budget/__tests__/gate.test.ts
@@ -0,0 +1,329 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ get: vi.fn(),
+ set: vi.fn(),
+ eval: vi.fn(),
+ hgetall: vi.fn(),
+ redisSignals: [] as AbortSignal[],
+ syncUsageGrants: vi.fn(),
+ resolveUsageAnchor: vi.fn(),
+ getCurrentUser: vi.fn()
+}))
+
+vi.mock('@upstash/redis', () => ({
+ Redis: class {
+ constructor(config: { signal?: AbortSignal }) {
+ if (config.signal) mocks.redisSignals.push(config.signal)
+ }
+
+ get = mocks.get
+ set = mocks.set
+ eval = mocks.eval
+ hgetall = mocks.hgetall
+ }
+}))
+
+vi.mock('../grants', () => ({
+ resolveUsageAnchor: mocks.resolveUsageAnchor,
+ syncUsageGrants: mocks.syncUsageGrants
+}))
+
+vi.mock('@/lib/auth/get-current-user', () => ({
+ getCurrentUser: mocks.getCurrentUser
+}))
+
+import {
+ consumeUsage,
+ getUsageBudget,
+ refundUsage,
+ USAGE_GATE_SCRIPT,
+ USAGE_REFUND_SCRIPT
+} from '../gate'
+
+describe('usage budget gate', () => {
+ const originalEnv = { ...process.env }
+ const now = new Date('2026-09-20T12:30:00.000Z')
+ const anchor = new Date('2026-01-20T12:00:00.000Z')
+ const resetAt = Date.parse('2026-10-20T12:00:00.000Z')
+
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.redisSignals.length = 0
+ process.env.MORPHIC_CLOUD_DEPLOYMENT = 'true'
+ process.env.UPSTASH_REDIS_REST_URL = 'https://redis.example.test'
+ process.env.UPSTASH_REDIS_REST_TOKEN = 'token'
+ mocks.resolveUsageAnchor.mockResolvedValue(anchor)
+ mocks.syncUsageGrants.mockResolvedValue({
+ monthly: 100,
+ monthlyExpiresAt: new Date(resetAt)
+ })
+ mocks.get.mockImplementation((key: string) => {
+ if (key.startsWith('ub:v2:g:')) return `100|${resetAt}`
+ return null
+ })
+ mocks.hgetall.mockResolvedValue({
+ period_spend_key: 'ub:v2:p:user-1:original-period',
+ hourly_spend_key: 'ub:v2:h:user-1:2026-09-20-12'
+ })
+ })
+
+ afterEach(() => {
+ process.env = { ...originalEnv }
+ vi.useRealTimers()
+ })
+
+ it('bypasses Redis outside Morphic Cloud', async () => {
+ process.env.MORPHIC_CLOUD_DEPLOYMENT = 'false'
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-1',
+ now
+ })
+
+ expect(result.allowed).toBe(true)
+ expect(result.enforced).toBe(false)
+ expect(mocks.eval).not.toHaveBeenCalled()
+ })
+
+ it('bypasses Redis when Upstash is not configured', async () => {
+ delete process.env.UPSTASH_REDIS_REST_TOKEN
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-unconfigured',
+ now
+ })
+
+ expect(result.allowed).toBe(true)
+ expect(result.enforced).toBe(false)
+ expect(mocks.eval).not.toHaveBeenCalled()
+ })
+
+ it('uses one Lua evaluation for the anniversary-period budget', async () => {
+ mocks.eval.mockResolvedValue([1, 0, 1, 1, 99, '', 1, 100, resetAt, resetAt])
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-1',
+ now
+ })
+
+ expect(result).toMatchObject({
+ allowed: true,
+ duplicate: false,
+ remaining: 99,
+ limit: 100,
+ enforced: true
+ })
+ expect(mocks.eval).toHaveBeenCalledTimes(1)
+ const [, keys, args] = mocks.eval.mock.calls[0]
+ expect(keys).toEqual([
+ `ub:v2:p:user-1:${Date.parse('2026-09-20T12:00:00.000Z')}`,
+ 'ub:v2:h:user-1:2026-09-20-12',
+ 'ub:v2:a:user-1:attempt-1',
+ `ub:v2:g:user-1:${Date.parse('2026-09-20T12:00:00.000Z')}`
+ ])
+ expect(args[5]).toBeGreaterThanOrEqual(35 * 24 * 60 * 60)
+ expect(args.slice(6)).toEqual([
+ resetAt,
+ Date.parse('2026-09-20T13:00:00.000Z')
+ ])
+ })
+
+ it('replays a cross-boundary duplicate before syncing the new grant', async () => {
+ mocks.eval.mockResolvedValue([
+ 1,
+ 1,
+ 100,
+ 1,
+ 0,
+ '',
+ 1,
+ 100,
+ Date.parse('2026-09-20T12:00:00.000Z'),
+ Date.parse('2026-09-20T12:00:00.000Z')
+ ])
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-from-previous-period',
+ now
+ })
+
+ expect(result.duplicate).toBe(true)
+ expect(mocks.eval).toHaveBeenCalledTimes(1)
+ expect(mocks.get).not.toHaveBeenCalled()
+ expect(mocks.syncUsageGrants).not.toHaveBeenCalled()
+ })
+
+ it('syncs and retries once when a new period grant is missing', async () => {
+ mocks.eval
+ .mockResolvedValueOnce([-1, 0, 0, 0, 0, '', 1, 0, resetAt, resetAt])
+ .mockResolvedValueOnce([1, 0, 1, 1, 99, '', 1, 100, resetAt, resetAt])
+ mocks.get
+ .mockResolvedValueOnce(null)
+ .mockResolvedValueOnce(`100|${resetAt}`)
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-new-period',
+ now
+ })
+
+ expect(result.remaining).toBe(99)
+ expect(mocks.syncUsageGrants).toHaveBeenCalledTimes(1)
+ expect(mocks.eval).toHaveBeenCalledTimes(2)
+ })
+
+ it('preserves monthly remaining and exposes the hourly retry boundary', async () => {
+ mocks.eval.mockResolvedValue([
+ 0,
+ 0,
+ 25,
+ 31,
+ 75,
+ 'hourly',
+ 1,
+ 100,
+ resetAt,
+ Date.parse('2026-09-20T13:00:00.000Z')
+ ])
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-hourly',
+ now
+ })
+
+ expect(result.reason).toBe('hourly')
+ expect(result.remaining).toBe(75)
+ expect(result.retryAt).toBe(Date.parse('2026-09-20T13:00:00.000Z'))
+ expect(result.resetAt).toBe(resetAt)
+ })
+
+ it('returns the anniversary reset as the snapshot refresh boundary', async () => {
+ const usage = await getUsageBudget({
+ userId: 'user-1',
+ userCreatedAt: anchor,
+ now
+ })
+
+ expect(usage).toEqual({
+ remaining: 100,
+ limit: 100,
+ resetAt,
+ refreshAt: resetAt,
+ costs: { quick: 1, adaptive: 2 }
+ })
+ })
+
+ it('fails open when trusted created_at is missing', async () => {
+ mocks.resolveUsageAnchor.mockResolvedValue(null)
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-no-anchor',
+ now
+ })
+
+ expect(result.allowed).toBe(true)
+ expect(result.enforced).toBe(false)
+ expect(result.resetAt).toBe(0)
+ expect(mocks.get).not.toHaveBeenCalled()
+ })
+
+ it('fails open when Redis fails', async () => {
+ mocks.eval.mockRejectedValue(new Error('Redis unavailable'))
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ const result = await consumeUsage({
+ userId: 'user-1',
+ mode: 'adaptive',
+ attemptId: 'attempt-2',
+ now
+ })
+
+ expect(result.allowed).toBe(true)
+ expect(result.enforced).toBe(false)
+ expect(result.cost).toBe(2)
+ errorSpy.mockRestore()
+ })
+
+ it('fails open when Redis times out', async () => {
+ vi.useFakeTimers()
+ mocks.eval.mockReturnValue(new Promise(() => {}))
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+
+ const pending = consumeUsage({
+ userId: 'user-1',
+ mode: 'quick',
+ attemptId: 'attempt-timeout',
+ now
+ })
+ await vi.advanceTimersByTimeAsync(3000)
+ const result = await pending
+
+ expect(result.allowed).toBe(true)
+ expect(result.enforced).toBe(false)
+ expect(mocks.redisSignals).toHaveLength(1)
+ expect(mocks.redisSignals[0].aborted).toBe(true)
+ errorSpy.mockRestore()
+ })
+
+ it('refunds through one idempotent Lua evaluation', async () => {
+ mocks.eval.mockResolvedValue([1, 0, 8, 4, 92, 2, 100, resetAt])
+
+ const result = await refundUsage({
+ userId: 'user-1',
+ attemptId: 'attempt-3',
+ now
+ })
+
+ expect(result).toMatchObject({
+ refunded: true,
+ duplicate: false,
+ amount: 2,
+ remaining: 92
+ })
+ expect(mocks.eval).toHaveBeenCalledTimes(1)
+ })
+
+ it('refunds the original stored period across a boundary', async () => {
+ mocks.hgetall.mockResolvedValue({
+ period_spend_key: 'ub:v2:p:user-1:original-period',
+ hourly_spend_key: 'ub:v2:h:user-1:2026-09-30-23'
+ })
+ mocks.eval.mockResolvedValue([1, 0, 8, 4, 92, 2, 100, resetAt])
+
+ await refundUsage({
+ userId: 'user-1',
+ attemptId: 'attempt-boundary',
+ now: new Date('2026-10-01T00:00:01.000Z')
+ })
+
+ const [, keys] = mocks.eval.mock.calls[0]
+ expect(keys).toEqual([
+ 'ub:v2:p:user-1:original-period',
+ 'ub:v2:h:user-1:2026-09-30-23',
+ 'ub:v2:a:user-1:attempt-boundary'
+ ])
+ })
+
+ it('keeps all gate mutations and refund deduplication inside Lua', () => {
+ expect(USAGE_GATE_SCRIPT).toContain("redis.call('HGETALL', KEYS[3])")
+ expect(USAGE_GATE_SCRIPT).toContain("'period_spend_key', KEYS[1]")
+ expect(USAGE_GATE_SCRIPT).toContain("redis.call('INCRBY'")
+ expect(USAGE_GATE_SCRIPT).toContain("redis.call('EXPIRE'")
+ expect(USAGE_REFUND_SCRIPT).toContain("'refunded', 1")
+ expect(USAGE_REFUND_SCRIPT).toContain("redis.call('DECRBY'")
+ })
+})
diff --git a/lib/usage-budget/__tests__/grants.test.ts b/lib/usage-budget/__tests__/grants.test.ts
new file mode 100644
index 00000000..4dbe6371
--- /dev/null
+++ b/lib/usage-budget/__tests__/grants.test.ts
@@ -0,0 +1,147 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ inserted: [] as Array<Record<string, unknown>>,
+ activeRows: [] as Array<{
+ amount: number
+ idempotencyKey: string
+ kind: 'period' | 'adjustment'
+ expiresAt: Date
+ }>,
+ getCurrentUser: vi.fn(),
+ trackSyncFailed: vi.fn()
+}))
+
+vi.mock('@/lib/auth/get-current-user', () => ({
+ getCurrentUser: mocks.getCurrentUser
+}))
+
+vi.mock('../analytics', () => ({
+ trackUsageGrantSyncFailed: mocks.trackSyncFailed
+}))
+
+vi.mock('@/lib/db/with-rls', () => ({
+ withRLS: vi.fn(
+ async (
+ _userId: string,
+ callback: (transaction: unknown) => Promise<unknown>
+ ) => {
+ const transaction = {
+ insert: vi.fn(() => ({
+ values: vi.fn((value: Record<string, unknown>) => {
+ mocks.inserted.push(value)
+ return { onConflictDoNothing: vi.fn().mockResolvedValue(undefined) }
+ })
+ })),
+ select: vi.fn(() => ({
+ from: vi.fn(() => ({
+ where: vi.fn().mockResolvedValue(mocks.activeRows)
+ }))
+ }))
+ }
+ return callback(transaction)
+ }
+ )
+}))
+
+import { syncUsageGrants, UsageAnchorUnavailableError } from '../grants'
+
+describe('usage grant synchronization', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mocks.inserted.length = 0
+ mocks.activeRows.length = 0
+ })
+
+ it('issues only the current anniversary grant', async () => {
+ const now = new Date('2026-09-20T13:00:00.000Z')
+ const anchor = new Date('2025-01-31T12:00:00.000Z')
+ const periodStart = new Date('2026-09-30T12:00:00.000Z')
+ // September 20 is before this month's clamped anniversary, so the active
+ // period began on August 31.
+ const actualStart = new Date('2026-08-31T12:00:00.000Z')
+ const periodEnd = periodStart
+ const idempotencyKey = `period:${actualStart.getTime()}`
+ mocks.activeRows.push({
+ amount: 100,
+ idempotencyKey,
+ kind: 'period',
+ expiresAt: periodEnd
+ })
+
+ const grants = await syncUsageGrants({
+ userId: 'user-1',
+ userCreatedAt: anchor,
+ now
+ })
+
+ expect(mocks.inserted).toHaveLength(1)
+ expect(mocks.inserted[0]).toMatchObject({
+ idempotencyKey,
+ kind: 'period',
+ amount: 100,
+ grantedAt: actualStart,
+ expiresAt: periodEnd
+ })
+ expect(grants).toEqual({
+ monthly: 100,
+ monthlyExpiresAt: periodEnd
+ })
+ })
+
+ it('excludes adjustments until their lifecycle is implemented', async () => {
+ const now = new Date('2026-09-20T13:00:00.000Z')
+ const anchor = new Date('2026-01-20T12:00:00.000Z')
+ const currentKey = `period:${Date.parse('2026-09-20T12:00:00.000Z')}`
+ const expiresAt = new Date('2026-10-20T12:00:00.000Z')
+ mocks.activeRows.push(
+ {
+ amount: 100,
+ idempotencyKey: currentKey,
+ kind: 'period',
+ expiresAt
+ },
+ {
+ amount: 50,
+ idempotencyKey: 'adjust:future-lifecycle',
+ kind: 'adjustment',
+ expiresAt
+ }
+ )
+
+ const grants = await syncUsageGrants({
+ userId: 'user-1',
+ userCreatedAt: anchor,
+ now
+ })
+
+ expect(grants.monthly).toBe(100)
+ expect(mocks.inserted).toHaveLength(1)
+ })
+
+ it('fails without inventing an anchor when created_at is unavailable', async () => {
+ await expect(
+ syncUsageGrants({
+ userId: 'user-1',
+ userCreatedAt: null,
+ now: new Date('2026-09-20T00:00:00.000Z')
+ })
+ ).rejects.toBeInstanceOf(UsageAnchorUnavailableError)
+
+ expect(mocks.inserted).toHaveLength(0)
+ expect(mocks.getCurrentUser).not.toHaveBeenCalled()
+ expect(mocks.trackSyncFailed).toHaveBeenCalledWith(
+ expect.objectContaining({ grantKind: 'period' })
+ )
+ })
+
+ it('fails for a future trusted created_at', async () => {
+ await expect(
+ syncUsageGrants({
+ userId: 'user-1',
+ userCreatedAt: new Date('2026-09-21T00:00:00.000Z'),
+ now: new Date('2026-09-20T00:00:00.000Z')
+ })
+ ).rejects.toBeInstanceOf(UsageAnchorUnavailableError)
+ })
+})
diff --git a/lib/usage-budget/__tests__/refund-handler.test.ts b/lib/usage-budget/__tests__/refund-handler.test.ts
new file mode 100644
index 00000000..60331398
--- /dev/null
+++ b/lib/usage-budget/__tests__/refund-handler.test.ts
@@ -0,0 +1,99 @@
+import { describe, expect, it, vi } from 'vitest'
+
+import { createUsageRefundHandler } from '../refund-handler'
+import type { RefundResult } from '../types'
+
+function result(overrides: Partial<RefundResult>): RefundResult {
+ return {
+ refunded: false,
+ duplicate: false,
+ monthUsed: 0,
+ hourUsed: 0,
+ remaining: 100,
+ limit: 100,
+ resetAt: 0,
+ amount: 0,
+ enforced: false,
+ ...overrides
+ }
+}
+
+describe('usage refund handler', () => {
+ it('retries a transient refund failure before returning', async () => {
+ const refund = vi
+ .fn<() => Promise<RefundResult>>()
+ .mockResolvedValueOnce(result({}))
+ .mockResolvedValueOnce(
+ result({ refunded: true, amount: 2, remaining: 98, enforced: true })
+ )
+ const onRefunded = vi.fn()
+ const handler = createUsageRefundHandler({
+ charged: true,
+ refund,
+ onRefunded
+ })
+
+ await handler()
+ await handler()
+
+ expect(refund).toHaveBeenCalledTimes(2)
+ expect(onRefunded).toHaveBeenCalledOnce()
+ })
+
+ it('remains retryable after the immediate retry budget is exhausted', async () => {
+ const refund = vi
+ .fn<() => Promise<RefundResult>>()
+ .mockResolvedValueOnce(result({}))
+ .mockResolvedValueOnce(result({}))
+ .mockResolvedValueOnce(result({ refunded: true, enforced: true }))
+ const handler = createUsageRefundHandler({
+ charged: true,
+ refund,
+ onRefunded: vi.fn()
+ })
+
+ await handler()
+ expect(refund).toHaveBeenCalledTimes(2)
+
+ await handler()
+ expect(refund).toHaveBeenCalledTimes(3)
+ })
+
+ it('treats a duplicate refund as completed', async () => {
+ const refund = vi
+ .fn<() => Promise<RefundResult>>()
+ .mockResolvedValue(result({ duplicate: true, enforced: true }))
+ const handler = createUsageRefundHandler({
+ charged: true,
+ refund,
+ onRefunded: vi.fn()
+ })
+
+ await handler()
+ await handler()
+
+ expect(refund).toHaveBeenCalledOnce()
+ })
+
+ it('shares an in-flight refund between concurrent callers', async () => {
+ let resolveRefund: ((value: RefundResult) => void) | undefined
+ const refund = vi.fn(
+ () =>
+ new Promise<RefundResult>(resolve => {
+ resolveRefund = resolve
+ })
+ )
+ const handler = createUsageRefundHandler({
+ charged: true,
+ refund,
+ onRefunded: vi.fn()
+ })
+
+ const first = handler()
+ const second = handler()
+ resolveRefund?.(result({ refunded: true, enforced: true }))
+ await Promise.all([first, second])
+
+ expect(refund).toHaveBeenCalledOnce()
+ })
+})
diff --git a/lib/usage-budget/__tests__/response.test.ts b/lib/usage-budget/__tests__/response.test.ts
new file mode 100644
index 00000000..c9bda09f
--- /dev/null
+++ b/lib/usage-budget/__tests__/response.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest'
+
+import { usageLimitResponse } from '../response'
+
+describe('usage limit response', () => {
+ it('returns a machine-readable monthly 429 response', async () => {
+ const resetAt = Date.now() + 60_000
+ const response = usageLimitResponse({
+ allowed: false,
+ duplicate: false,
+ monthUsed: 100,
+ hourUsed: 2,
+ remaining: 0,
+ reason: 'monthly',
+ retryAt: resetAt,
+ cost: 1,
+ limit: 100,
+ resetAt,
+ enforced: true
+ })
+
+ expect(response.status).toBe(429)
+ expect(response.headers.get('X-Usage-Remaining')).toBe('0')
+ await expect(response.json()).resolves.toMatchObject({
+ type: 'rate-limit',
+ code: 'usage_limit',
+ usageLimitReached: true,
+ reason: 'monthly'
+ })
+ })
+
+ it('does not disguise an hourly guard as exhausted monthly usage', async () => {
+ const resetAt = Date.now() + 10 * 24 * 60 * 60 * 1000
+ const retryAt = Date.now() + 30 * 60 * 1000
+ const response = usageLimitResponse({
+ allowed: false,
+ duplicate: false,
+ monthUsed: 25,
+ hourUsed: 31,
+ remaining: 175,
+ reason: 'hourly',
+ retryAt,
+ cost: 1,
+ limit: 200,
+ resetAt,
+ enforced: true
+ })
+
+ expect(response.headers.get('X-Usage-Remaining')).toBe('175')
+ await expect(response.json()).resolves.toMatchObject({
+ reason: 'hourly',
+ remaining: 175,
+ resetAt,
+ retryAt
+ })
+ })
+})
diff --git a/lib/usage-budget/__tests__/time.test.ts b/lib/usage-budget/__tests__/time.test.ts
new file mode 100644
index 00000000..13541e77
--- /dev/null
+++ b/lib/usage-budget/__tests__/time.test.ts
@@ -0,0 +1,53 @@
+import { describe, expect, it } from 'vitest'
+
+import { getUsagePeriod } from '../time'
+
+describe('anniversary usage periods', () => {
+ it.each([29, 30, 31])(
+ 'clamps a January %i anchor in February without drifting March',
+ day => {
+ const anchor = new Date(`2025-01-${day}T08:15:30.250Z`)
+ const period = getUsagePeriod(
+ anchor,
+ new Date('2025-02-28T09:00:00.000Z')
+ )
+
+ expect(period.periodStartAt).toBe(Date.parse('2025-02-28T08:15:30.250Z'))
+ expect(period.resetAt).toBe(Date.parse(`2025-03-${day}T08:15:30.250Z`))
+ }
+ )
+
+ it('uses February 29 in a leap year and restores the original day', () => {
+ const anchor = new Date('2024-01-31T23:45:00.000Z')
+ const period = getUsagePeriod(anchor, new Date('2024-02-29T23:45:00.000Z'))
+
+ expect(period.periodStartAt).toBe(Date.parse('2024-02-29T23:45:00.000Z'))
+ expect(period.resetAt).toBe(Date.parse('2024-03-31T23:45:00.000Z'))
+ })
+
+ it('preserves a February 29 anchor across a non-leap February', () => {
+ const anchor = new Date('2024-02-29T06:00:00.000Z')
+ const period = getUsagePeriod(anchor, new Date('2025-02-28T06:00:00.000Z'))
+
+ expect(period.periodStartAt).toBe(Date.parse('2025-02-28T06:00:00.000Z'))
+ expect(period.resetAt).toBe(Date.parse('2025-03-29T06:00:00.000Z'))
+ })
+
+ it('treats an exact anniversary as the start of the next half-open cycle', () => {
+ const anchor = new Date('2026-01-20T12:00:00.000Z')
+ const period = getUsagePeriod(anchor, new Date('2026-09-20T12:00:00.000Z'))
+
+ expect(period.periodStartAt).toBe(Date.parse('2026-09-20T12:00:00.000Z'))
+ expect(period.resetAt).toBe(Date.parse('2026-10-20T12:00:00.000Z'))
+ expect(period.periodKey).toBe(String(period.periodStartAt))
+ })
+
+ it('rejects missing temporal trust when now predates the anchor', () => {
+ expect(() =>
+ getUsagePeriod(
+ new Date('2026-09-21T00:00:00.000Z'),
+ new Date('2026-09-20T00:00:00.000Z')
+ )
+ ).toThrow(RangeError)
+ })
+})
diff --git a/lib/usage-budget/analytics.ts b/lib/usage-budget/analytics.ts
new file mode 100644
index 00000000..73eea13e
--- /dev/null
+++ b/lib/usage-budget/analytics.ts
@@ -0,0 +1,59 @@
+import { capture } from '@/lib/analytics/dispatch'
+
+import type { UsageLimitReason, UsageMode } from './types'
+
+export function trackUsageConsumed(data: {
+ userId: string
+ mode: UsageMode
+ remaining: number
+ enforcement: 'on' | 'shadow'
+}): Promise<void> {
+ return capture({
+ event: 'usage_consumed',
+ distinctId: data.userId,
+ properties: {
+ mode: data.mode,
+ remaining: data.remaining,
+ enforcement: data.enforcement
+ }
+ })
+}
+
+export function trackUsageLimitReached(data: {
+ userId: string
+ mode: UsageMode
+ reason: UsageLimitReason
+ enforcement: 'on' | 'shadow'
+}): Promise<void> {
+ return capture({
+ event: 'usage_limit_reached',
+ distinctId: data.userId,
+ properties: {
+ mode: data.mode,
+ reason: data.reason,
+ enforcement: data.enforcement
+ }
+ })
+}
+
+export function trackUsageGrantSyncFailed(data: {
+ userId: string
+ grantKind: 'period'
+ reason: string
+}): Promise<void> {
+ return capture({
+ event: 'usage_grant_sync_failed',
+ distinctId: data.userId,
+ properties: {
+ grantKind: data.grantKind,
+ reason: data.reason
+ }
+ })
+}
+
+export function trackAdditionalUsageInterest(userId: string): Promise<void> {
+ return capture({
+ event: 'additional_usage_interest',
+ distinctId: userId
+ })
+}
diff --git a/lib/usage-budget/attempt-id.ts b/lib/usage-budget/attempt-id.ts
new file mode 100644
index 00000000..495e78cd
--- /dev/null
+++ b/lib/usage-budget/attempt-id.ts
@@ -0,0 +1,5 @@
+const USAGE_ATTEMPT_ID_PATTERN = /^[A-Za-z0-9_-]{16,191}$/
+
+export function isValidUsageAttemptId(value: unknown): value is string {
+ return typeof value === 'string' && USAGE_ATTEMPT_ID_PATTERN.test(value)
+}
diff --git a/lib/usage-budget/config.ts b/lib/usage-budget/config.ts
new file mode 100644
index 00000000..3f692b73
--- /dev/null
+++ b/lib/usage-budget/config.ts
@@ -0,0 +1,46 @@
+const DEFAULT_USAGE_COST_QUICK = 1
+const DEFAULT_USAGE_COST_ADAPTIVE = 2
+const DEFAULT_MONTHLY_ALLOWANCE = 100
+const DEFAULT_HOURLY_GUARD = 30
+
+function positiveInteger(value: string | undefined, fallback: number): number {
+ if (!value) return fallback
+
+ const parsed = Number(value)
+ return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback
+}
+
+export const USAGE_COST = {
+ quick: positiveInteger(
+ process.env.USAGE_COST_QUICK,
+ DEFAULT_USAGE_COST_QUICK
+ ),
+ adaptive: positiveInteger(
+ process.env.USAGE_COST_ADAPTIVE,
+ DEFAULT_USAGE_COST_ADAPTIVE
+ )
+} as const
+
+export const MONTHLY_ALLOWANCE = positiveInteger(
+ process.env.MONTHLY_USAGE_ALLOWANCE,
+ DEFAULT_MONTHLY_ALLOWANCE
+)
+
+export const HOURLY_GUARD = positiveInteger(
+ process.env.HOURLY_USAGE_GUARD,
+ DEFAULT_HOURLY_GUARD
+)
+
+export const ENFORCEMENT =
+ process.env.USAGE_BUDGET_ENFORCEMENT === 'on' ? 'on' : 'shadow'
+
+export const UI_ENABLED = process.env.USAGE_BUDGET_UI === 'on'
+
+export function isUsageBudgetAvailable(): boolean {
+ return (
+ process.env.MORPHIC_CLOUD_DEPLOYMENT === 'true' &&
+ Boolean(
+ process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN
+ )
+ )
+}
diff --git a/lib/usage-budget/events.ts b/lib/usage-budget/events.ts
new file mode 100644
index 00000000..6a9d8e39
--- /dev/null
+++ b/lib/usage-budget/events.ts
@@ -0,0 +1,64 @@
+import { sql } from 'drizzle-orm'
+
+import { additionalUsageInterest, usageEvents } from '@/lib/db/schema'
+import { withRLS } from '@/lib/db/with-rls'
+
+import { trackAdditionalUsageInterest } from './analytics'
+import type { UsageMode } from './types'
+
+export async function recordUsageEvent(params: {
+ userId: string
+ eventType: 'spend' | 'refund' | 'limit_reached'
+ amount: number
+ mode?: UsageMode | null
+ attemptId: string
+ messageId?: string | null
+ remaining?: number | null
+}): Promise<void> {
+ try {
+ await withRLS(params.userId, async tx => {
+ await tx
+ .insert(usageEvents)
+ .values({
+ userId: params.userId,
+ eventType: params.eventType,
+ amount: params.amount,
+ mode: params.mode ?? null,
+ attemptId: params.attemptId,
+ messageId: params.messageId ?? null,
+ remaining: params.remaining ?? null
+ })
+ .onConflictDoNothing()
+ })
+ } catch (error) {
+ // These events are explicitly best-effort and never affect the Redis
+ // balance or whether a request is served.
+ console.error('Failed to record usage event:', error)
+ }
+}
+
+export async function recordAdditionalUsageInterest(
+ userId: string
+): Promise<void> {
+ const now = new Date()
+
+ await withRLS(userId, async tx => {
+ await tx
+ .insert(additionalUsageInterest)
+ .values({
+ userId,
+ count: 1,
+ firstClickedAt: now,
+ lastClickedAt: now
+ })
+ .onConflictDoUpdate({
+ target: additionalUsageInterest.userId,
+ set: {
+ count: sql`${additionalUsageInterest.count} + 1`,
+ lastClickedAt: now
+ }
+ })
+ })
+
+ await trackAdditionalUsageInterest(userId)
+}
diff --git a/lib/usage-budget/gate.ts b/lib/usage-budget/gate.ts
new file mode 100644
index 00000000..9f137ba6
--- /dev/null
+++ b/lib/usage-budget/gate.ts
@@ -0,0 +1,471 @@
+import { Redis } from '@upstash/redis'
+
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+
+import { trackUsageGrantSyncFailed } from './analytics'
+import {
+ ENFORCEMENT,
+ HOURLY_GUARD,
+ isUsageBudgetAvailable,
+ USAGE_COST
+} from './config'
+import { resolveUsageAnchor, syncUsageGrants } from './grants'
+import { getUsagePeriod, type UsagePeriod } from './time'
+import type {
+ GateResult,
+ RefundResult,
+ UsageBudgetSnapshot,
+ UsageLimitReason,
+ UsageMode
+} from './types'
+
+const REDIS_TIMEOUT_MS = 3000
+const HOURLY_TTL_SECONDS = 2 * 60 * 60
+const ATTEMPT_TTL_SECONDS = 35 * 24 * 60 * 60
+
+// KEYS: anniversary-period spend, hourly spend, attempt, active grant.
+export const USAGE_GATE_SCRIPT = `
+local existing = redis.call('HGETALL', KEYS[3])
+if #existing > 0 then
+ local values = {}
+ for index = 1, #existing, 2 do
+ values[existing[index]] = existing[index + 1]
+ end
+ return {
+ tonumber(values.allowed), 1, tonumber(values.month_used),
+ tonumber(values.hour_used), tonumber(values.remaining),
+ values.reason or '', tonumber(values.cost), tonumber(values.usage_limit),
+ tonumber(values.reset_at), tonumber(values.retry_at)
+ }
+end
+
+local function parse_grant(value)
+ if not value then return nil end
+ local separator = string.find(value, '|', 1, true)
+ if not separator then return tonumber(value) end
+ return tonumber(string.sub(value, 1, separator - 1))
+end
+
+local cost = tonumber(ARGV[1])
+local hourly_guard = tonumber(ARGV[2])
+local enforcement = ARGV[3]
+local period_ttl = tonumber(ARGV[4])
+local hour_ttl = tonumber(ARGV[5])
+local attempt_ttl = tonumber(ARGV[6])
+local reset_at = tonumber(ARGV[7])
+local hourly_retry_at = tonumber(ARGV[8])
+local usage_limit = parse_grant(redis.call('GET', KEYS[4]))
+if not usage_limit then
+ return {-1, 0, 0, 0, 0, '', cost, 0, reset_at, reset_at}
+end
+
+local month_used = tonumber(redis.call('GET', KEYS[1]) or '0')
+local hour_used = tonumber(redis.call('GET', KEYS[2]) or '0')
+local budget_exceeded = month_used + cost > usage_limit
+local hour_exceeded = hour_used + cost > hourly_guard
+local allowed = not budget_exceeded and not hour_exceeded
+local charged = allowed or enforcement == 'shadow'
+local reason = ''
+
+if budget_exceeded then reason = 'monthly'
+elseif hour_exceeded then reason = 'hourly' end
+
+if charged then
+ local month_existed = redis.call('EXISTS', KEYS[1])
+ local hour_existed = redis.call('EXISTS', KEYS[2])
+ month_used = redis.call('INCRBY', KEYS[1], cost)
+ hour_used = redis.call('INCRBY', KEYS[2], cost)
+ if month_existed == 0 then redis.call('EXPIRE', KEYS[1], period_ttl) end
+ if hour_existed == 0 then redis.call('EXPIRE', KEYS[2], hour_ttl) end
+end
+
+local remaining = math.max(0, usage_limit - month_used)
+local retry_at = reason == 'hourly' and hourly_retry_at or reset_at
+redis.call(
+ 'HSET', KEYS[3],
+ 'allowed', allowed and 1 or 0,
+ 'month_used', month_used,
+ 'hour_used', hour_used,
+ 'remaining', remaining,
+ 'reason', reason,
+ 'cost', cost,
+ 'usage_limit', usage_limit,
+ 'charged', charged and 1 or 0,
+ 'refunded', 0,
+ 'period_spend_key', KEYS[1],
+ 'hourly_spend_key', KEYS[2],
+ 'reset_at', reset_at,
+ 'retry_at', retry_at
+)
+redis.call('EXPIRE', KEYS[3], attempt_ttl)
+
+return {
+ allowed and 1 or 0, 0, month_used, hour_used, remaining,
+ reason, cost, usage_limit, reset_at, retry_at
+}
+`
+
+// KEYS are read from the immutable attempt metadata before this script runs:
+// original period spend, original hourly spend, attempt.
+export const USAGE_REFUND_SCRIPT = `
+if redis.call('EXISTS', KEYS[3]) == 0 then
+ return {0, 0, 0, 0, 0, 0, 0, 0}
+end
+
+local charged = tonumber(redis.call('HGET', KEYS[3], 'charged') or '0')
+local refunded = tonumber(redis.call('HGET', KEYS[3], 'refunded') or '0')
+local cost = tonumber(redis.call('HGET', KEYS[3], 'cost') or '0')
+local usage_limit = tonumber(redis.call('HGET', KEYS[3], 'usage_limit') or '0')
+local reset_at = tonumber(redis.call('HGET', KEYS[3], 'reset_at') or '0')
+local month_used = tonumber(redis.call('GET', KEYS[1]) or '0')
+local hour_used = tonumber(redis.call('GET', KEYS[2]) or '0')
+
+if charged == 0 then
+ return {0, 0, month_used, hour_used, math.max(0, usage_limit - month_used), 0, usage_limit, reset_at}
+end
+if refunded == 1 then
+ return {0, 1, month_used, hour_used, math.max(0, usage_limit - month_used), cost, usage_limit, reset_at}
+end
+
+if redis.call('EXISTS', KEYS[1]) == 1 then
+ month_used = redis.call('DECRBY', KEYS[1], cost)
+ if month_used < 0 then redis.call('SET', KEYS[1], 0, 'KEEPTTL'); month_used = 0 end
+end
+if redis.call('EXISTS', KEYS[2]) == 1 then
+ hour_used = redis.call('DECRBY', KEYS[2], cost)
+ if hour_used < 0 then redis.call('SET', KEYS[2], 0, 'KEEPTTL'); hour_used = 0 end
+end
+redis.call('HSET', KEYS[3], 'refunded', 1)
+
+return {1, 0, month_used, hour_used, math.max(0, usage_limit - month_used), cost, usage_limit, reset_at}
+`
+
+function getRedis(signal?: AbortSignal): Redis {
+ return new Redis({
+ url: process.env.UPSTASH_REDIS_REST_URL!,
+ token: process.env.UPSTASH_REDIS_REST_TOKEN!,
+ ...(signal ? { signal } : {})
+ })
+}
+
+async function withRedisTimeout<T>(
+ operation: (redis: Redis) => Promise<T>
+): Promise<T> {
+ const controller = new AbortController()
+ let timeout: ReturnType<typeof setTimeout> | undefined
+ try {
+ return await Promise.race([
+ operation(getRedis(controller.signal)),
+ new Promise<T>((_, reject) => {
+ timeout = setTimeout(() => {
+ const error = new Error('Usage budget Redis timeout')
+ controller.abort(error)
+ reject(error)
+ }, REDIS_TIMEOUT_MS)
+ })
+ ])
+ } finally {
+ if (timeout) clearTimeout(timeout)
+ }
+}
+
+function keysFor(userId: string, attemptId: string, period: UsagePeriod) {
+ return {
+ period,
+ periodSpend: `ub:v2:p:${userId}:${period.periodKey}`,
+ hour: `ub:v2:h:${userId}:${period.hourKey}`,
+ attempt: `ub:v2:a:${userId}:${attemptId}`,
+ periodGrant: `ub:v2:g:${userId}:${period.periodKey}`
+ }
+}
+
+function attemptKeyFor(userId: string, attemptId: string): string {
+ return `ub:v2:a:${userId}:${attemptId}`
+}
+
+function encodeGrant(amount: number, expiresAt: number): string {
+ return `${amount}|${expiresAt}`
+}
+
+function decodeGrant(value: string | null) {
+ if (value === null) return null
+ const [rawAmount, rawExpiry] = value.split('|')
+ const amount = Number(rawAmount)
+ const expiresAt = Number(rawExpiry)
+ return Number.isFinite(amount) && Number.isFinite(expiresAt)
+ ? { amount, expiresAt }
+ : null
+}
+
+async function getOrSyncGrantLimit(params: {
+ userId: string
+ periodGrantKey: string
+ userCreatedAt: Date
+ now: Date
+}): Promise<{ monthly: number; monthlyExpiresAt: number }> {
+ const cached = decodeGrant(
+ await withRedisTimeout(redis => redis.get<string>(params.periodGrantKey))
+ )
+ if (cached) {
+ return { monthly: cached.amount, monthlyExpiresAt: cached.expiresAt }
+ }
+
+ const active = await syncUsageGrants({
+ userId: params.userId,
+ userCreatedAt: params.userCreatedAt,
+ now: params.now
+ })
+ const monthlyExpiresAt = active.monthlyExpiresAt.getTime()
+ const ttl = Math.max(
+ 1,
+ Math.ceil((monthlyExpiresAt - params.now.getTime()) / 1000)
+ )
+ await withRedisTimeout(redis =>
+ redis.set(
+ params.periodGrantKey,
+ encodeGrant(active.monthly, monthlyExpiresAt),
+ { ex: ttl, nx: true }
+ )
+ )
+
+ const winner = decodeGrant(
+ await withRedisTimeout(redis => redis.get<string>(params.periodGrantKey))
+ )
+ return winner
+ ? { monthly: winner.amount, monthlyExpiresAt: winner.expiresAt }
+ : { monthly: active.monthly, monthlyExpiresAt }
+}
+
+function numberAt(values: unknown[], index: number): number {
+ const value = Number(values[index])
+ return Number.isFinite(value) ? value : 0
+}
+
+function parseGateResult(values: unknown[]): GateResult {
+ const reason = values[5]
+ return {
+ allowed: numberAt(values, 0) === 1,
+ duplicate: numberAt(values, 1) === 1,
+ monthUsed: numberAt(values, 2),
+ hourUsed: numberAt(values, 3),
+ remaining: numberAt(values, 4),
+ reason:
+ reason === 'monthly' || reason === 'hourly'
+ ? (reason as UsageLimitReason)
+ : undefined,
+ cost: numberAt(values, 6),
+ limit: numberAt(values, 7),
+ resetAt: numberAt(values, 8),
+ retryAt: numberAt(values, 9),
+ enforced: true
+ }
+}
+
+async function usageAnchor(params: {
+ userId: string
+ userCreatedAt?: Date | string | null
+}): Promise<Date | null> {
+ return resolveUsageAnchor(params.userId, params.userCreatedAt)
+}
+
+function reportMissingAnchor(userId: string): void {
+ void trackUsageGrantSyncFailed({
+ userId,
+ grantKind: 'period',
+ reason: 'missing_invalid_or_future_user_created_at'
+ })
+}
+
+export async function consumeUsage(params: {
+ userId: string
+ mode: UsageMode
+ attemptId: string
+ messageId?: string | null
+ userCreatedAt?: Date | string | null
+ now?: Date
+}): Promise<GateResult> {
+ const cost = USAGE_COST[params.mode]
+ if (!isUsageBudgetAvailable()) return failOpenGate(cost)
+
+ const now = params.now ?? new Date()
+ try {
+ const anchor = await usageAnchor(params)
+ if (!anchor || anchor.getTime() > now.getTime()) {
+ reportMissingAnchor(params.userId)
+ return failOpenGate(cost)
+ }
+
+ const period = getUsagePeriod(anchor, now)
+ const keys = keysFor(params.userId, params.attemptId, period)
+ const attemptTtl = Math.max(
+ ATTEMPT_TTL_SECONDS,
+ period.periodTtlSeconds + 24 * 60 * 60
+ )
+ const evaluateGate = () =>
+ withRedisTimeout(redis =>
+ redis.eval<unknown[], unknown[]>(
+ USAGE_GATE_SCRIPT,
+ [keys.periodSpend, keys.hour, keys.attempt, keys.periodGrant],
+ [
+ cost,
+ HOURLY_GUARD,
+ ENFORCEMENT,
+ period.periodTtlSeconds,
+ HOURLY_TTL_SECONDS,
+ attemptTtl,
+ period.resetAt,
+ period.hourlyResetAt
+ ]
+ )
+ )
+
+ // Let Lua replay a stored attempt before consulting the current period's
+ // grant. This keeps duplicate detection available across a period boundary
+ // even if synchronizing the new grant is temporarily unavailable.
+ let values = await evaluateGate()
+ if (numberAt(values, 0) === -1) {
+ await getOrSyncGrantLimit({
+ userId: params.userId,
+ periodGrantKey: keys.periodGrant,
+ userCreatedAt: anchor,
+ now
+ })
+ values = await evaluateGate()
+ }
+
+ if (numberAt(values, 0) === -1) return failOpenGate(cost)
+ return parseGateResult(values)
+ } catch (error) {
+ console.error('Usage budget check failed; allowing request:', error)
+ return failOpenGate(cost)
+ }
+}
+
+function failOpenGate(cost: number): GateResult {
+ return {
+ allowed: true,
+ duplicate: false,
+ monthUsed: 0,
+ hourUsed: 0,
+ remaining: Number.POSITIVE_INFINITY,
+ limit: Number.POSITIVE_INFINITY,
+ resetAt: 0,
+ cost,
+ enforced: false
+ }
+}
+
+function stringField(
+ value: Record<string, unknown> | null,
+ key: string
+): string | null {
+ const field = value?.[key]
+ return typeof field === 'string' && field ? field : null
+}
+
+export async function refundUsage(params: {
+ userId: string
+ attemptId: string
+ now?: Date
+}): Promise<RefundResult> {
+ if (!isUsageBudgetAvailable()) return failedRefund()
+
+ try {
+ const attemptKey = attemptKeyFor(params.userId, params.attemptId)
+ const attempt = await withRedisTimeout(redis =>
+ redis.hgetall<Record<string, unknown>>(attemptKey)
+ )
+ const periodSpend = stringField(attempt, 'period_spend_key')
+ const hourlySpend = stringField(attempt, 'hourly_spend_key')
+ if (!periodSpend || !hourlySpend) return failedRefund(true)
+
+ const values = await withRedisTimeout(redis =>
+ redis.eval<unknown[], unknown[]>(
+ USAGE_REFUND_SCRIPT,
+ [periodSpend, hourlySpend, attemptKey],
+ []
+ )
+ )
+
+ return {
+ refunded: numberAt(values, 0) === 1,
+ duplicate: numberAt(values, 1) === 1,
+ monthUsed: numberAt(values, 2),
+ hourUsed: numberAt(values, 3),
+ remaining: numberAt(values, 4),
+ amount: numberAt(values, 5),
+ limit: numberAt(values, 6),
+ resetAt: numberAt(values, 7),
+ enforced: true
+ }
+ } catch (error) {
+ console.error('Usage budget refund failed:', error)
+ return failedRefund()
+ }
+}
+
+function failedRefund(enforced = false): RefundResult {
+ return {
+ refunded: false,
+ duplicate: false,
+ monthUsed: 0,
+ hourUsed: 0,
+ remaining: Number.POSITIVE_INFINITY,
+ limit: Number.POSITIVE_INFINITY,
+ resetAt: 0,
+ amount: 0,
+ enforced
+ }
+}
+
+export async function getUsageBudget(params?: {
+ userId?: string
+ userCreatedAt?: Date | string | null
+ now?: Date
+}): Promise<UsageBudgetSnapshot | null> {
+ if (!isUsageBudgetAvailable()) return null
+
+ const user = params?.userId ? null : await getCurrentUser()
+ const userId = params?.userId ?? user?.id
+ if (!userId) return null
+
+ const now = params?.now ?? new Date()
+ try {
+ const requestedCreatedAt =
+ params?.userCreatedAt !== undefined
+ ? params.userCreatedAt
+ : user?.created_at
+ const anchor = await usageAnchor({
+ userId,
+ userCreatedAt: requestedCreatedAt
+ })
+ if (!anchor || anchor.getTime() > now.getTime()) {
+ reportMissingAnchor(userId)
+ return null
+ }
+
+ const period = getUsagePeriod(anchor, now)
+ const keys = keysFor(userId, 'snapshot', period)
+ const grant = await getOrSyncGrantLimit({
+ userId,
+ periodGrantKey: keys.periodGrant,
+ userCreatedAt: anchor,
+ now
+ })
+ const used = Number(
+ (await withRedisTimeout(redis => redis.get<number>(keys.periodSpend))) ??
+ 0
+ )
+
+ return {
+ remaining: Math.max(0, grant.monthly - used),
+ limit: grant.monthly,
+ resetAt: period.resetAt,
+ refreshAt: period.resetAt,
+ costs: USAGE_COST
+ }
+ } catch (error) {
+ console.error('Failed to read usage budget:', error)
+ return null
+ }
+}
diff --git a/lib/usage-budget/grants.ts b/lib/usage-budget/grants.ts
new file mode 100644
index 00000000..ead5f9d3
--- /dev/null
+++ b/lib/usage-budget/grants.ts
@@ -0,0 +1,111 @@
+import { and, eq, gt, sql } from 'drizzle-orm'
+
+import { getCurrentUser } from '@/lib/auth/get-current-user'
+import { usageGrants } from '@/lib/db/schema'
+import { withRLS } from '@/lib/db/with-rls'
+
+import { trackUsageGrantSyncFailed } from './analytics'
+import { MONTHLY_ALLOWANCE } from './config'
+import { getUsagePeriod } from './time'
+
+export interface ActiveGrants {
+ monthly: number
+ monthlyExpiresAt: Date
+}
+
+export class UsageAnchorUnavailableError extends Error {
+ constructor() {
+ super('A trusted Supabase user creation timestamp is required')
+ this.name = 'UsageAnchorUnavailableError'
+ }
+}
+
+function parseAnchor(value: Date | string | null | undefined): Date | null {
+ if (!value) return null
+ const date = value instanceof Date ? new Date(value) : new Date(value)
+ return Number.isNaN(date.getTime()) ? null : date
+}
+
+export async function resolveUsageAnchor(
+ userId: string,
+ provided?: Date | string | null
+): Promise<Date | null> {
+ if (provided !== undefined) return parseAnchor(provided)
+
+ const user = await getCurrentUser()
+ if (!user || user.id !== userId) return null
+ return parseAnchor(user.created_at)
+}
+
+export async function syncUsageGrants(params: {
+ userId: string
+ userCreatedAt?: Date | string | null
+ now?: Date
+}): Promise<ActiveGrants> {
+ const now = params.now ?? new Date()
+ const anchor = await resolveUsageAnchor(params.userId, params.userCreatedAt)
+
+ if (!anchor || anchor.getTime() > now.getTime()) {
+ void trackUsageGrantSyncFailed({
+ userId: params.userId,
+ grantKind: 'period',
+ reason: 'missing_invalid_or_future_user_created_at'
+ })
+ throw new UsageAnchorUnavailableError()
+ }
+
+ const period = getUsagePeriod(anchor, now)
+ const periodStart = new Date(period.periodStartAt)
+ const periodEnd = new Date(period.resetAt)
+ const idempotencyKey = `period:${period.periodKey}`
+
+ return withRLS(params.userId, async tx => {
+ await tx
+ .insert(usageGrants)
+ .values({
+ userId: params.userId,
+ idempotencyKey,
+ kind: 'period',
+ amount: MONTHLY_ALLOWANCE,
+ grantedAt: periodStart,
+ expiresAt: periodEnd
+ })
+ .onConflictDoNothing()
+
+ const active = await tx
+ .select({
+ amount: usageGrants.amount,
+ idempotencyKey: usageGrants.idempotencyKey,
+ kind: usageGrants.kind,
+ expiresAt: usageGrants.expiresAt
+ })
+ .from(usageGrants)
+ .where(
+ and(
+ sql`${usageGrants.userId} = ${params.userId}`,
+ eq(usageGrants.kind, 'period'),
+ eq(usageGrants.idempotencyKey, idempotencyKey),
+ gt(usageGrants.expiresAt, now)
+ )
+ )
+
+ // Adjustment lifecycle and cache invalidation are not in Phase 1.
+ const applicable = active.filter(
+ grant =>
+ grant.kind === 'period' && grant.idempotencyKey === idempotencyKey
+ )
+ const monthly = Math.max(
+ 0,
+ applicable.reduce((sum, grant) => sum + grant.amount, 0)
+ )
+ const monthlyExpiresAt = applicable.reduce(
+ (earliest, grant) =>
+ grant.expiresAt.getTime() < earliest.getTime()
+ ? grant.expiresAt
+ : earliest,
+ periodEnd
+ )
+
+ return { monthly, monthlyExpiresAt }
+ })
+}
diff --git a/lib/usage-budget/index.ts b/lib/usage-budget/index.ts
new file mode 100644
index 00000000..90172b1f
--- /dev/null
+++ b/lib/usage-budget/index.ts
@@ -0,0 +1,26 @@
+export {
+ trackAdditionalUsageInterest,
+ trackUsageConsumed,
+ trackUsageGrantSyncFailed,
+ trackUsageLimitReached
+} from './analytics'
+export { isValidUsageAttemptId } from './attempt-id'
+export {
+ ENFORCEMENT,
+ HOURLY_GUARD,
+ isUsageBudgetAvailable,
+ MONTHLY_ALLOWANCE,
+ UI_ENABLED,
+ USAGE_COST
+} from './config'
+export { recordAdditionalUsageInterest, recordUsageEvent } from './events'
+export { consumeUsage, getUsageBudget, refundUsage } from './gate'
+export { createUsageRefundHandler } from './refund-handler'
+export { usageLimitResponse } from './response'
+export type {
+ GateResult,
+ RefundResult,
+ UsageBudgetSnapshot,
+ UsageLimitReason,
+ UsageMode
+} from './types'
diff --git a/lib/usage-budget/refund-handler.ts b/lib/usage-budget/refund-handler.ts
new file mode 100644
index 00000000..68e58ae8
--- /dev/null
+++ b/lib/usage-budget/refund-handler.ts
@@ -0,0 +1,40 @@
+import type { RefundResult } from './types'
+
+const REFUND_ATTEMPTS_PER_INVOCATION = 2
+
+export function createUsageRefundHandler(params: {
+ charged: boolean
+ refund: () => Promise<RefundResult>
+ onRefunded: (refund: RefundResult) => void
+ onError?: (error: unknown) => void
+}): () => Promise<void> {
+ let completed = false
+ let inFlight: Promise<void> | undefined
+
+ return async () => {
+ if (!params.charged || completed) return
+ if (inFlight) return inFlight
+
+ inFlight = (async () => {
+ try {
+ for (
+ let attempt = 0;
+ attempt < REFUND_ATTEMPTS_PER_INVOCATION && !completed;
+ attempt += 1
+ ) {
+ try {
+ const refund = await params.refund()
+ completed = refund.refunded || refund.duplicate
+ if (refund.refunded) params.onRefunded(refund)
+ } catch (error) {
+ params.onError?.(error)
+ }
+ }
+ } finally {
+ inFlight = undefined
+ }
+ })()
+
+ return inFlight
+ }
+}
diff --git a/lib/usage-budget/response.ts b/lib/usage-budget/response.ts
new file mode 100644
index 00000000..c53078a2
--- /dev/null
+++ b/lib/usage-budget/response.ts
@@ -0,0 +1,36 @@
+import type { GateResult } from './types'
+
+export function usageLimitResponse(result: GateResult): Response {
+ const reason = result.reason ?? 'monthly'
+ const retryAt = result.retryAt ?? result.resetAt
+ const error =
+ reason === 'hourly'
+ ? 'Too much usage in a short period. Please try again later.'
+ : 'Monthly usage limit reached.'
+
+ return new Response(
+ JSON.stringify({
+ error,
+ type: 'rate-limit',
+ code: 'usage_limit',
+ usageLimitReached: true,
+ reason,
+ remaining: result.remaining,
+ limit: result.limit,
+ resetAt: result.resetAt,
+ retryAt
+ }),
+ {
+ status: 429,
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-Usage-Limit': String(result.limit),
+ 'X-Usage-Remaining': String(result.remaining),
+ 'X-Usage-Reset': String(result.resetAt),
+ 'Retry-After': String(
+ Math.max(1, Math.ceil((retryAt - Date.now()) / 1000))
+ )
+ }
+ }
+ )
+}
diff --git a/lib/usage-budget/time.ts b/lib/usage-budget/time.ts
new file mode 100644
index 00000000..af30f3f8
--- /dev/null
+++ b/lib/usage-budget/time.ts
@@ -0,0 +1,83 @@
+export interface UsagePeriod {
+ periodKey: string
+ hourKey: string
+ periodStartAt: number
+ resetAt: number
+ hourlyResetAt: number
+ periodTtlSeconds: number
+}
+
+function daysInUtcMonth(year: number, month: number): number {
+ return new Date(Date.UTC(year, month + 1, 0)).getUTCDate()
+}
+
+function anniversaryInMonth(anchor: Date, year: number, month: number): Date {
+ const date = new Date(0)
+ date.setUTCFullYear(
+ year,
+ month,
+ Math.min(anchor.getUTCDate(), daysInUtcMonth(year, month))
+ )
+ date.setUTCHours(
+ anchor.getUTCHours(),
+ anchor.getUTCMinutes(),
+ anchor.getUTCSeconds(),
+ anchor.getUTCMilliseconds()
+ )
+ return date
+}
+
+function adjacentMonth(year: number, month: number, offset: number) {
+ const date = new Date(Date.UTC(year, month + offset, 1))
+ return { year: date.getUTCFullYear(), month: date.getUTCMonth() }
+}
+
+/**
+ * Return the user's current monthly usage cycle. Every boundary is calculated
+ * from the original Supabase creation day/time, so a February clamp never
+ * changes a day-29/30/31 user's March anchor.
+ */
+export function getUsagePeriod(anchor: Date, now = new Date()): UsagePeriod {
+ if (
+ Number.isNaN(anchor.getTime()) ||
+ Number.isNaN(now.getTime()) ||
+ now.getTime() < anchor.getTime()
+ ) {
+ throw new RangeError('A valid usage anchor at or before now is required')
+ }
+
+ const year = now.getUTCFullYear()
+ const month = now.getUTCMonth()
+ let start = anniversaryInMonth(anchor, year, month)
+
+ if (start.getTime() > now.getTime()) {
+ const previous = adjacentMonth(year, month, -1)
+ start = anniversaryInMonth(anchor, previous.year, previous.month)
+ }
+
+ // The first cycle cannot begin before the account exists.
+ if (start.getTime() < anchor.getTime()) start = new Date(anchor)
+
+ const next = adjacentMonth(start.getUTCFullYear(), start.getUTCMonth(), 1)
+ const reset = anniversaryInMonth(anchor, next.year, next.month)
+ const hourlyResetAt = Date.UTC(
+ year,
+ month,
+ now.getUTCDate(),
+ now.getUTCHours() + 1
+ )
+
+ return {
+ periodKey: String(start.getTime()),
+ hourKey: `${year}-${String(month + 1).padStart(2, '0')}-${String(
+ now.getUTCDate()
+ ).padStart(2, '0')}-${String(now.getUTCHours()).padStart(2, '0')}`,
+ periodStartAt: start.getTime(),
+ resetAt: reset.getTime(),
+ hourlyResetAt,
+ periodTtlSeconds: Math.max(
+ 1,
+ Math.ceil((reset.getTime() - now.getTime()) / 1000)
+ )
+ }
+}
diff --git a/lib/usage-budget/types.ts b/lib/usage-budget/types.ts
new file mode 100644
index 00000000..5bc88302
--- /dev/null
+++ b/lib/usage-budget/types.ts
@@ -0,0 +1,31 @@
+export type UsageMode = 'quick' | 'adaptive'
+
+export type UsageLimitReason = 'monthly' | 'hourly'
+
+export interface UsageBudgetSnapshot {
+ remaining: number
+ limit: number
+ resetAt: number
+ refreshAt?: number
+ costs?: Record<UsageMode, number>
+}
+
+export interface GateResult extends UsageBudgetSnapshot {
+ allowed: boolean
+ duplicate: boolean
+ monthUsed: number
+ hourUsed: number
+ reason?: UsageLimitReason
+ retryAt?: number
+ cost: number
+ enforced: boolean
+}
+
+export interface RefundResult extends UsageBudgetSnapshot {
+ refunded: boolean
+ duplicate: boolean
+ monthUsed: number
+ hourUsed: number
+ amount: number
+ enforced: boolean
+}