Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat: ai usage ui (#7529)

Peter Chinman768ecc438251
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index cffcc3ec33..31e62acab5 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -24,6 +24,7 @@ import {
} from '@app/features/inbox/AddInboxDialog';
import { MacroMcpSetupModal } from '@app/features/integrations/mcp-setup/MacroMcpSetupModal';
import { AiUsageLimitDialog } from '@app/features/paywall/AiUsageLimitDialog';
+import { observeAiUsageLimitMutations } from '@app/features/paywall/ai-usage-limit-handling';
import { Paywall } from '@app/features/paywall/Paywall';
import { PropertyEditorModal } from '@app/features/property/editor/PropertyEditorModal';
import { ReminderComposerModal } from '@app/features/reminders/ReminderComposerModal';
@@ -43,11 +44,7 @@ import {
import { useIsAuthenticated } from '@core/auth';
import { UserCardDrawer } from '@core/component/UserCardDrawer';
import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
-import {
- enableAiUsageBilling,
- enableDatabases,
- enableReminders,
-} from '@core/constant/featureFlags';
+import { enableDatabases, enableReminders } from '@core/constant/featureFlags';
import { usePaywallState } from '@core/constant/PaywallState';
import { attachGlobalDOMScope } from '@core/hotkey/hotkeys';
import { isMobile } from '@core/mobile/isMobile';
@@ -56,6 +53,7 @@ import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import { updateCookie } from '@core/util/cookies';
import { useUserInfoQuery } from '@queries/auth/user-info';
+import { queryClient } from '@queries/client';
import {
type RouteSectionProps,
useLocation,
@@ -171,6 +169,8 @@ function LayoutInner(props: RouteSectionProps) {
const { usageLimitOpen } = useAiUsageLimitState();
const location = useLocation();
+ onCleanup(observeAiUsageLimitMutations(queryClient));
+
useAppSquishHandlers();
// save last_path to cookie
@@ -265,11 +265,9 @@ function LayoutInner(props: RouteSectionProps) {
<Paywall />
</Suspense>
</Show>
- <ShowFeatureFlag flag={enableAiUsageBilling}>
- <Show when={usageLimitOpen()}>
- <AiUsageLimitDialog />
- </Show>
- </ShowFeatureFlag>
+ <Show when={usageLimitOpen()}>
+ <AiUsageLimitDialog />
+ </Show>
<div class="max-h-full grow flex">
<ItemDndProvider>
<Show when={isSidebarVisible()}>
diff --git a/apps/web/src/features/block-agent/context/confirm-session-control.ts b/apps/web/src/features/block-agent/context/confirm-session-control.ts
index 922f2af342..90695821b5 100644
--- a/apps/web/src/features/block-agent/context/confirm-session-control.ts
+++ b/apps/web/src/features/block-agent/context/confirm-session-control.ts
@@ -1,12 +1,14 @@
import type { AgentSession } from '@core/agent-session/AgentSession';
import type { AgentAction } from '@service-agent-harness/generated/schemas';
+import { issueSessionAction } from '../queries/issue-session-action';
+
/** HTTP acceptance only queues a control. Wait for its correlated ACP outcome. */
export async function confirmSessionControl(
session: Pick<AgentSession, 'issue' | 'snapshot' | 'subscribe'>,
action: AgentAction
): Promise<void> {
- const result = await session.issue(action);
+ const result = await issueSessionAction(session, action);
if (result.isErr())
throw new Error(result.error.map((error) => error.message).join(' '));
const actionId = result.value.actionId;
diff --git a/apps/web/src/features/block-agent/context/create-agent-session.ts b/apps/web/src/features/block-agent/context/create-agent-session.ts
index e1ddd426d6..634d7a18ed 100644
--- a/apps/web/src/features/block-agent/context/create-agent-session.ts
+++ b/apps/web/src/features/block-agent/context/create-agent-session.ts
@@ -41,6 +41,7 @@ import {
untrack,
} from 'solid-js';
import { createStore, produce, reconcile } from 'solid-js/store';
+import { issueSessionAction } from '../queries/issue-session-action';
import type { EffortSelection } from '../state/session-config';
import { configureSessionModel } from './configure-session-model';
@@ -358,14 +359,19 @@ export function createAgentSession(
loadFailed: () => failure() !== undefined,
accessDenied: () => failure() instanceof AgentSessionAccessDenied,
retry: () => void refetch(),
- issue: (action) => live()?.issue(action, { userId: options.userId() }),
+ issue: (action) => {
+ const current = live();
+ return current
+ ? issueSessionAction(current, action, { userId: options.userId() })
+ : undefined;
+ },
selectModel: async (model, effort) => {
const current = live();
if (!current) throw new Error('The agent session is not ready.');
await configureSessionModel(
{
issue: (action) =>
- current.issue(action, { userId: options.userId() }),
+ issueSessionAction(current, action, { userId: options.userId() }),
snapshot: () => current.snapshot(),
subscribe: (listener) => current.subscribe(listener),
},
diff --git a/apps/web/src/features/block-agent/context/pending-session.ts b/apps/web/src/features/block-agent/context/pending-session.ts
index 3da22ae1dc..8caede6523 100644
--- a/apps/web/src/features/block-agent/context/pending-session.ts
+++ b/apps/web/src/features/block-agent/context/pending-session.ts
@@ -20,6 +20,7 @@
* they already handle while the GET is in flight.
*/
+import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';
import { AgentSession } from '@core/agent-session/AgentSession';
import { refetchSoupEntity } from '@queries/soup/normalized-cache';
import { agentHarnessServiceClient } from '@service-agent-harness/client';
@@ -29,6 +30,7 @@ import type {
} from '@service-agent-harness/generated/schemas';
import { type Accessor, createSignal } from 'solid-js';
import { v7 as uuidv7 } from 'uuid';
+import { issueSessionAction } from '../queries/issue-session-action';
import { effortConfigOption } from '../state/session-config';
import { confirmSessionControl } from './confirm-session-control';
@@ -114,6 +116,7 @@ export function startPendingSession(
} satisfies CreateAgentSessionRequest)
.then(async (result) => {
if (result.isErr()) {
+ handleAiUsageLimitError(result.error);
setError(
result.error.map((error) => error.message).join(' ') ||
'The agent session could not be created.'
@@ -166,7 +169,8 @@ export function startPendingSession(
}
setSessionId(created);
if (prompt || options.attachments?.length) {
- const delivered = await session.issue(
+ const delivered = await issueSessionAction(
+ session,
{
type: 'prompt',
prompt,
diff --git a/apps/web/src/features/block-agent/queries/issue-session-action.test.ts b/apps/web/src/features/block-agent/queries/issue-session-action.test.ts
new file mode 100644
index 0000000000..9b650f4a66
--- /dev/null
+++ b/apps/web/src/features/block-agent/queries/issue-session-action.test.ts
@@ -0,0 +1,44 @@
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import { err, ok } from 'neverthrow';
+import { afterEach, expect, test, vi } from 'vitest';
+import { issueSessionAction } from './issue-session-action';
+
+const state = useAiUsageLimitState();
+afterEach(() => state.hideUsageLimit());
+
+test.each([
+ 'ai_allowance_exhausted',
+ 'ai_free_allowance_exhausted',
+ 'ai_overage_limit_reached',
+ 'ai_overage_payment_failed',
+] as const)(
+ 'presents a refused live session action (%s) without losing its result',
+ async (reason) => {
+ const refusal = err([
+ { code: 'AI_USAGE_LIMIT' as const, reason, message: 'Usage blocked' },
+ ]);
+ const session = { issue: vi.fn().mockResolvedValue(refusal) };
+ const action = { type: 'prompt', prompt: 'Hello' } as const;
+
+ expect(await issueSessionAction(session, action)).toBe(refusal);
+ expect(session.issue).toHaveBeenCalledWith(action);
+ expect(state.usageLimitOpen()).toBe(true);
+ expect(state.usageLimitCode()).toBe(reason);
+ }
+);
+
+test('leaves permission failures and accepted actions to their caller', async () => {
+ const failure = err([{ code: 'FORBIDDEN' as const, message: 'No access' }]);
+ const accepted = ok({ actionId: 'action', status: 'sent' as const });
+ const session = {
+ issue: vi
+ .fn()
+ .mockResolvedValueOnce(failure)
+ .mockResolvedValueOnce(accepted),
+ };
+ const action = { type: 'prompt', prompt: 'Hello' } as const;
+
+ expect(await issueSessionAction(session, action)).toBe(failure);
+ expect(await issueSessionAction(session, action)).toBe(accepted);
+ expect(state.usageLimitOpen()).toBe(false);
+});
diff --git a/apps/web/src/features/block-agent/queries/issue-session-action.ts b/apps/web/src/features/block-agent/queries/issue-session-action.ts
new file mode 100644
index 0000000000..8bbdd3fe83
--- /dev/null
+++ b/apps/web/src/features/block-agent/queries/issue-session-action.ts
@@ -0,0 +1,12 @@
+import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';
+import type { AgentSession } from '@core/agent-session/AgentSession';
+
+/** Deliver a foreground session action and present any typed quota refusal. */
+export async function issueSessionAction(
+ session: Pick<AgentSession, 'issue'>,
+ ...args: Parameters<AgentSession['issue']>
+) {
+ const result = await session.issue(...args);
+ if (result.isErr()) handleAiUsageLimitError(result.error);
+ return result;
+}
diff --git a/apps/web/src/features/block-chat/component/Chat.tsx b/apps/web/src/features/block-chat/component/Chat.tsx
index 53f533589c..268332bdda 100644
--- a/apps/web/src/features/block-chat/component/Chat.tsx
+++ b/apps/web/src/features/block-chat/component/Chat.tsx
@@ -1,3 +1,4 @@
+import { showAiUsageLimit } from '@app/features/paywall/ai-usage-limit-handling';
import type { SendBuilder } from '@block-chat/blockClient';
import { TopBar } from '@block-chat/component/TopBar';
import type { ChatData } from '@block-chat/definition';
@@ -42,7 +43,6 @@ import {
storeChatState,
} from '@core/component/AI/util/storage';
import { CustomScrollbar } from '@core/component/CustomScrollbar';
-import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
import { usePaywallState } from '@core/constant/PaywallState';
import { TOKENS } from '@core/hotkey/tokens';
import { registerScopeSignalHotkey } from '@core/hotkey/utils';
@@ -99,7 +99,6 @@ function ChatWithController(props: {
loadedInputText: string | undefined;
}) {
const { showPaywall } = usePaywallState();
- const { showUsageLimit } = useAiUsageLimitState();
const input = useChatInputContext();
const hasPaidAccess = useHasPaidAccess();
@@ -130,7 +129,7 @@ function ChatWithController(props: {
messages={props.data.chat.messages}
controllerOptions={{
onShowPaywall: showPaywall,
- onShowUsageLimit: showUsageLimit,
+ onShowUsageLimit: showAiUsageLimit,
onSwitchModel,
hasAlternateModel: () => nextModel() !== undefined,
}}
diff --git a/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
index 9498cf94eb..f524f885a5 100644
--- a/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
+++ b/apps/web/src/features/block-md/component/DocumentAiEditBar.tsx
@@ -3,14 +3,10 @@ import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownS
import clickOutside from '@core/directive/clickOutside';
import { TOKENS } from '@core/hotkey/tokens';
import SparkleIcon from '@phosphor/sparkle.svg';
-import {
- cancelAiEdit,
- requestAiEdit,
- toastAiEditResult,
-} from '@service-ai-editing/client';
import { Button, ComposerSurface, SendButton } from '@ui';
import { createSignal, Show } from 'solid-js';
import { useMarkdownDocument } from '../context/markdown-document-context';
+import { cancelAiEdit, requestAiEditWithToast } from '../queries/ai-edit';
false && clickOutside;
@@ -42,12 +38,10 @@ export function DocumentAiEditBar(props: { documentId: string }) {
collapse();
setEditing(true);
- requestAiEdit({
- documentId: props.documentId,
- prompt: value,
- })
- .then(toastAiEditResult)
- .finally(() => setEditing(false));
+ void requestAiEditWithToast(
+ { documentId: props.documentId, prompt: value },
+ () => setEditing(false)
+ );
};
const configureEditor = () =>
diff --git a/apps/web/src/features/block-md/component/MarkdownPopup.tsx b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
index d3816024b8..36dcdb8487 100644
--- a/apps/web/src/features/block-md/component/MarkdownPopup.tsx
+++ b/apps/web/src/features/block-md/component/MarkdownPopup.tsx
@@ -61,12 +61,6 @@ import SparkleIcon from '@phosphor-icons/core/bold/sparkle-bold.svg?component-so
import LoadingIcon from '@phosphor-icons/core/bold/spinner-gap-bold.svg?component-solid';
import CheckSquareIcon from '@phosphor-icons/core/regular/check-square.svg?component-solid';
import LinkIcon from '@phosphor-icons/core/regular/link.svg?component-solid';
-import {
- cancelAiEdit,
- hasActiveAiEdit,
- requestAiEdit,
- toastAiEditResult,
-} from '@service-ai-editing/client';
import { makeResizeObserver } from '@solid-primitives/resize-observer';
import { Button, Toolbar } from '@ui';
import {
@@ -89,6 +83,11 @@ import {
} from 'solid-js';
import { Dynamic } from 'solid-js/web';
import { useMarkdownDocument } from '../context/markdown-document-context';
+import {
+ cancelAiEdit,
+ hasActiveAiEdit,
+ requestAiEditWithToast,
+} from '../queries/ai-edit';
import { FormatTools } from './FormatTools';
import { TouchSelectionToolbar } from './TouchSelectionToolbar';
@@ -351,17 +350,18 @@ export function MarkdownPopup(props: {
setAiEditRunning(true);
// Fast mode: one model edits the whole document directly, no supervisor.
// Apply ops locally so the edit lands in this client's undo stack.
- requestAiEdit({
- documentId: blockId,
- prompt: `Request: ${instruction}\nUser is selecting nodes ${nodeIds.join(' ')}. Proceed with requested edit`,
- mode: 'fast',
- onOps: (ops) => applyAiOps(editor, props.lexicalMapping, ops),
- })
- .then(toastAiEditResult)
- .finally(() => {
+ void requestAiEditWithToast(
+ {
+ documentId: blockId,
+ prompt: `Request: ${instruction}\nUser is selecting nodes ${nodeIds.join(' ')}. Proceed with requested edit`,
+ mode: 'fast',
+ onOps: (ops) => applyAiOps(editor, props.lexicalMapping, ops),
+ },
+ () => {
setAiEditLocation(null);
setAiEditRunning(false);
- });
+ }
+ );
setAiEditInput('');
setAiEditDrawerOpen(false);
setPopupVisible(false);
diff --git a/apps/web/src/features/block-md/queries/ai-edit.ts b/apps/web/src/features/block-md/queries/ai-edit.ts
new file mode 100644
index 0000000000..d50d8cc4d9
--- /dev/null
+++ b/apps/web/src/features/block-md/queries/ai-edit.ts
@@ -0,0 +1,30 @@
+import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';
+import { toast } from '@core/component/Toast/Toast';
+import { type AiEditResult, requestAiEdit } from '@service-ai-editing/client';
+
+export {
+ cancelAiEdit,
+ hasActiveAiEdit,
+ requestAiEdit,
+} from '@service-ai-editing/client';
+
+/** Present edit failures at the document action boundary; cancellations stay silent. */
+export function toastAiEditResult(result: AiEditResult): void {
+ if (result.kind === 'usage-limit') {
+ handleAiUsageLimitError(result.error);
+ return;
+ }
+ if (result.kind === 'failed') toast.failure('AI edit failed');
+ if (result.kind === 'blocked') toast.failure(result.message);
+}
+
+export async function requestAiEditWithToast(
+ args: Parameters<typeof requestAiEdit>[0],
+ onSettled: () => void
+): Promise<void> {
+ try {
+ toastAiEditResult(await requestAiEdit(args));
+ } finally {
+ onSettled();
+ }
+}
diff --git a/apps/web/src/features/database-query/queries/app-query-source.ts b/apps/web/src/features/database-query/queries/app-query-source.ts
index fc7adc615d..529a27014a 100644
--- a/apps/web/src/features/database-query/queries/app-query-source.ts
+++ b/apps/web/src/features/database-query/queries/app-query-source.ts
@@ -1,3 +1,4 @@
+import { handleAiUsageLimitError } from '@app/features/paywall/ai-usage-limit-handling';
import type { TModel } from '@core/component/AI/constant';
import { databaseSqlAnswer } from '@core/database-sql/answer';
import { databaseSqlSchema } from '@core/database-sql/catalog';
@@ -64,10 +65,10 @@ function generateDatabaseQuery(
cognition.generateDatabaseQuery(input, model).mapErr((failure) =>
generationFailure(
match(failure)
- .with(
- { kind: 'service' },
- ({ errors }) => serviceError(errors).message
- )
+ .with({ kind: 'service' }, ({ errors }) => {
+ handleAiUsageLimitError(errors);
+ return serviceError(errors).message;
+ })
.with({ kind: 'interrupted' }, ({ reason }) => reason)
.exhaustive()
)
diff --git a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
index bcd4fa2f85..5330fa3f5a 100644
--- a/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
+++ b/apps/web/src/features/paywall/AiUsageLimitDialog.tsx
@@ -1,12 +1,18 @@
-import { AiUsageControls, AiUsageMeter } from '@app/features/settings/AiUsage';
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { toast } from '@core/component/Toast/Toast';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
-import { useAiBillingSummaryQuery, useChangePlanMutation } from '@queries/auth';
+import {
+ enableAiUsageBilling,
+ LOCAL_ONLY,
+ PROD_MODE_ENV,
+} from '@core/constant/featureFlags';
+import { useSettingsState } from '@core/constant/SettingsState';
+import { useAiBillingSummaryQuery } from '@queries/auth';
import type { AiDenyCode } from '@service-auth/ai-billing-types';
-import { useNavigate } from '@solidjs/router';
import { Button, Dialog, Surface } from '@ui';
import { Show, Suspense } from 'solid-js';
+import { MonthlyLimit } from '../usage/components/monthly-limit';
+import { isUsageAvailable, monthlyUsagePercent } from '../usage/core/usage';
+import { useAiUsagePreview } from './ai-usage-preview';
const TITLES: Record<AiDenyCode, string> = {
ai_allowance_exhausted: "You've used this month's included AI",
@@ -16,38 +22,31 @@ const TITLES: Record<AiDenyCode, string> = {
};
/**
- * Shown when the backend refuses an AI request with a billing code. Offers the
- * payer the same controls as Billing settings, right where they were blocked.
- * Free users have no controls; they are pointed at an upgrade instead.
+ * Shown when the backend refuses an AI request with a billing code. Shows the
+ * monthly limit and offers paid subscriptions to Free users or usage credits
+ * to paid users.
*/
export function AiUsageLimitDialog() {
const { usageLimitOpen, usageLimitCode, hideUsageLimit } =
useAiUsageLimitState();
- const analytics = useAnalytics();
- const navigate = useNavigate();
+ const { openSettings } = useSettingsState();
const summary = useAiBillingSummaryQuery({ enabled: usageLimitOpen });
- const changePlan = useChangePlanMutation();
+ const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
+ const usagePreview = useAiUsagePreview();
+ const available = () =>
+ !usagePreview.beforeLaunch() &&
+ isUsageAvailable(PROD_MODE_ENV && !LOCAL_ONLY, aiUsageBilling().enabled);
+ const usageSnapshot = () =>
+ usagePreview.withPreview(summary.isSuccess ? summary.data : undefined);
+ const freePlan = () =>
+ usageLimitCode() === 'ai_free_allowance_exhausted' ||
+ usageSnapshot()?.tier === 'free';
- const code = () => usageLimitCode() ?? 'ai_allowance_exhausted';
- const title = () => TITLES[code()];
- const free = () => code() === 'ai_free_allowance_exhausted';
- const returnUrl = () => `${window.location.origin}/app/settings/billing`;
-
- const upgradeToMax = async () => {
- try {
- await changePlan.mutateAsync({ plan: 'max' });
- analytics.track('plan_changed', { plan: 'max', from: 'usage_limit' });
- toast.success('Upgraded to Max. Send your message again.');
- hideUsageLimit();
- } catch (error) {
- console.error(error);
- toast.failure("Couldn't upgrade. Please try again from Billing.");
- }
- };
+ const title = () => TITLES[usageLimitCode() ?? 'ai_allowance_exhausted'];
return (
<Dialog
- open={usageLimitOpen()}
+ open={usageLimitOpen() && available()}
onOpenChange={(open) => !open && hideUsageLimit()}
position="center"
class="w-160"
@@ -55,34 +54,40 @@ export function AiUsageLimitDialog() {
<Surface depth={2} class="rounded-xl">
<section class="flex flex-col gap-5 p-6 font-sans">
<div class="flex flex-col gap-1">
- <h2 class="text-xl font-semibold text-ink">{title()}</h2>
- <p class="text-sm text-ink-extra-muted">
- <Show
- when={!free()}
- fallback="Guest access includes a fixed amount of AI each month, measured at provider cost. Upgrade to keep going now and unlock every model."
- >
- Your plan includes AI each month, measured at provider cost. Add
- credits or turn on usage billing to keep going, or move to Max
- for a larger included amount.
- </Show>
- </p>
+ <Dialog.Title class="text-xl font-semibold text-ink">
+ {title()}
+ </Dialog.Title>
+ <Dialog.Description class="text-sm text-ink-extra-muted">
+ {freePlan()
+ ? 'Subscribe to a paid plan to keep going.'
+ : usageSnapshot()
+ ? 'Add additional credits to keep going.'
+ : 'Check your plan and usage options to keep going.'}
+ </Dialog.Description>
</div>
+ <Show when={usagePreview.active()}>
+ <p class="text-xs text-ink-muted" role="status">
+ Developer preview:{' '}
+ {usagePreview.plan() === 'free' ? 'Free' : 'paid'} plan. No
+ account billing has changed.
+ </p>
+ </Show>
+
{/* The summary is a suspending query resource; keep its
suspension inside the dialog rather than the route boundary. */}
<Suspense fallback={null}>
- <Show when={summary.isSuccess && summary.data}>
+ <Show when={usageSnapshot()}>
{(snapshot) => (
<div class="flex flex-col gap-4 rounded-lg bg-active p-4">
- <AiUsageMeter snapshot={snapshot()} />
- <Show when={snapshot().tier !== 'free'}>
- <div class="border-t border-t-edge-muted pt-4">
- <AiUsageControls
- snapshot={snapshot()}
- returnUrl={returnUrl()}
- />
- </div>
- </Show>
+ <MonthlyLimit
+ percentage={monthlyUsagePercent(
+ snapshot().used_cents,
+ snapshot().included_cents
+ )}
+ periodEnd={snapshot().period_end}
+ unlimited={snapshot().unlimited}
+ />
</div>
)}
</Show>
@@ -90,15 +95,16 @@ export function AiUsageLimitDialog() {
<div class="flex flex-col gap-2 sm:flex-row sm:items-center sm:justify-between">
<Button
- variant="ghost"
+ variant={freePlan() ? 'accent' : 'ghost'}
depth={3}
class="px-3 py-1.5"
onClick={() => {
+ const target = freePlan() ? 'Billing' : 'Usage';
hideUsageLimit();
- navigate('/app/settings/billing');
+ openSettings(target);
}}
>
- Open billing settings
+ {freePlan() ? 'View plans' : 'Open usage settings'}
</Button>
<div class="flex gap-2 sm:justify-end">
<Button
@@ -109,36 +115,6 @@ export function AiUsageLimitDialog() {
>
Dismiss
</Button>
- <Suspense fallback={null}>
- <Show when={summary.isSuccess && summary.data.tier === 'free'}>
- <Button
- variant="strong"
- class="px-3 py-1.5"
- onClick={() => {
- hideUsageLimit();
- navigate('/app/settings/billing');
- }}
- >
- Upgrade
- </Button>
- </Show>
- <Show
- when={
- summary.isSuccess &&
- summary.data.can_manage_billing &&
- summary.data.tier === 'premium'
- }
- >
- <Button
- variant="strong"
- class="px-3 py-1.5"
- disabled={changePlan.isPending}
- onClick={() => void upgradeToMax()}
- >
- Upgrade to Max
- </Button>
- </Show>
- </Suspense>
</div>
</div>
</section>
diff --git a/apps/web/src/features/paywall/ai-usage-limit-handling.test.ts b/apps/web/src/features/paywall/ai-usage-limit-handling.test.ts
new file mode 100644
index 0000000000..5c2daadea0
--- /dev/null
+++ b/apps/web/src/features/paywall/ai-usage-limit-handling.test.ts
@@ -0,0 +1,246 @@
+import {
+ AI_USAGE_LIMIT_ERROR,
+ readAiUsageLimitError,
+} from '@app/lib/service-clients/ai-usage-limit';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import { ThrownResultError, throwOnErr } from '@core/util/result';
+import { safeFetch } from '@core/util/safeFetch';
+import { agentHarnessServiceClient } from '@service-agent-harness/client';
+import { cognitionApiServiceClient } from '@service-cognition/client';
+import { importClient } from '@service-cognition/import';
+import { scheduledActionClient } from '@service-scheduled-action/client';
+import { QueryClient } from '@tanstack/solid-query';
+import { afterEach, beforeEach, expect, test, vi } from 'vitest';
+import {
+ handleAiUsageLimitError,
+ observeAiUsageLimitMutations,
+} from './ai-usage-limit-handling';
+
+const state = useAiUsageLimitState();
+const fetch = vi.fn<typeof window.fetch>();
+let client: QueryClient;
+let unsubscribe: () => void;
+
+beforeEach(() => {
+ state.hideUsageLimit();
+ fetch.mockReset();
+ vi.stubGlobal('fetch', fetch);
+ client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false },
+ mutations: { retry: false, gcTime: 0 },
+ },
+ });
+ unsubscribe = observeAiUsageLimitMutations(client);
+});
+
+afterEach(() => {
+ unsubscribe();
+ client.clear();
+ state.hideUsageLimit();
+ vi.unstubAllGlobals();
+});
+
+const spendingActions = [
+ [
+ 'chat send',
+ () =>
+ cognitionApiServiceClient.sendStreamChatMessage({
+ content: 'Hello',
+ model: 'test',
+ }),
+ ],
+ [
+ 'structured completion',
+ () =>
+ cognitionApiServiceClient.structuredCompletion({
+ prompt: 'Answer',
+ model: 'test',
+ output_schema: { name: 'test', schema: {} },
+ }),
+ ],
+ ['session creation', () => agentHarnessServiceClient.create({})],
+ [
+ 'session control',
+ () =>
+ agentHarnessServiceClient.control('session', {
+ type: 'prompt',
+ prompt: 'Hello',
+ }),
+ ],
+ [
+ 'import',
+ () => importClient.runImport({ import_ids: ['id'], discard_ids: [] }),
+ ],
+ ['gather retry', () => importClient.retryGather('linear')],
+ [
+ 'run schedule',
+ () => scheduledActionClient.runNow({ scheduleId: 'schedule' }),
+ ],
+] as const;
+
+test.each(
+ spendingActions.flatMap(([name, action]) =>
+ ['ai_allowance_exhausted', 'ai_free_allowance_exhausted'].map((reason) => ({
+ name,
+ action,
+ reason,
+ }))
+ )
+)(
+ '$name returns a typed $reason refusal without opening UI in the client',
+ async ({ action, reason }) => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: reason, error: 'Usage blocked' }, { status: 402 })
+ );
+ const result = await action();
+ expect(result._unsafeUnwrapErr()).toEqual([
+ {
+ code: AI_USAGE_LIMIT_ERROR,
+ reason,
+ message: 'Usage blocked',
+ },
+ ]);
+ expect(state.usageLimitOpen()).toBe(false);
+ expect(handleAiUsageLimitError(result._unsafeUnwrapErr())).toBe(true);
+ expect(state.usageLimitCode()).toBe(reason);
+ }
+);
+
+test.each([
+ 'ai_allowance_exhausted',
+ 'ai_free_allowance_exhausted',
+ 'ai_overage_limit_reached',
+ 'ai_overage_payment_failed',
+])(
+ 'opens the dialog after a foreground mutation fails with %s',
+ async (reason) => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: reason, error: 'Usage blocked' }, { status: 402 })
+ );
+ const mutation = client.getMutationCache().build(client, {
+ mutationFn: () =>
+ throwOnErr(() =>
+ scheduledActionClient.runNow({ scheduleId: 'schedule' })
+ ),
+ });
+ await expect(mutation.execute(undefined)).rejects.toBeInstanceOf(
+ ThrownResultError
+ );
+ expect(state.usageLimitOpen()).toBe(true);
+ expect(state.usageLimitCode()).toBe(reason);
+ expect(fetch).toHaveBeenCalledOnce();
+ }
+);
+
+test('keeps background queries quiet even when the AI client returns a typed refusal', async () => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: 'ai_allowance_exhausted' }, { status: 402 })
+ );
+ await expect(
+ client.fetchQuery({
+ queryKey: ['background'],
+ queryFn: () =>
+ throwOnErr(() =>
+ cognitionApiServiceClient.structuredCompletion({
+ prompt: 'Answer',
+ model: 'test',
+ output_schema: { name: 'test', schema: {} },
+ })
+ ),
+ })
+ ).rejects.toBeInstanceOf(ThrownResultError);
+ expect(state.usageLimitOpen()).toBe(false);
+});
+
+test('does not intercept generic HTTP requests even with a quota-shaped body', async () => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: 'ai_allowance_exhausted' }, { status: 402 })
+ );
+ const result = await safeFetch('https://localhost/not-an-ai-action');
+ expect(result._unsafeUnwrapErr()[0].code).toBe('HTTP_ERROR');
+ expect(handleAiUsageLimitError(result._unsafeUnwrapErr())).toBe(false);
+ expect(state.usageLimitOpen()).toBe(false);
+});
+
+test('leaves the response body available to other client error handling', async () => {
+ const body = { code: 'ai_allowance_exhausted', error: 'Usage blocked' };
+ const response = Response.json(body, { status: 402 });
+ expect(await readAiUsageLimitError(response)).toMatchObject({
+ reason: body.code,
+ });
+ expect(await response.json()).toEqual(body);
+});
+
+test.each([
+ [402, { code: 'paid_plan_required' }],
+ [402, { code: 'unknown_code' }],
+ [402, { code: 1 }],
+ [402, null],
+ [503, { code: 'ai_billing_unavailable' }],
+ [403, { code: 'ai_allowance_exhausted' }],
+])(
+ 'does not classify unrelated HTTP %i (%j) as a quota refusal',
+ async (status, body) => {
+ fetch.mockResolvedValueOnce(Response.json(body, { status }));
+ const mutation = client.getMutationCache().build(client, {
+ mutationFn: () =>
+ throwOnErr(() =>
+ scheduledActionClient.runNow({ scheduleId: 'schedule' })
+ ),
+ });
+ await expect(mutation.execute(undefined)).rejects.toBeInstanceOf(
+ ThrownResultError
+ );
+ expect(state.usageLimitOpen()).toBe(false);
+ }
+);
+
+test('keeps malformed 402 responses as ordinary HTTP errors', async () => {
+ fetch.mockResolvedValueOnce(
+ new Response('Payment required', { status: 402 })
+ );
+ const result = await scheduledActionClient.runNow({ scheduleId: 'schedule' });
+ expect(result._unsafeUnwrapErr()[0].code).toBe('HTTP_ERROR');
+ expect(handleAiUsageLimitError(result._unsafeUnwrapErr())).toBe(false);
+});
+
+test('keeps service-specific error messages intact', async () => {
+ fetch.mockResolvedValueOnce(
+ new Response('Model is unavailable.', { status: 422 })
+ );
+ const result = await agentHarnessServiceClient.control('session', {
+ type: 'setModel',
+ model: 'missing',
+ });
+ expect(result._unsafeUnwrapErr()[0].message).toBe('Model is unavailable.');
+ expect(handleAiUsageLimitError(result._unsafeUnwrapErr())).toBe(false);
+});
+
+test('preserves generic server-error retries', async () => {
+ fetch.mockResolvedValueOnce(Response.json({}, { status: 500 }));
+ fetch.mockResolvedValueOnce(Response.json({ ok: true }));
+ const result = await safeFetch('https://localhost/request', {
+ retry: { maxTries: 2, delay: 0 },
+ });
+ expect(result.isOk()).toBe(true);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ expect(state.usageLimitOpen()).toBe(false);
+});
+
+test('stops handling mutation failures when the app subscription is disposed', async () => {
+ unsubscribe();
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: 'ai_allowance_exhausted' }, { status: 402 })
+ );
+ const mutation = client.getMutationCache().build(client, {
+ mutationFn: () =>
+ throwOnErr(() =>
+ scheduledActionClient.runNow({ scheduleId: 'schedule' })
+ ),
+ });
+ await expect(mutation.execute(undefined)).rejects.toBeInstanceOf(
+ ThrownResultError
+ );
+ expect(state.usageLimitOpen()).toBe(false);
+});
diff --git a/apps/web/src/features/paywall/ai-usage-limit-handling.ts b/apps/web/src/features/paywall/ai-usage-limit-handling.ts
new file mode 100644
index 0000000000..b86a02daa4
--- /dev/null
+++ b/apps/web/src/features/paywall/ai-usage-limit-handling.ts
@@ -0,0 +1,34 @@
+import {
+ isAiDenyCode,
+ isAiUsageLimitError,
+} from '@app/lib/service-clients/ai-usage-limit';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import { ThrownResultError } from '@core/util/result';
+import type { QueryClient } from '@tanstack/solid-query';
+
+/** Present a typed AI refusal at a user-action boundary. Other errors stay local. */
+export function handleAiUsageLimitError(error: unknown): boolean {
+ const errors = error instanceof ThrownResultError ? error.errors : error;
+ const limit = Array.isArray(errors)
+ ? errors.find(isAiUsageLimitError)
+ : isAiUsageLimitError(errors)
+ ? errors
+ : undefined;
+ if (!limit) return false;
+ showAiUsageLimit(limit.reason);
+ return true;
+}
+
+/** Live chat tools report a reason code rather than an HTTP response. */
+export function showAiUsageLimit(reason: string): void {
+ if (isAiDenyCode(reason)) useAiUsageLimitState().showUsageLimit(reason);
+}
+
+/** Observe completed action failures, leaving background queries alone. */
+export function observeAiUsageLimitMutations(client: QueryClient) {
+ return client.getMutationCache().subscribe((event) => {
+ if (event.type === 'updated' && event.action.type === 'error') {
+ handleAiUsageLimitError(event.action.error);
+ }
+ });
+}
diff --git a/apps/web/src/features/paywall/ai-usage-preview.test.ts b/apps/web/src/features/paywall/ai-usage-preview.test.ts
new file mode 100644
index 0000000000..b9146f4fa0
--- /dev/null
+++ b/apps/web/src/features/paywall/ai-usage-preview.test.ts
@@ -0,0 +1,97 @@
+import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { useAiUsagePreview } from './ai-usage-preview';
+
+const state = vi.hoisted(() => ({ dev: true }));
+vi.mock('@core/constant/featureFlags', () => ({
+ get DEV_MODE_ENV() {
+ return state.dev;
+ },
+}));
+
+const snapshot: AiUsageSnapshot = {
+ tier: 'premium',
+ unlimited: false,
+ payer: 'macro|[email protected]',
+ can_manage_billing: true,
+ seats: 1,
+ period_start: '2026-10-01T00:00:00Z',
+ period_end: '2026-11-01T00:00:00Z',
+ included_cents: 4_000,
+ used_cents: 1_000,
+ credits_consumed_cents: 500,
+ credit_balance_cents: 2_500,
+ overage_enabled: true,
+ overage_limit_cents: 5_000,
+ overage_charged_cents: 1_000,
+ overage_suspended: false,
+ uncovered_cents: 0,
+ remaining_cents: 10_500,
+};
+
+beforeEach(() => {
+ state.dev = true;
+ useAiUsagePreview().reset();
+});
+
+describe('AI usage preview', () => {
+ it('shares an exhausted preview across consumers without mutating the summary', () => {
+ const before = { ...snapshot };
+ useAiUsagePreview().previewLimit('paid');
+ const preview = useAiUsagePreview().withPreview(snapshot);
+ expect(preview).toMatchObject({
+ used_cents: snapshot.included_cents,
+ remaining_cents: 0,
+ credit_balance_cents: 0,
+ overage_enabled: false,
+ blocked_reason: 'allowance_exhausted',
+ });
+ expect(snapshot).toEqual(before);
+ useAiUsagePreview().reset();
+ expect(useAiUsagePreview().withPreview(snapshot)).toBe(snapshot);
+ });
+
+ it('uses the backend allowance and Free refusal reason in the preview', () => {
+ useAiUsagePreview().previewLimit('free');
+ const preview = useAiUsagePreview().withPreview({
+ ...snapshot,
+ tier: 'free',
+ included_cents: 500,
+ used_cents: 250,
+ });
+ expect(preview).toMatchObject({
+ tier: 'free',
+ included_cents: 500,
+ used_cents: 500,
+ blocked_reason: 'free_allowance_exhausted',
+ });
+ });
+
+ it('cannot override billing data outside development', () => {
+ state.dev = false;
+ useAiUsagePreview().previewLimit('paid');
+ useAiUsagePreview().previewBeforeLaunch();
+ expect(useAiUsagePreview().active()).toBe(false);
+ expect(useAiUsagePreview().beforeLaunch()).toBe(false);
+ expect(useAiUsagePreview().withPreview(snapshot)).toBe(snapshot);
+ });
+
+ it('previews the rollout announcement with real usage or either plan and resets it', () => {
+ const preview = useAiUsagePreview();
+ preview.previewBeforeLaunch();
+ expect(preview.active()).toBe(true);
+ expect(preview.beforeLaunch()).toBe(true);
+ expect(preview.withPreview(snapshot)).toBe(snapshot);
+ for (const plan of ['free', 'paid'] as const) {
+ preview.previewPlan(plan);
+ expect(preview.beforeLaunch()).toBe(true);
+ expect(preview.withPreview(snapshot)?.tier).toBe(
+ plan === 'free' ? 'free' : 'premium'
+ );
+ }
+ preview.reset();
+ expect(preview.active()).toBe(false);
+ expect(preview.beforeLaunch()).toBe(false);
+ expect(preview.withPreview(snapshot)).toBe(snapshot);
+ });
+});
diff --git a/apps/web/src/features/paywall/ai-usage-preview.ts b/apps/web/src/features/paywall/ai-usage-preview.ts
new file mode 100644
index 0000000000..f539a7eac0
--- /dev/null
+++ b/apps/web/src/features/paywall/ai-usage-preview.ts
@@ -0,0 +1,121 @@
+import { DEV_MODE_ENV } from '@core/constant/featureFlags';
+import type {
+ AiPlanCatalogEntry,
+ AiUsageSnapshot,
+} from '@service-auth/ai-billing-types';
+import { createSignal } from 'solid-js';
+import type { UsagePreviewPlan } from '../usage/core/usage';
+
+const [preview, setPreview] = createSignal<{
+ plan?: UsagePreviewPlan;
+ exhausted: boolean;
+ beforeLaunch: boolean;
+}>();
+
+function previewPeriod(
+ snapshot: AiUsageSnapshot | undefined,
+ tier: 'free' | 'premium'
+) {
+ if (tier === 'premium' && snapshot) {
+ return {
+ period_start: snapshot.period_start,
+ period_end: snapshot.period_end,
+ };
+ }
+ const now = new Date();
+ return {
+ period_start: new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)
+ ).toISOString(),
+ period_end: new Date(
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)
+ ).toISOString(),
+ };
+}
+
+/** Development-only display state shared by Usage and the usage-limit dialog. */
+export function useAiUsagePreview() {
+ const state = () => (DEV_MODE_ENV ? preview() : undefined);
+ const active = () => !!state();
+ const plan = () => state()?.plan;
+ const beforeLaunch = () => state()?.beforeLaunch === true;
+ const previewPlan = (plan: UsagePreviewPlan) => {
+ if (DEV_MODE_ENV) {
+ setPreview((current) => ({
+ plan,
+ exhausted: false,
+ beforeLaunch: current?.beforeLaunch ?? false,
+ }));
+ }
+ };
+ const previewLimit = (plan: UsagePreviewPlan) => {
+ if (DEV_MODE_ENV)
+ setPreview({ plan, exhausted: true, beforeLaunch: false });
+ };
+ const previewBeforeLaunch = () => {
+ if (DEV_MODE_ENV) {
+ setPreview((current) => ({
+ plan: current?.plan,
+ exhausted: false,
+ beforeLaunch: true,
+ }));
+ }
+ };
+ const reset = () => setPreview(undefined);
+
+ const withPreview = (
+ snapshot: AiUsageSnapshot | undefined,
+ plans?: readonly AiPlanCatalogEntry[]
+ ): AiUsageSnapshot | undefined => {
+ const selected = state();
+ if (!selected?.plan) return snapshot;
+ const tier = selected.plan === 'free' ? 'free' : 'premium';
+ const allowance = plans?.find(
+ (entry) => entry.tier === tier
+ )?.included_ai_cents_per_seat;
+ // The fallback only supplies a denominator for the display preview.
+ const included =
+ allowance && allowance > 0
+ ? allowance
+ : snapshot?.tier === tier && snapshot.included_cents > 0
+ ? snapshot.included_cents
+ : 100;
+ const used = selected.exhausted ? included : included / 2;
+ return {
+ ...snapshot,
+ ...previewPeriod(snapshot, tier),
+ tier,
+ unlimited: false,
+ payer: snapshot?.payer ?? 'developer-preview',
+ can_manage_billing: true,
+ seats: 1,
+ included_cents: included,
+ used_cents: used,
+ credits_consumed_cents: 0,
+ credit_balance_cents:
+ selected.plan === 'paid' && !selected.exhausted ? 2_500 : 0,
+ overage_enabled: false,
+ overage_limit_cents: 0,
+ overage_charged_cents: 0,
+ overage_suspended: false,
+ uncovered_cents: 0,
+ remaining_cents: included - used,
+ blocked_reason: selected.exhausted
+ ? tier === 'free'
+ ? 'free_allowance_exhausted'
+ : 'allowance_exhausted'
+ : undefined,
+ };
+ };
+
+ return {
+ active,
+ plan,
+ beforeLaunch,
+ previewPlan,
+ previewLimit,
+ previewBeforeLaunch,
+ reset,
+ withPreview,
+ };
+}
diff --git a/apps/web/src/features/settings/AiUsage.test.tsx b/apps/web/src/features/settings/AiUsage.test.tsx
deleted file mode 100644
index 5314d5604e..0000000000
--- a/apps/web/src/features/settings/AiUsage.test.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { afterEach, describe, expect, it, vi } from 'vitest';
-import { AiUsageMeter } from './AiUsage';
-
-vi.mock('@ui', () => ({
- cn: (...values: unknown[]) => values.filter(Boolean).join(' '),
- Button: () => null,
- ToggleSwitch: () => null,
-}));
-
-const snapshot = (seats: number): AiUsageSnapshot => ({
- tier: 'premium',
- unlimited: false,
- payer: 'macro|[email protected]',
- can_manage_billing: true,
- seats,
- period_start: '2026-09-01T00:00:00Z',
- period_end: '2026-10-01T00:00:00Z',
- included_cents: 2_000,
- used_cents: 1_000,
- credits_consumed_cents: 0,
- credit_balance_cents: 2_500,
- overage_enabled: true,
- overage_limit_cents: 5_000,
- overage_charged_cents: 1_000,
- overage_suspended: false,
- uncovered_cents: 0,
- remaining_cents: 10_500,
-});
-
-afterEach(cleanup);
-
-describe('AiUsageMeter', () => {
- it('shows a team member their own allowance and shared billing balances', () => {
- render(() => <AiUsageMeter snapshot={snapshot(5)} />);
-
- expect(screen.getAllByText('$10')).toHaveLength(2);
- expect(screen.getByText(/of \$20 included/)).toBeTruthy();
- expect(screen.queryByText(/across 5 seats/)).toBeNull();
- expect(screen.getByText(/Team credits:/)).toBeTruthy();
- expect(screen.getByText(/Team usage billing this period/)).toBeTruthy();
- });
-
- it('uses personal labels outside a team', () => {
- render(() => <AiUsageMeter snapshot={snapshot(1)} />);
-
- expect(screen.getByText(/Credits:/)).toBeTruthy();
- expect(screen.getByText(/Usage billing this period/)).toBeTruthy();
- expect(screen.queryByText(/Team credits:/)).toBeNull();
- });
-
- it('shows free users only their monthly cap and the upgrade prompt', () => {
- render(() => (
- <AiUsageMeter
- snapshot={{
- ...snapshot(1),
- tier: 'free',
- included_cents: 500,
- used_cents: 500,
- credit_balance_cents: 0,
- overage_enabled: false,
- overage_limit_cents: 0,
- overage_charged_cents: 0,
- remaining_cents: 0,
- blocked_reason: 'free_allowance_exhausted',
- }}
- />
- ));
-
- expect(screen.getByText(/of \$5 included/)).toBeTruthy();
- expect(screen.queryByText(/Credits:/)).toBeNull();
- expect(screen.queryByText(/Usage billing/)).toBeNull();
- expect(screen.getByText(/Upgrade to keep going/)).toBeTruthy();
- });
-});
diff --git a/apps/web/src/features/settings/AiUsage.tsx b/apps/web/src/features/settings/AiUsage.tsx
deleted file mode 100644
index 2c6b1fee19..0000000000
--- a/apps/web/src/features/settings/AiUsage.tsx
+++ /dev/null
@@ -1,281 +0,0 @@
-import { useAnalytics } from '@app/lib/analytics/analytics-context';
-import { toast } from '@core/component/Toast/Toast';
-import {
- useAiBillingPlansQuery,
- useCreateAiCreditCheckoutMutation,
- useUpdateAiOverageMutation,
-} from '@queries/auth';
-import type {
- AiDenyReason,
- AiUsageSnapshot,
-} from '@service-auth/ai-billing-types';
-import { Button, cn, ToggleSwitch } from '@ui';
-import { createMemo, createSignal, For, Match, Show, Switch } from 'solid-js';
-
-/** Whole dollars when even, otherwise dollars and cents. */
-export function formatCents(cents: number): string {
- const dollars = cents / 100;
- return Number.isInteger(dollars)
- ? `$${dollars.toLocaleString()}`
- : `$${dollars.toLocaleString(undefined, {
- minimumFractionDigits: 2,
- maximumFractionDigits: 2,
- })}`;
-}
-
-function formatPeriodEnd(iso: string): string {
- const date = new Date(iso);
- if (Number.isNaN(date.getTime())) return '';
- return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
-}
-
-const BLOCKED_COPY: Record<AiDenyReason, string> = {
- allowance_exhausted:
- "You've used this period's included AI. Add credits or turn on usage billing to keep going.",
- free_allowance_exhausted:
- "You've used this month's free AI. Upgrade to keep going.",
- overage_limit_reached:
- "You've reached your usage billing limit for this period. Raise the limit or add credits to keep going.",
- overage_payment_failed:
- "Your last AI usage charge didn't go through. Update your payment method in Manage, then turn usage billing back on.",
-};
-
-/** Fallback caps offered when the catalog has not loaded yet. */
-const DEFAULT_OVERAGE_LIMITS_CENTS = [2_500, 5_000, 10_000, 25_000];
-const DEFAULT_CREDIT_PACKS_CENTS = [1_000, 2_500, 5_000, 10_000];
-
-/**
- * The period's AI position: a meter of included usage plus credits and overage
- * headroom, and where the user stands right now. Free users see only the
- * meter against their monthly cap; they have no credits or usage billing.
- */
-export function AiUsageMeter(props: { snapshot: AiUsageSnapshot }) {
- const free = () => props.snapshot.tier === 'free';
- const included = () => props.snapshot.included_cents;
- const used = () => props.snapshot.used_cents;
- const includedUsed = () => Math.min(used(), included());
- const beyond = () => Math.max(0, used() - included());
- // Both segments share one scale (the larger of included and used) so they
- // total at most 100% and the beyond-included segment stays visible.
- const scale = () => Math.max(included(), used());
- const pct = () => (scale() > 0 ? (includedUsed() / scale()) * 100 : 0);
- const beyondPct = () => (scale() > 0 ? (beyond() / scale()) * 100 : 0);
- const blocked = () => !!props.snapshot.blocked_reason;
-
- return (
- <div class="flex flex-col gap-2">
- <div class="flex items-baseline justify-between gap-3">
- <span class="text-sm text-ink">
- <span class="font-semibold">{formatCents(used())}</span>
- <span class="text-ink-muted">
- {' '}
- of {formatCents(included())} included
- </span>
- </span>
- <span class="text-xs text-ink-extra-muted">
- Resets {formatPeriodEnd(props.snapshot.period_end)}
- </span>
- </div>
- <div class="relative h-2 w-full overflow-hidden rounded-full bg-active">
- <div
- class={cn(
- 'absolute inset-y-0 left-0 rounded-full transition-[width]',
- blocked() ? 'bg-failure' : 'bg-accent'
- )}
- style={{ width: `${pct()}%` }}
- />
- <Show when={beyond() > 0}>
- <div
- class="absolute inset-y-0 rounded-full bg-warning/70"
- style={{ left: `${pct()}%`, width: `${beyondPct()}%` }}
- />
- </Show>
- </div>
- <div class="flex flex-wrap gap-x-4 gap-y-1 text-xs text-ink-muted">
- <Show when={beyond() > 0}>
- <span>{formatCents(beyond())} beyond included</span>
- </Show>
- <Show when={!free()}>
- <span>
- {props.snapshot.seats > 1 ? 'Team credits' : 'Credits'}:{' '}
- <span class="text-ink">
- {formatCents(props.snapshot.credit_balance_cents)}
- </span>
- </span>
- </Show>
- <Show when={props.snapshot.overage_enabled}>
- <span>
- {props.snapshot.seats > 1
- ? 'Team usage billing this period'
- : 'Usage billing this period'}
- :{' '}
- <span class="text-ink">
- {formatCents(props.snapshot.overage_charged_cents)}
- </span>{' '}
- of {formatCents(props.snapshot.overage_limit_cents)}
- </span>
- </Show>
- </div>
- <Show when={props.snapshot.blocked_reason}>
- {(reason) => (
- <p class="text-xs text-failure">{BLOCKED_COPY[reason()]}</p>
- )}
- </Show>
- </div>
- );
-}
-
-/**
- * The payer's controls: buy a credit pack, and turn usage billing on or off
- * with a per-period cap. Members who are not the payer see who to ask.
- */
-export function AiUsageControls(props: {
- snapshot: AiUsageSnapshot;
- /** Where Stripe returns after a credit purchase. */
- returnUrl: string;
-}) {
- const analytics = useAnalytics();
- const plans = useAiBillingPlansQuery();
- const updateOverage = useUpdateAiOverageMutation();
- const creditCheckout = useCreateAiCreditCheckoutMutation();
-
- const creditPacks = () =>
- plans.isSuccess
- ? plans.data.credit_packs_cents
- : DEFAULT_CREDIT_PACKS_CENTS;
- const overageLimits = createMemo(() => {
- const current = props.snapshot.overage_limit_cents;
- const options = [...DEFAULT_OVERAGE_LIMITS_CENTS];
- if (current > 0 && !options.includes(current)) {
- options.push(current);
- options.sort((a, b) => a - b);
- }
- return options;
- });
- const [pendingLimit, setPendingLimit] = createSignal<number | null>(null);
- const selectedLimit = () =>
- pendingLimit() ??
- (props.snapshot.overage_limit_cents > 0
- ? props.snapshot.overage_limit_cents
- : DEFAULT_OVERAGE_LIMITS_CENTS[1]);
-
- const busy = () => updateOverage.isPending || creditCheckout.isPending;
-
- const buyCredits = async (amountCents: number) => {
- try {
- analytics.track('ai_credits_checkout_start', { amountCents });
- const url = await creditCheckout.mutateAsync({
- amountCents,
- successUrl: `${props.returnUrl}?aiCreditsSuccess=true`,
- cancelUrl: `${props.returnUrl}?aiCreditsCancel=true`,
- });
- window.location.href = url;
- } catch (error) {
- console.error(error);
- toast.failure("Couldn't start the credit purchase. Please try again.");
- }
- };
-
- const setOverage = async (enabled: boolean, limitCents: number) => {
- try {
- await updateOverage.mutateAsync({ enabled, limitCents });
- analytics.track('ai_overage_updated', { enabled, limitCents });
- setPendingLimit(null);
- toast.success(
- enabled
- ? `Usage billing on, up to ${formatCents(limitCents)} per period.`
- : 'Usage billing off.'
- );
- } catch (error) {
- console.error(error);
- toast.failure("Couldn't update usage billing. Please try again.");
- }
- };
-
- return (
- <Show
- when={props.snapshot.can_manage_billing}
- fallback={
- <p class="text-xs text-ink-extra-muted">
- AI usage for your team is managed by the team owner. Ask them to add
- credits or turn on usage billing.
- </p>
- }
- >
- <div class="flex flex-col gap-5">
- <div class="flex flex-col gap-2">
- <div class="flex flex-col">
- <span class="text-sm text-ink">Add credits</span>
- <span class="text-xs text-ink-extra-muted">
- Prepaid AI usage that applies after included usage and carries
- over between periods.
- </span>
- </div>
- <div class="flex flex-wrap gap-2">
- <For each={creditPacks()}>
- {(cents) => (
- <Button
- variant="outline"
- size="sm"
- depth={2}
- disabled={busy()}
- onClick={() => void buyCredits(cents)}
- >
- {formatCents(cents)}
- </Button>
- )}
- </For>
- </div>
- </div>
-
- <div class="flex flex-col gap-2">
- <div class="flex items-start justify-between gap-4">
- <div class="flex flex-col">
- <span class="text-sm text-ink">Usage billing</span>
- <span class="text-xs text-ink-extra-muted">
- Bill AI beyond included usage and credits to your card in{' '}
- {formatCents(1_000)} increments, up to a limit you set.
- </span>
- </div>
- <ToggleSwitch
- size="md"
- checked={props.snapshot.overage_enabled}
- disabled={busy()}
- onChange={(checked) => void setOverage(checked, selectedLimit())}
- />
- </div>
- <Switch>
- <Match when={props.snapshot.overage_suspended}>
- <p class="text-xs text-failure">
- Paused after a failed charge. Fix your payment method under
- Manage, then turn usage billing back on to retry.
- </p>
- </Match>
- <Match when={props.snapshot.overage_enabled}>
- <div class="flex flex-wrap items-center gap-2">
- <span class="text-xs text-ink-muted">Limit per period</span>
- <For each={overageLimits()}>
- {(cents) => (
- <Button
- variant={selectedLimit() === cents ? 'accent' : 'outline'}
- size="xs"
- depth={2}
- class="px-2"
- disabled={busy()}
- onClick={() => {
- setPendingLimit(cents);
- void setOverage(true, cents);
- }}
- >
- {formatCents(cents)}
- </Button>
- )}
- </For>
- </div>
- </Match>
- </Switch>
- </div>
- </div>
- </Show>
- );
-}
diff --git a/apps/web/src/features/settings/Billing.test.tsx b/apps/web/src/features/settings/Billing.test.tsx
deleted file mode 100644
index 6c0075e25a..0000000000
--- a/apps/web/src/features/settings/Billing.test.tsx
+++ /dev/null
@@ -1,231 +0,0 @@
-import { type PlanTier, planFeatures } from '@app/features/paywall/plans';
-import { PERMISSION_IDS } from '@core/constant/permissions';
-import {
- cleanup,
- fireEvent,
- render,
- screen,
- waitFor,
-} from '@solidjs/testing-library';
-import { type JSX, Show } from 'solid-js';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { Billing } from './Billing';
-
-const state = vi.hoisted(() => ({
- tier: 'premium' as PlanTier,
- aiUsageBilling: false,
- summarySuccess: true,
- unlimited: false,
- toastSuccess: vi.fn(),
- changePlan: vi.fn(),
-}));
-
-vi.mock('@core/constant/featureFlags', () => ({
- enableAiUsageBilling: { key: 'enable-ai-usage-billing', override: undefined },
-}));
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => ({
- enabled: state.aiUsageBilling,
- payload: undefined,
- loading: false,
- }),
- ShowFeatureFlag: (props: {
- children: JSX.Element;
- fallback?: JSX.Element;
- }) => (
- <Show when={state.aiUsageBilling} fallback={props.fallback}>
- {props.children}
- </Show>
- ),
-}));
-vi.mock('@app/lib/analytics/analytics-context', () => ({
- useAnalytics: () => ({ track: vi.fn() }),
-}));
-vi.mock('@core/auth', () => ({
- useHasPaidAccess: () => () => state.tier !== 'free',
-}));
-vi.mock('@core/context/user', () => ({
- usePermissions: () => () => [PERMISSION_IDS.WRITE_STRIPE_SUBSCRIPTION],
- useUserId: () => () => 'macro|[email protected]',
-}));
-vi.mock('@core/component/Toast/Toast', () => ({
- toast: { success: state.toastSuccess, failure: vi.fn() },
-}));
-vi.mock('@queries/team/teams', () => ({
- useCurrentTeamQuery: () => ({ data: undefined }),
-}));
-vi.mock('@queries/auth', () => ({
- useAiBillingSummaryQuery: () => ({
- isSuccess: state.summarySuccess,
- get data() {
- if (!state.summarySuccess) throw new Error('Read pending summary');
- return {
- tier: state.tier,
- can_manage_billing: true,
- unlimited: state.unlimited,
- used_cents: 1_000_000,
- included_cents: 2_000,
- credit_balance_cents: 0,
- blocked_reason: 'ai_allowance_exhausted',
- };
- },
- }),
- useChangePlanMutation: () => ({
- isPending: false,
- mutateAsync: state.changePlan,
- }),
- useCreateCheckoutSessionMutation: () => ({ mutateAsync: vi.fn() }),
- useIncludedAiCentsByTier: () => () => ({
- free: 500,
- premium: 2_000,
- max: 10_000,
- }),
-}));
-vi.mock('@service-stripe/client', () => ({
- stripeServiceClient: { createPortalSession: vi.fn() },
-}));
-vi.mock('./AiUsage', () => ({
- AiUsageMeter: () => <div data-testid="usage-meter">AI usage meter</div>,
- AiUsageControls: () => <div data-testid="usage-controls">Add credits</div>,
-}));
-vi.mock('@ui', () => ({
- cn: (...values: unknown[]) => values.filter(Boolean).join(' '),
- Layer: (props: { children: JSX.Element }) => <>{props.children}</>,
- ComposerSurface: (props: { children: JSX.Element; class?: string }) => (
- <div class={props.class}>{props.children}</div>
- ),
- Button: (props: JSX.ButtonHTMLAttributes<HTMLButtonElement>) => (
- <button type="button" onClick={props.onClick}>
- {props.children}
- </button>
- ),
-}));
-
-afterEach(cleanup);
-
-describe.each([false, true])(
- 'Billing with enable-ai-usage-billing=%s',
- (aiUsageBilling) => {
- beforeEach(() => {
- state.aiUsageBilling = aiUsageBilling;
- state.tier = 'premium';
- state.summarySuccess = true;
- state.unlimited = false;
- state.toastSuccess.mockClear();
- state.changePlan.mockClear();
- });
-
- it.each<PlanTier>(['free', 'premium', 'max'])(
- 'keeps %s subscription controls and gates usage UI and copy on the flag',
- (tier) => {
- state.tier = tier;
- const { container } = render(() => <Billing />);
-
- expect(screen.getByRole('heading', { name: 'Billing' })).toBeTruthy();
- // Free users see their monthly cap but have no credits or usage billing.
- expect(screen.queryByTestId('usage-meter') !== null).toBe(
- aiUsageBilling
- );
- expect(screen.queryByTestId('usage-controls') !== null).toBe(
- aiUsageBilling && tier !== 'free'
- );
- expect(container.textContent?.includes('of AI usage')).toBe(
- aiUsageBilling
- );
- if (!aiUsageBilling) {
- expect(container.textContent).not.toMatch(
- /AI usage|Add credits|Usage billing|included AI|out of credits/i
- );
- }
- expect(
- screen.getByRole('button', {
- name: tier === 'free' ? 'Upgrade now' : 'Manage',
- })
- ).toBeTruthy();
- }
- );
-
- it('gates usage-billing rows in the plan comparison on the flag', () => {
- const labels = planFeatures(aiUsageBilling).map(
- (feature) => feature.label
- );
- expect(labels.includes('AI usage included')).toBe(aiUsageBilling);
- expect(labels.includes('Beyond included')).toBe(aiUsageBilling);
- expect(labels).toContain('AI Agent');
- expect(labels).toContain('Storage');
- });
-
- it('does not read a pending billing summary', () => {
- state.summarySuccess = false;
- render(() => <Billing />);
- expect(screen.queryByTestId('usage-meter')).toBeNull();
- expect(screen.getByRole('button', { name: 'Manage' })).toBeTruthy();
- });
-
- it('keeps unlimited plans free of credit controls', () => {
- state.unlimited = true;
- render(() => <Billing />);
- expect(screen.queryByTestId('usage-controls')).toBeNull();
- expect(
- screen.queryByText(
- 'Your enterprise plan includes unlimited AI usage.'
- ) !== null
- ).toBe(aiUsageBilling);
- });
-
- it('offers both paid plans to free users', () => {
- state.tier = 'free';
- const { container } = render(() => <Billing />);
-
- expect(screen.getByRole('button', { name: 'Upgrade now' })).toBeTruthy();
- expect(screen.getByRole('button', { name: 'Get Max' })).toBeTruthy();
- expect(
- screen.queryByRole('button', { name: 'Upgrade to Max' })
- ).toBeNull();
- // Allowances come from the catalog, including the free cap.
- expect(container.textContent?.includes('$5 of AI usage')).toBe(
- aiUsageBilling
- );
- expect(container.textContent?.includes('$100 of AI usage')).toBe(
- aiUsageBilling
- );
- });
-
- it('lets a Premium payer move to Max', async () => {
- state.tier = 'premium';
- render(() => <Billing />);
-
- expect(
- screen.getByText(aiUsageBilling ? 'Need more AI?' : 'Upgrade')
- ).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();
- fireEvent.click(screen.getByRole('button', { name: 'Upgrade to Max' }));
- await waitFor(() =>
- expect(state.changePlan).toHaveBeenCalledWith({ plan: 'max' })
- );
- expect(state.toastSuccess).toHaveBeenCalledWith(
- aiUsageBilling
- ? 'Upgraded to Max. Your larger AI allowance applies right away.'
- : 'Upgraded to Max.'
- );
- });
-
- it('keeps the current Max plan visible and allows a Premium downgrade', async () => {
- state.tier = 'max';
- render(() => <Billing />);
-
- expect(screen.getByRole('heading', { name: 'Max plan' })).toBeTruthy();
- expect(screen.queryByRole('button', { name: 'Get Max' })).toBeNull();
- expect(
- screen.queryByRole('button', { name: 'Upgrade to Max' })
- ).toBeNull();
-
- fireEvent.click(
- screen.getByRole('button', { name: 'Switch to Premium' })
- );
- await waitFor(() =>
- expect(state.changePlan).toHaveBeenCalledWith({ plan: 'premium' })
- );
- });
- }
-);
diff --git a/apps/web/src/features/settings/Billing.tsx b/apps/web/src/features/settings/Billing.tsx
index 51c605f643..46b700a1dc 100644
--- a/apps/web/src/features/settings/Billing.tsx
+++ b/apps/web/src/features/settings/Billing.tsx
@@ -25,7 +25,6 @@ import type { TeamMember } from '@service-auth/generated/schemas/teamMember';
import { stripeServiceClient } from '@service-stripe/client';
import { Button, Layer } from '@ui';
import { createMemo, For, Match, Show, Switch } from 'solid-js';
-import { AiUsageControls, AiUsageMeter } from './AiUsage';
import { SettingsCard, SettingsPage, SettingsSection } from './primitives';
/**
@@ -197,8 +196,6 @@ export const Billing = () => {
}
};
- const returnUrl = () => `${window.location.origin}/app/settings/billing`;
-
return (
<SettingsPage
title="Billing"
@@ -287,44 +284,6 @@ export const Billing = () => {
</SettingsCard>
</SettingsSection>
- <Show
- when={aiUsageBilling().enabled && summary.isSuccess && summary.data}
- >
- {(snapshot) => (
- <SettingsSection
- title="AI usage"
- description={
- snapshot().tier === 'free'
- ? 'Guest access includes a fixed amount of AI each month, measured at provider cost. Upgrade for more and to unlock every model.'
- : 'Your plan includes AI each month, measured at provider cost. Beyond that, prepaid credits and usage billing keep you going.'
- }
- >
- <SettingsCard>
- <section class="flex flex-col gap-5 p-4">
- <Show
- when={!snapshot().unlimited}
- fallback={
- <p class="text-sm text-ink-muted">
- Your enterprise plan includes unlimited AI usage.
- </p>
- }
- >
- <AiUsageMeter snapshot={snapshot()} />
- <Show when={snapshot().tier !== 'free'}>
- <div class="border-t border-t-edge-muted pt-4">
- <AiUsageControls
- snapshot={snapshot()}
- returnUrl={returnUrl()}
- />
- </div>
- </Show>
- </Show>
- </section>
- </SettingsCard>
- </SettingsSection>
- )}
- </Show>
-
<Show when={canChangePlan()}>
<Switch>
<Match when={!hasPaid()}>
diff --git a/apps/web/src/features/settings/SettingsTabContent.tsx b/apps/web/src/features/settings/SettingsTabContent.tsx
index 0aed6cbd5c..5539f972cf 100644
--- a/apps/web/src/features/settings/SettingsTabContent.tsx
+++ b/apps/web/src/features/settings/SettingsTabContent.tsx
@@ -4,6 +4,7 @@ import { Show, Suspense } from 'solid-js';
import { CalendarSettings } from '../calendar/calendar-settings';
import { CrmSettings as Crm } from '../crm/crm-settings';
import { SchedulingSettings } from '../scheduling/scheduling';
+import { Usage } from '../usage/usage';
import { Account } from './Account';
import { Admin } from './Admin';
import { Agent } from './Agent';
@@ -55,6 +56,9 @@ export function SettingsTabContent(props: { tab: SettingsTab }) {
<Show when={isCurrentTab('Billing')}>
<Billing />
</Show>
+ <Show when={isCurrentTab('Usage')}>
+ <Usage />
+ </Show>
<Show when={isCurrentTab('Appearance')}>
<Appearance />
</Show>
diff --git a/apps/web/src/features/usage/components/auto-reload-dialog.tsx b/apps/web/src/features/usage/components/auto-reload-dialog.tsx
new file mode 100644
index 0000000000..8b909e4cfa
--- /dev/null
+++ b/apps/web/src/features/usage/components/auto-reload-dialog.tsx
@@ -0,0 +1,180 @@
+import XIcon from '@phosphor/x.svg';
+import { Button, Dialog, InputGroup, Surface, TextField } from '@ui';
+import { Show } from 'solid-js';
+
+export function AutoReloadDialog(props: {
+ enabled: boolean;
+ minimum: string;
+ target: string;
+ maximum: string;
+ onMinimum: (value: string) => void;
+ onTarget: (value: string) => void;
+ onMaximum: (value: string) => void;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+ onSave: () => void;
+ onTurnOff: () => void;
+ onPaymentMethods: () => void;
+ canManagePaymentMethods: boolean;
+ pending: boolean;
+ paymentMethodsPending: boolean;
+ disabled: boolean;
+ invalid: boolean;
+ notice?: string;
+ error?: string;
+}) {
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && props.onClose()}
+ onCloseAutoFocus={
+ props.onRestoreFocus
+ ? (event) => {
+ event.preventDefault();
+ props.onRestoreFocus?.();
+ }
+ : undefined
+ }
+ position="center"
+ class="w-160"
+ >
+ <Surface depth={2} class="relative rounded-xl">
+ <div class="flex max-h-[85dvh] flex-col gap-6 overflow-y-auto p-6">
+ <Dialog.Title class="pr-8 text-xl font-semibold text-ink">
+ Auto-Reload
+ </Dialog.Title>
+ <Dialog.Description class="sr-only">
+ Set balance thresholds and a monthly spending limit for automatic
+ credit purchases.
+ </Dialog.Description>
+ <TextField value={props.minimum} onChange={props.onMinimum}>
+ <TextField.Label>Minimum balance</TextField.Label>
+ <TextField.Description>
+ Automatically purchase credits when my balance drops below this
+ amount.
+ </TextField.Description>
+ <InputGroup size="xl">
+ <TextField.Input
+ as={InputGroup.Input}
+ inputMode="decimal"
+ class="text-sm"
+ />
+ <InputGroup.Addon aria-hidden="true">$</InputGroup.Addon>
+ </InputGroup>
+ </TextField>
+ <TextField value={props.target} onChange={props.onTarget}>
+ <TextField.Label>Target balance</TextField.Label>
+ <TextField.Description>
+ Bring my balance back to this amount if I hit my minimum.
+ </TextField.Description>
+ <InputGroup size="xl">
+ <TextField.Input
+ as={InputGroup.Input}
+ inputMode="decimal"
+ class="text-sm"
+ />
+ <InputGroup.Addon aria-hidden="true">$</InputGroup.Addon>
+ </InputGroup>
+ </TextField>
+ <TextField value={props.maximum} onChange={props.onMaximum}>
+ <TextField.Label>Maximum monthly spend (optional)</TextField.Label>
+ <TextField.Description>
+ Limit the total amount of credits purchased through auto-reload
+ each month. Leave blank for no limit.
+ </TextField.Description>
+ <InputGroup size="xl">
+ <TextField.Input
+ as={InputGroup.Input}
+ inputMode="decimal"
+ class="text-sm"
+ placeholder="No limit."
+ />
+ <InputGroup.Addon aria-hidden="true">$</InputGroup.Addon>
+ </InputGroup>
+ </TextField>
+ <div class="flex flex-col gap-2">
+ <h3 class="text-sm font-medium text-ink">Payment method</h3>
+ <p class="text-xs text-ink-muted">
+ Choose or add a payment method in your billing portal.
+ </p>
+ <Button
+ class="self-start"
+ variant="outline"
+ depth={3}
+ size="sm"
+ disabled={
+ !props.canManagePaymentMethods || props.paymentMethodsPending
+ }
+ onClick={props.onPaymentMethods}
+ >
+ {props.paymentMethodsPending
+ ? 'Opening billing portal…'
+ : 'Manage payment methods'}
+ </Button>
+ </div>
+ <div class="rounded-xl border border-edge-muted p-4">
+ <h3 class="text-sm font-semibold text-ink">
+ Your card will be automatically charged
+ </h3>
+ <p class="mt-2 text-sm text-ink-muted">
+ Enabling auto-reload will charge your card every time you drop
+ below your minimum balance. You can disable it in settings at any
+ time.
+ </p>
+ </div>
+ <Show when={props.notice}>
+ <p class="text-xs text-ink-muted" role="status">
+ {props.notice}
+ </p>
+ </Show>
+ <Show when={props.error}>
+ <p class="text-sm text-failure" role="alert">
+ {props.error}
+ </p>
+ </Show>
+ <div class="flex justify-end gap-2">
+ <Show
+ when={props.enabled}
+ fallback={
+ <Button variant="ghost" depth={3} onClick={props.onClose}>
+ Cancel
+ </Button>
+ }
+ >
+ <Button
+ variant="ghost"
+ depth={3}
+ disabled={props.disabled || props.pending}
+ onClick={props.onTurnOff}
+ >
+ Turn off
+ </Button>
+ </Show>
+ <Button
+ variant="accent"
+ depth={3}
+ disabled={props.disabled || props.pending || props.invalid}
+ onClick={props.onSave}
+ >
+ {props.pending
+ ? 'Saving…'
+ : props.enabled
+ ? 'Save'
+ : 'Turn on auto-reload'}
+ </Button>
+ </div>
+ </div>
+ <Button
+ class="absolute right-4 top-4"
+ size="icon-sm"
+ variant="ghost"
+ depth={3}
+ label="Close Auto-Reload"
+ onClick={props.onClose}
+ >
+ <XIcon class="size-4" />
+ </Button>
+ </Surface>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/usage/components/credit-purchase-dialog.tsx b/apps/web/src/features/usage/components/credit-purchase-dialog.tsx
new file mode 100644
index 0000000000..766277d414
--- /dev/null
+++ b/apps/web/src/features/usage/components/credit-purchase-dialog.tsx
@@ -0,0 +1,146 @@
+import XIcon from '@phosphor/x.svg';
+import { Button, Dialog, InputGroup, Surface } from '@ui';
+import { createUniqueId, For, Show } from 'solid-js';
+import { formatCreditBalance } from '../core/usage';
+
+export function CreditPurchaseDialog(props: {
+ selection: number | 'other';
+ customAmount: string;
+ amountCents: number | undefined;
+ onSelect: (amount: number | 'other') => void;
+ onCustomAmount: (amount: string) => void;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+ onCheckout: () => void;
+ onViewPlans?: () => void;
+ pending: boolean;
+ disabled: boolean;
+ notice?: string;
+ error?: string;
+}) {
+ const name = createUniqueId();
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => !open && props.onClose()}
+ onCloseAutoFocus={
+ props.onRestoreFocus
+ ? (event) => {
+ event.preventDefault();
+ props.onRestoreFocus?.();
+ }
+ : undefined
+ }
+ position="center"
+ class="w-180"
+ >
+ <Surface depth={2} class="relative rounded-xl">
+ <div class="flex max-h-[85dvh] flex-col gap-5 overflow-y-auto p-6">
+ <header class="pr-8">
+ <Dialog.Title class="text-xl font-semibold text-ink">
+ Need more usage?
+ </Dialog.Title>
+ <Dialog.Description class="mt-1 text-sm text-ink-muted">
+ Choose an amount to start. You can always buy more later.
+ </Dialog.Description>
+ </header>
+ <fieldset class="grid grid-cols-2 gap-3 sm:grid-cols-4">
+ <legend class="sr-only">Credit amount</legend>
+ <For each={[2_500, 5_000, 10_000, 'other'] as const}>
+ {(amount) => (
+ <label class="relative flex min-h-22 items-start rounded-xl border border-edge-muted p-4 has-checked:border-accent has-checked:ring-1 has-checked:ring-accent focus-within:ring-2 focus-within:ring-accent">
+ <input
+ class="sr-only"
+ type="radio"
+ name={name}
+ value={amount}
+ checked={props.selection === amount}
+ onChange={() => props.onSelect(amount)}
+ />
+ <span class="text-base font-semibold text-ink">
+ {amount === 'other' ? 'Other' : formatCreditBalance(amount)}
+ </span>
+ </label>
+ )}
+ </For>
+ </fieldset>
+ <Show when={props.selection === 'other'}>
+ <InputGroup size="xl">
+ <InputGroup.Input
+ aria-label="Custom credit amount in dollars"
+ inputMode="decimal"
+ class="text-sm"
+ placeholder="Enter amount"
+ value={props.customAmount}
+ onInput={(event) =>
+ props.onCustomAmount(event.currentTarget.value)
+ }
+ />
+ <InputGroup.Addon aria-hidden="true">$</InputGroup.Addon>
+ </InputGroup>
+ </Show>
+ <div class="rounded-xl border border-edge-muted p-4 text-sm text-ink">
+ <div class="flex justify-between gap-4">
+ <span>Usage credits</span>
+ <span>{formatCreditBalance(props.amountCents ?? 0)}</span>
+ </div>
+ <div class="mt-4 flex justify-between gap-4 border-t border-edge-muted pt-4">
+ <span>Total</span>
+ <span class="font-semibold">
+ {formatCreditBalance(props.amountCents ?? 0)}
+ </span>
+ </div>
+ </div>
+ <p class="text-xs text-ink-muted">
+ Choose or add your payment method and review your purchase in Stripe
+ Checkout.
+ </p>
+ <Show when={props.notice}>
+ <p class="text-sm text-ink-muted" role="status">
+ {props.notice}
+ </p>
+ </Show>
+ <Show when={props.error}>
+ <p class="text-sm text-failure" role="alert">
+ {props.error}
+ </p>
+ </Show>
+ <div class="flex justify-end gap-2">
+ <Button variant="ghost" depth={3} onClick={props.onClose}>
+ Cancel
+ </Button>
+ <Show
+ when={props.onViewPlans}
+ fallback={
+ <Button
+ variant="accent"
+ depth={3}
+ disabled={props.disabled || props.pending}
+ onClick={props.onCheckout}
+ >
+ {props.pending ? 'Opening checkout…' : 'Continue to checkout'}
+ </Button>
+ }
+ >
+ {(viewPlans) => (
+ <Button variant="accent" depth={3} onClick={viewPlans()}>
+ View plans
+ </Button>
+ )}
+ </Show>
+ </div>
+ </div>
+ <Button
+ class="absolute right-4 top-4"
+ size="icon-sm"
+ variant="ghost"
+ depth={3}
+ label="Close credit purchase"
+ onClick={props.onClose}
+ >
+ <XIcon class="size-4" />
+ </Button>
+ </Surface>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/usage/components/monthly-limit.tsx b/apps/web/src/features/usage/components/monthly-limit.tsx
new file mode 100644
index 0000000000..7f0660ffea
--- /dev/null
+++ b/apps/web/src/features/usage/components/monthly-limit.tsx
@@ -0,0 +1,65 @@
+import InfoIcon from '@phosphor/info.svg';
+import { Button, cn } from '@ui';
+import { Show } from 'solid-js';
+
+export function MonthlyLimit(props: {
+ percentage: number;
+ periodEnd: string;
+ unlimited?: boolean;
+ onInfo?: () => void;
+ infoButtonRef?: (button: HTMLButtonElement) => void;
+}) {
+ const resetDate = () => {
+ const date = new Date(props.periodEnd);
+ return Number.isNaN(date.getTime())
+ ? undefined
+ : date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+ };
+ const percentageLabel = () => `${Math.round(props.percentage)}%`;
+ return (
+ <div class="flex flex-col gap-3">
+ <div class="flex items-center justify-between gap-3">
+ <div class="flex items-center gap-1.5">
+ <h2 class="text-sm font-medium text-ink">Monthly limit</h2>
+ <Show when={props.onInfo}>
+ <Button
+ ref={props.infoButtonRef}
+ size="icon-sm"
+ variant="ghost"
+ depth={3}
+ label="About monthly usage"
+ onClick={props.onInfo}
+ >
+ <InfoIcon class="size-4 text-ink-muted" />
+ </Button>
+ </Show>
+ </div>
+ <span class="text-sm font-medium text-ink">
+ {props.unlimited ? 'Unlimited' : `${percentageLabel()} used`}
+ </span>
+ </div>
+ <Show when={!props.unlimited}>
+ <div
+ role="progressbar"
+ aria-label="Monthly limit"
+ aria-valuemin={0}
+ aria-valuemax={100}
+ aria-valuenow={props.percentage}
+ aria-valuetext={`${percentageLabel()} used`}
+ class="h-2 w-full overflow-hidden rounded-full bg-active"
+ >
+ <div
+ class={cn(
+ 'h-full rounded-full transition-[width]',
+ props.percentage >= 100 ? 'bg-failure' : 'bg-accent'
+ )}
+ style={{ width: `${props.percentage}%` }}
+ />
+ </div>
+ </Show>
+ <Show when={resetDate()}>
+ <p class="text-xs text-ink-muted">Resets {resetDate()}</p>
+ </Show>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/usage/components/usage-info-dialog.tsx b/apps/web/src/features/usage/components/usage-info-dialog.tsx
new file mode 100644
index 0000000000..a4f23ed3e1
--- /dev/null
+++ b/apps/web/src/features/usage/components/usage-info-dialog.tsx
@@ -0,0 +1,52 @@
+import XIcon from '@phosphor/x.svg';
+import { Button, Dialog, Surface } from '@ui';
+
+export function UsageInfoDialog(props: {
+ open: boolean;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+}) {
+ return (
+ <Dialog
+ open={props.open}
+ onOpenChange={(open) => !open && props.onClose()}
+ onCloseAutoFocus={
+ props.onRestoreFocus
+ ? (event) => {
+ event.preventDefault();
+ props.onRestoreFocus?.();
+ }
+ : undefined
+ }
+ position="center"
+ class="w-120"
+ >
+ <Surface depth={2} class="rounded-xl p-6">
+ <div class="flex items-start justify-between gap-4">
+ <Dialog.Title class="text-xl font-semibold text-ink">
+ Monthly limit
+ </Dialog.Title>
+ <Button
+ size="icon-sm"
+ variant="ghost"
+ depth={3}
+ label="Close usage explanation"
+ onClick={props.onClose}
+ >
+ <XIcon class="size-4" />
+ </Button>
+ </div>
+ <Dialog.Description class="mt-3 text-sm text-ink-muted">
+ Your monthly usage includes AI agent chat usage and AI document
+ editing.
+ </Dialog.Description>
+ <p class="mt-3 text-sm text-ink-muted">
+ The percentage shows how much of your plan's included usage you've
+ used in the current period. On paid plans, usage credits let you
+ continue after you reach your monthly limit. On the Free plan,
+ subscribe to a paid plan for more usage.
+ </p>
+ </Surface>
+ </Dialog>
+ );
+}
diff --git a/apps/web/src/features/usage/context/usage-context.ts b/apps/web/src/features/usage/context/usage-context.ts
new file mode 100644
index 0000000000..d764e0a017
--- /dev/null
+++ b/apps/web/src/features/usage/context/usage-context.ts
@@ -0,0 +1,46 @@
+import type { Accessor } from 'solid-js';
+import type {
+ AutoReloadSettings,
+ UsagePreviewPlan,
+ UsageSummary,
+} from '../core/usage';
+
+/** Capabilities supplied by the app; views can also be mounted with test sources. */
+export type UsageContext = {
+ available: Accessor<boolean>;
+ summary: Accessor<UsageSummary | undefined>;
+ loading: Accessor<boolean>;
+ failed: Accessor<boolean>;
+ refresh: () => void;
+ checkout: {
+ pending: Accessor<boolean>;
+ supportedAmounts: Accessor<readonly number[]>;
+ start: (amountCents: number) => Promise<string>;
+ };
+ autoReload: {
+ settings: Accessor<AutoReloadSettings>;
+ available: Accessor<boolean>;
+ pending: Accessor<boolean>;
+ save: (settings: AutoReloadSettings) => Promise<void>;
+ preview: Accessor<boolean>;
+ };
+ paymentMethods: {
+ pending: Accessor<boolean>;
+ open: () => Promise<string>;
+ };
+ existingUsageBilling: {
+ pending: Accessor<boolean>;
+ turnOff: () => Promise<void>;
+ };
+ navigateToPayment: (url: string) => void;
+ openPlans: () => void;
+ developer?: {
+ active: Accessor<boolean>;
+ plan: Accessor<UsagePreviewPlan | undefined>;
+ beforeLaunch: Accessor<boolean>;
+ previewPlan: (plan: UsagePreviewPlan) => void;
+ openLimitDialog: (plan: UsagePreviewPlan) => void;
+ previewBeforeLaunch: () => void;
+ reset: () => void;
+ };
+};
diff --git a/apps/web/src/features/usage/core/usage.test.ts b/apps/web/src/features/usage/core/usage.test.ts
new file mode 100644
index 0000000000..d16da2c46c
--- /dev/null
+++ b/apps/web/src/features/usage/core/usage.test.ts
@@ -0,0 +1,50 @@
+import { describe, expect, it } from 'vitest';
+import {
+ isUsageAvailable,
+ monthlyUsagePercent,
+ parseDollarInput,
+} from './usage';
+
+describe('monthly usage', () => {
+ it('measures included usage and clamps usage beyond the allowance', () => {
+ expect(monthlyUsagePercent(1_000, 4_000)).toBe(25);
+ expect(monthlyUsagePercent(6_000, 4_000)).toBe(100);
+ expect(monthlyUsagePercent(0, 0)).toBe(0);
+ expect(monthlyUsagePercent(100, 0)).toBe(100);
+ });
+});
+
+describe('dollar inputs', () => {
+ it('preserves cents and rejects fractional cents, exponents and invalid amounts', () => {
+ expect(parseDollarInput('25')).toBe(2_500);
+ expect(parseDollarInput(' 50.01 ')).toBe(5_001);
+ expect(parseDollarInput('10.1')).toBe(1_010);
+ for (const value of [
+ '',
+ '0',
+ '-10',
+ '1e2',
+ '25.001',
+ 'NaN',
+ '999999999999999999',
+ ]) {
+ expect(parseDollarInput(value)).toBeUndefined();
+ }
+ });
+});
+
+describe('Usage rollout', () => {
+ it.each([
+ { production: false, flag: false, available: true },
+ { production: false, flag: true, available: true },
+ { production: false, flag: undefined, available: true },
+ { production: true, flag: false, available: false },
+ { production: true, flag: true, available: true },
+ { production: true, flag: undefined, available: false },
+ ])(
+ 'production=$production flag=$flag yields available=$available',
+ ({ production, flag, available }) => {
+ expect(isUsageAvailable(production, flag)).toBe(available);
+ }
+ );
+});
diff --git a/apps/web/src/features/usage/core/usage.ts b/apps/web/src/features/usage/core/usage.ts
new file mode 100644
index 0000000000..996a108d76
--- /dev/null
+++ b/apps/web/src/features/usage/core/usage.ts
@@ -0,0 +1,70 @@
+export type UsageSummary = {
+ monthlyPercent: number;
+ periodEnd: string;
+ unlimited: boolean;
+ creditBalanceCents: number;
+ billingAccess: 'free' | 'payer' | 'team-member';
+ existingUsageBilling?: { limitCents: number; suspended: boolean };
+};
+
+export type UsagePreviewPlan = 'free' | 'paid';
+
+export type AutoReloadSettings = {
+ enabled: boolean;
+ minimumBalanceCents: number;
+ targetBalanceCents: number;
+ monthlySpendLimitCents: number | null;
+};
+
+export const DEFAULT_AUTO_RELOAD: AutoReloadSettings = {
+ enabled: false,
+ minimumBalanceCents: 1_000,
+ targetBalanceCents: 10_000,
+ monthlySpendLimitCents: null,
+};
+
+/** Development remains interactive; production follows the UI rollout flag. */
+export function isUsageAvailable(
+ production: boolean,
+ flagEnabled: boolean | undefined
+) {
+ return !production || flagEnabled === true;
+}
+
+export function monthlyUsagePercent(usedCents: number, includedCents: number) {
+ if (includedCents <= 0) return usedCents > 0 ? 100 : 0;
+ return Math.min(100, Math.max(0, (usedCents / includedCents) * 100));
+}
+
+export function formatCreditBalance(cents: number) {
+ return new Intl.NumberFormat('en-US', {
+ style: 'currency',
+ currency: 'USD',
+ minimumFractionDigits: cents % 100 === 0 ? 0 : 2,
+ }).format(cents / 100);
+}
+
+/** Parse decimal dollars without rounding fractional cents or accepting exponents. */
+export function parseDollarInput(value: string): number | undefined {
+ const match = /^(\d+)(?:\.(\d{1,2}))?$/.exec(value.trim());
+ if (!match) return;
+ const cents =
+ Number(match[1]) * 100 + Number((match[2] ?? '').padEnd(2, '0'));
+ return Number.isSafeInteger(cents) && cents > 0 ? cents : undefined;
+}
+
+export function validateAutoReload(
+ settings: AutoReloadSettings
+): string | undefined {
+ if (settings.minimumBalanceCents <= 0)
+ return 'Enter a minimum balance greater than $0.';
+ if (settings.targetBalanceCents <= settings.minimumBalanceCents) {
+ return 'Target balance must be greater than minimum balance.';
+ }
+ if (
+ settings.monthlySpendLimitCents !== null &&
+ settings.monthlySpendLimitCents <= 0
+ ) {
+ return 'Enter a monthly spend limit greater than $0, or leave it blank.';
+ }
+}
diff --git a/apps/web/src/features/usage/primitives/auto-reload-form.test.ts b/apps/web/src/features/usage/primitives/auto-reload-form.test.ts
new file mode 100644
index 0000000000..29068ffdee
--- /dev/null
+++ b/apps/web/src/features/usage/primitives/auto-reload-form.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from 'vitest';
+import { DEFAULT_AUTO_RELOAD } from '../core/usage';
+import { createAutoReloadForm } from './auto-reload-form';
+
+describe('Auto-Reload form', () => {
+ it('defaults to $10/$100, accepts an optional cap and rejects an inverted balance range', () => {
+ const form = createAutoReloadForm(DEFAULT_AUTO_RELOAD);
+ expect(form.error()).toBeUndefined();
+ expect(form.settings()).toEqual({ ...DEFAULT_AUTO_RELOAD, enabled: true });
+ form.setMaximum('125.50');
+ expect(form.settings()?.monthlySpendLimitCents).toBe(12_550);
+ form.setTarget('5');
+ expect(form.error()).toContain('Target balance must be greater');
+ form.setTarget('100');
+ form.setMaximum('');
+ expect(form.settings()?.monthlySpendLimitCents).toBeNull();
+ });
+});
diff --git a/apps/web/src/features/usage/primitives/auto-reload-form.ts b/apps/web/src/features/usage/primitives/auto-reload-form.ts
new file mode 100644
index 0000000000..38df1b0e19
--- /dev/null
+++ b/apps/web/src/features/usage/primitives/auto-reload-form.ts
@@ -0,0 +1,55 @@
+import { createSignal } from 'solid-js';
+import {
+ type AutoReloadSettings,
+ parseDollarInput,
+ validateAutoReload,
+} from '../core/usage';
+
+export function createAutoReloadForm(initial: AutoReloadSettings) {
+ const [minimum, setMinimum] = createSignal(
+ String(initial.minimumBalanceCents / 100)
+ );
+ const [target, setTarget] = createSignal(
+ String(initial.targetBalanceCents / 100)
+ );
+ const [maximum, setMaximum] = createSignal(
+ initial.monthlySpendLimitCents === null
+ ? ''
+ : String(initial.monthlySpendLimitCents / 100)
+ );
+ const settings = (): AutoReloadSettings | undefined => {
+ const minimumBalanceCents = parseDollarInput(minimum());
+ const targetBalanceCents = parseDollarInput(target());
+ const monthlySpendLimitCents = maximum().trim()
+ ? parseDollarInput(maximum())
+ : null;
+ if (
+ minimumBalanceCents === undefined ||
+ targetBalanceCents === undefined ||
+ monthlySpendLimitCents === undefined
+ )
+ return;
+ return {
+ enabled: true,
+ minimumBalanceCents,
+ targetBalanceCents,
+ monthlySpendLimitCents,
+ };
+ };
+ const error = () => {
+ const value = settings();
+ return value
+ ? validateAutoReload(value)
+ : 'Enter dollar amounts greater than $0, using at most two decimal places.';
+ };
+ return {
+ minimum,
+ setMinimum,
+ target,
+ setTarget,
+ maximum,
+ setMaximum,
+ settings,
+ error,
+ };
+}
diff --git a/apps/web/src/features/usage/queries/usage-summary.test.ts b/apps/web/src/features/usage/queries/usage-summary.test.ts
new file mode 100644
index 0000000000..e2e3c632c5
--- /dev/null
+++ b/apps/web/src/features/usage/queries/usage-summary.test.ts
@@ -0,0 +1,69 @@
+import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';
+import { describe, expect, it } from 'vitest';
+import { toUsageSummary } from './usage-summary';
+
+const snapshot: AiUsageSnapshot = {
+ tier: 'free',
+ unlimited: false,
+ payer: 'macro|[email protected]',
+ can_manage_billing: true,
+ seats: 1,
+ period_start: '2026-10-01T00:00:00Z',
+ period_end: '2026-11-01T00:00:00Z',
+ included_cents: 500,
+ used_cents: 250,
+ credits_consumed_cents: 0,
+ credit_balance_cents: 2_500,
+ overage_enabled: false,
+ overage_limit_cents: 0,
+ overage_charged_cents: 0,
+ overage_suspended: false,
+ uncovered_cents: 0,
+ remaining_cents: 250,
+};
+
+describe('usage billing access', () => {
+ it('marks a Free payer as ineligible for credit purchases', () => {
+ expect(toUsageSummary(snapshot)).toMatchObject({
+ billingAccess: 'free',
+ monthlyPercent: 50,
+ creditBalanceCents: 2_500,
+ });
+ });
+
+ it.each(['premium', 'max'] as const)(
+ 'does not grant billing access to a %s non-payer',
+ (tier) => {
+ expect(
+ toUsageSummary({ ...snapshot, tier, can_manage_billing: false })
+ .billingAccess
+ ).toBe('team-member');
+ }
+ );
+
+ it('still displays a Free monthly allowance supplied by the backend', () => {
+ expect(
+ toUsageSummary({ ...snapshot, included_cents: 1_000, used_cents: 250 })
+ ).toMatchObject({
+ billingAccess: 'free',
+ monthlyPercent: 25,
+ });
+ });
+
+ it('shows an exhausted Free allowance without granting access to legacy credits', () => {
+ expect(
+ toUsageSummary({
+ ...snapshot,
+ used_cents: 500,
+ blocked_reason: 'free_allowance_exhausted',
+ })
+ ).toMatchObject({ billingAccess: 'free', monthlyPercent: 100 });
+ });
+
+ it.each(['premium', 'max'] as const)(
+ 'lets a %s payer purchase credits',
+ (tier) => {
+ expect(toUsageSummary({ ...snapshot, tier }).billingAccess).toBe('payer');
+ }
+ );
+});
diff --git a/apps/web/src/features/usage/queries/usage-summary.ts b/apps/web/src/features/usage/queries/usage-summary.ts
new file mode 100644
index 0000000000..87714bc1ab
--- /dev/null
+++ b/apps/web/src/features/usage/queries/usage-summary.ts
@@ -0,0 +1,28 @@
+import type { AiUsageSnapshot } from '@service-auth/ai-billing-types';
+import { monthlyUsagePercent, type UsageSummary } from '../core/usage';
+
+export function toUsageSummary(snapshot: AiUsageSnapshot): UsageSummary {
+ return {
+ monthlyPercent: monthlyUsagePercent(
+ snapshot.used_cents,
+ snapshot.included_cents
+ ),
+ periodEnd: snapshot.period_end,
+ unlimited: snapshot.unlimited,
+ creditBalanceCents: snapshot.credit_balance_cents,
+ existingUsageBilling:
+ snapshot.tier !== 'free' &&
+ (snapshot.overage_enabled || snapshot.overage_suspended)
+ ? {
+ limitCents: snapshot.overage_limit_cents,
+ suspended: snapshot.overage_suspended,
+ }
+ : undefined,
+ billingAccess:
+ snapshot.tier === 'free'
+ ? 'free'
+ : snapshot.can_manage_billing
+ ? 'payer'
+ : 'team-member',
+ };
+}
diff --git a/apps/web/src/features/usage/usage.tsx b/apps/web/src/features/usage/usage.tsx
new file mode 100644
index 0000000000..7210b31c1b
--- /dev/null
+++ b/apps/web/src/features/usage/usage.tsx
@@ -0,0 +1,172 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import {
+ DEV_MODE_ENV,
+ enableAiUsageBilling,
+ LOCAL_ONLY,
+ PROD_MODE_ENV,
+} from '@core/constant/featureFlags';
+import { useSettingsState } from '@core/constant/SettingsState';
+import {
+ useAiBillingPlansQuery,
+ useAiBillingSummaryQuery,
+ useCreateAiCreditCheckoutMutation,
+ useCreateBillingPortalMutation,
+ useUpdateAiOverageMutation,
+} from '@queries/auth';
+import { createSignal, Suspense } from 'solid-js';
+import { useAiUsagePreview } from '../paywall/ai-usage-preview';
+import type { UsageContext } from './context/usage-context';
+import {
+ type AutoReloadSettings,
+ DEFAULT_AUTO_RELOAD,
+ isUsageAvailable,
+} from './core/usage';
+import { toUsageSummary } from './queries/usage-summary';
+import { UsageSettingsView } from './views/usage-settings';
+
+export function Usage() {
+ const summary = useAiBillingSummaryQuery();
+ const plans = useAiBillingPlansQuery();
+ const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
+ const checkout = useCreateAiCreditCheckoutMutation();
+ const portal = useCreateBillingPortalMutation();
+ const overage = useUpdateAiOverageMutation();
+ const usagePreview = useAiUsagePreview();
+ const { showUsageLimit, hideUsageLimit } = useAiUsageLimitState();
+ const { openSettings } = useSettingsState();
+ const autoReloadPreview = () => usagePreview.plan() === 'paid';
+ const [previewSettings, setPreviewSettings] =
+ createSignal<AutoReloadSettings>({ ...DEFAULT_AUTO_RELOAD });
+ const previewing = usagePreview.active;
+ const available = () =>
+ !usagePreview.beforeLaunch() &&
+ isUsageAvailable(PROD_MODE_ENV && !LOCAL_ONLY, aiUsageBilling().enabled);
+ const returnUrl = `${window.location.origin}/app/settings/usage`;
+ const context: UsageContext = {
+ available,
+ summary: () => {
+ const snapshot = usagePreview.withPreview(
+ summary.isSuccess ? summary.data : undefined,
+ plans.isSuccess ? plans.data.plans : undefined
+ );
+ return snapshot ? toUsageSummary(snapshot) : undefined;
+ },
+ loading: () => summary.isPending,
+ failed: () => summary.isError,
+ refresh: () => {
+ void summary.refetch();
+ },
+ checkout: {
+ pending: () => checkout.isPending,
+ supportedAmounts: () =>
+ plans.isSuccess
+ ? plans.data.credit_packs_cents
+ : [1_000, 2_500, 5_000, 10_000],
+ start: async (amountCents) => {
+ if (
+ !available() ||
+ previewing() ||
+ !summary.isSuccess ||
+ summary.data.unlimited ||
+ summary.data.tier === 'free' ||
+ !summary.data.can_manage_billing
+ )
+ throw new Error('Credit purchase unavailable');
+ return await checkout.mutateAsync({
+ amountCents,
+ successUrl: `${returnUrl}?aiCreditsSuccess=true`,
+ cancelUrl: `${returnUrl}?aiCreditsCancel=true`,
+ });
+ },
+ },
+ autoReload: {
+ settings: () =>
+ autoReloadPreview() ? previewSettings() : DEFAULT_AUTO_RELOAD,
+ available: () => available() && DEV_MODE_ENV && autoReloadPreview(),
+ pending: () => false,
+ preview: autoReloadPreview,
+ save: async (settings) => {
+ // No auto-reload API exists yet. Only the explicit development preview can save.
+ if (!available() || !DEV_MODE_ENV || !autoReloadPreview())
+ throw new Error('Auto-Reload unavailable');
+ setPreviewSettings(settings);
+ },
+ },
+ paymentMethods: {
+ pending: () => portal.isPending,
+ open: async () => {
+ if (
+ !available() ||
+ previewing() ||
+ !summary.isSuccess ||
+ summary.data.tier === 'free' ||
+ !summary.data.can_manage_billing
+ )
+ throw new Error('Payment methods unavailable');
+ return await portal.mutateAsync({ returnUrl });
+ },
+ },
+ navigateToPayment: (url) => {
+ if (!available()) return;
+ window.location.href = url;
+ },
+ openPlans: () => {
+ if (available()) openSettings('Billing');
+ },
+ existingUsageBilling: {
+ pending: () => overage.isPending,
+ turnOff: async () => {
+ if (
+ !available() ||
+ previewing() ||
+ !summary.isSuccess ||
+ summary.data.tier === 'free' ||
+ !summary.data.can_manage_billing
+ )
+ throw new Error('Usage billing unavailable');
+ await overage.mutateAsync({
+ enabled: false,
+ limitCents: summary.data.overage_limit_cents,
+ });
+ },
+ },
+ developer: DEV_MODE_ENV
+ ? {
+ active: usagePreview.active,
+ plan: usagePreview.plan,
+ beforeLaunch: usagePreview.beforeLaunch,
+ previewPlan: (plan) => {
+ hideUsageLimit();
+ setPreviewSettings({ ...DEFAULT_AUTO_RELOAD });
+ usagePreview.previewPlan(plan);
+ },
+ openLimitDialog: (plan) => {
+ if (!available()) return;
+ setPreviewSettings({ ...DEFAULT_AUTO_RELOAD });
+ usagePreview.previewLimit(plan);
+ showUsageLimit(
+ plan === 'free'
+ ? 'ai_free_allowance_exhausted'
+ : 'ai_allowance_exhausted'
+ );
+ },
+ previewBeforeLaunch: () => {
+ hideUsageLimit();
+ setPreviewSettings({ ...DEFAULT_AUTO_RELOAD });
+ usagePreview.previewBeforeLaunch();
+ },
+ reset: () => {
+ usagePreview.reset();
+ setPreviewSettings({ ...DEFAULT_AUTO_RELOAD });
+ hideUsageLimit();
+ },
+ }
+ : undefined,
+ };
+ return (
+ <Suspense fallback={<p role="status">Loading usage…</p>}>
+ <UsageSettingsView context={context} />
+ </Suspense>
+ );
+}
diff --git a/apps/web/src/features/usage/views/auto-reload.tsx b/apps/web/src/features/usage/views/auto-reload.tsx
new file mode 100644
index 0000000000..c206d0d276
--- /dev/null
+++ b/apps/web/src/features/usage/views/auto-reload.tsx
@@ -0,0 +1,81 @@
+import { createSignal } from 'solid-js';
+import { AutoReloadDialog } from '../components/auto-reload-dialog';
+import type { UsageContext } from '../context/usage-context';
+import { createAutoReloadForm } from '../primitives/auto-reload-form';
+
+export function AutoReloadView(props: {
+ context: UsageContext;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+}) {
+ const form = createAutoReloadForm(props.context.autoReload.settings());
+ const [error, setError] = createSignal<string>();
+ const notice = () => {
+ if (props.context.autoReload.preview())
+ return 'Developer preview. These settings only change this preview and will not charge your card.';
+ if (!props.context.autoReload.available())
+ return 'Automatic reload is not available yet. You can buy usage credits manually.';
+ };
+ const save = async (enabled: boolean) => {
+ const settings = enabled
+ ? form.settings()
+ : props.context.autoReload.settings();
+ if (
+ !settings ||
+ !props.context.autoReload.available() ||
+ props.context.autoReload.pending() ||
+ (enabled && form.error())
+ )
+ return;
+ setError(undefined);
+ try {
+ await props.context.autoReload.save({ ...settings, enabled });
+ props.onClose();
+ } catch {
+ setError("Couldn't save Auto-Reload settings. Please try again.");
+ }
+ };
+ const paymentMethods = async () => {
+ if (
+ props.context.summary()?.billingAccess !== 'payer' ||
+ props.context.autoReload.preview() ||
+ props.context.developer?.active() ||
+ props.context.paymentMethods.pending()
+ )
+ return;
+ setError(undefined);
+ try {
+ const url = await props.context.paymentMethods.open();
+ props.context.navigateToPayment(url);
+ } catch {
+ setError("Couldn't open payment methods. Please try again.");
+ }
+ };
+ return (
+ <AutoReloadDialog
+ enabled={props.context.autoReload.settings().enabled}
+ minimum={form.minimum()}
+ target={form.target()}
+ maximum={form.maximum()}
+ onMinimum={form.setMinimum}
+ onTarget={form.setTarget}
+ onMaximum={form.setMaximum}
+ onClose={props.onClose}
+ onRestoreFocus={props.onRestoreFocus}
+ onSave={() => void save(true)}
+ onTurnOff={() => void save(false)}
+ onPaymentMethods={() => void paymentMethods()}
+ canManagePaymentMethods={
+ props.context.summary()?.billingAccess === 'payer' &&
+ !props.context.autoReload.preview() &&
+ !props.context.developer?.active()
+ }
+ pending={props.context.autoReload.pending()}
+ paymentMethodsPending={props.context.paymentMethods.pending()}
+ disabled={!props.context.autoReload.available()}
+ invalid={!!form.error()}
+ notice={notice()}
+ error={form.error() ?? error()}
+ />
+ );
+}
diff --git a/apps/web/src/features/usage/views/credit-purchase.tsx b/apps/web/src/features/usage/views/credit-purchase.tsx
new file mode 100644
index 0000000000..a6cdc0bdc0
--- /dev/null
+++ b/apps/web/src/features/usage/views/credit-purchase.tsx
@@ -0,0 +1,85 @@
+import { thrownResultErrorHasCode } from '@core/util/result';
+import { createSignal } from 'solid-js';
+import { CreditPurchaseDialog } from '../components/credit-purchase-dialog';
+import type { UsageContext } from '../context/usage-context';
+import { parseDollarInput } from '../core/usage';
+
+export function CreditPurchaseView(props: {
+ context: UsageContext;
+ onClose: () => void;
+ onRestoreFocus?: () => void;
+}) {
+ const [selection, setSelection] = createSignal<number | 'other'>(2_500);
+ const [customAmount, setCustomAmount] = createSignal('');
+ const [error, setError] = createSignal<string>();
+ const [subscriptionRequired, setSubscriptionRequired] = createSignal(false);
+ const amountCents = () => {
+ const selected = selection();
+ return typeof selected === 'number'
+ ? selected
+ : parseDollarInput(customAmount());
+ };
+ const previewing = () =>
+ props.context.developer?.active() || props.context.autoReload.preview();
+ const notice = () => {
+ if (previewing())
+ return 'Credit purchases are disabled during the developer preview.';
+ if (props.context.summary()?.unlimited)
+ return 'Your plan includes unlimited AI usage. No additional credits are needed.';
+ if (props.context.summary()?.billingAccess === 'free')
+ return 'Subscribe to a paid plan to buy additional usage credits.';
+ if (props.context.summary()?.billingAccess !== 'payer')
+ return 'Your team owner manages usage credits. Ask them to add credits.';
+ const amount = amountCents();
+ if (amount === undefined)
+ return 'Enter an amount greater than $0, using at most two decimal places.';
+ if (!props.context.checkout.supportedAmounts().includes(amount))
+ return 'Custom credit amounts are not available yet. Choose $25, $50, or $100.';
+ };
+ const checkout = async () => {
+ const amount = amountCents();
+ if (notice() || amount === undefined || props.context.checkout.pending())
+ return;
+ setError(undefined);
+ try {
+ const url = await props.context.checkout.start(amount);
+ props.context.navigateToPayment(url);
+ } catch (error) {
+ const needsPlan = thrownResultErrorHasCode(error, 'PAID_PLAN_REQUIRED');
+ setSubscriptionRequired(needsPlan);
+ setError(
+ needsPlan
+ ? 'Subscribe to a paid plan to buy additional usage credits.'
+ : "Couldn't start checkout. Please try again."
+ );
+ }
+ };
+ return (
+ <CreditPurchaseDialog
+ selection={selection()}
+ customAmount={customAmount()}
+ amountCents={amountCents()}
+ onSelect={(value) => {
+ setSelection(value);
+ setError(undefined);
+ }}
+ onCustomAmount={setCustomAmount}
+ onClose={props.onClose}
+ onRestoreFocus={props.onRestoreFocus}
+ onCheckout={() => void checkout()}
+ onViewPlans={
+ (props.context.summary()?.billingAccess === 'free' && !previewing()) ||
+ subscriptionRequired()
+ ? () => {
+ props.onClose();
+ props.context.openPlans();
+ }
+ : undefined
+ }
+ pending={props.context.checkout.pending()}
+ disabled={!!notice()}
+ notice={notice()}
+ error={error()}
+ />
+ );
+}
diff --git a/apps/web/src/features/usage/views/usage-settings.tsx b/apps/web/src/features/usage/views/usage-settings.tsx
new file mode 100644
index 0000000000..61a079c361
--- /dev/null
+++ b/apps/web/src/features/usage/views/usage-settings.tsx
@@ -0,0 +1,336 @@
+import { Button, cn } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import {
+ SettingsCard,
+ SettingsPage,
+ SettingsRow,
+ SettingsSection,
+} from '../../settings/primitives';
+import { MonthlyLimit } from '../components/monthly-limit';
+import { UsageInfoDialog } from '../components/usage-info-dialog';
+import type { UsageContext } from '../context/usage-context';
+import { formatCreditBalance } from '../core/usage';
+import { AutoReloadView } from './auto-reload';
+import { CreditPurchaseView } from './credit-purchase';
+
+export function UsageSettingsView(props: { context: UsageContext }) {
+ const [infoOpen, setInfoOpen] = createSignal(false);
+ const [purchaseOpen, setPurchaseOpen] = createSignal(false);
+ const [autoReloadOpen, setAutoReloadOpen] = createSignal(false);
+ const [billingError, setBillingError] = createSignal<string>();
+ // Controlled dialogs have no Dialog.Trigger; restore their actual opener on close.
+ let infoTrigger: HTMLButtonElement | undefined;
+ let purchaseTrigger: HTMLButtonElement | undefined;
+ let autoReloadTrigger: HTMLButtonElement | undefined;
+ const turnOffUsageBilling = async () => {
+ if (
+ props.context.developer?.active() ||
+ props.context.autoReload.preview() ||
+ props.context.existingUsageBilling.pending()
+ )
+ return;
+ setBillingError(undefined);
+ try {
+ await props.context.existingUsageBilling.turnOff();
+ } catch {
+ setBillingError("Couldn't turn off usage billing. Please try again.");
+ }
+ };
+ return (
+ <SettingsPage title="Usage">
+ <Show when={!props.context.available()}>
+ <SettingsCard>
+ <div class="flex flex-col gap-2 p-6" role="status">
+ <p class="font-medium text-ink">
+ AI billing changes take effect on October 8, 2026.
+ </p>
+ <p class="text-sm text-ink-muted">
+ Usage is not metered until these changes take effect.
+ </p>
+ </div>
+ </SettingsCard>
+ </Show>
+ <fieldset
+ disabled={!props.context.available()}
+ class="flex min-w-0 flex-col gap-12 touch:gap-6"
+ classList={{ 'opacity-50': !props.context.available() }}
+ >
+ <Show
+ when={props.context.summary()}
+ fallback={
+ <SettingsCard>
+ <div class="flex flex-col gap-3 p-6" role="status">
+ <p class="text-sm text-ink-muted">
+ {props.context.failed()
+ ? "Couldn't load usage. Please try again."
+ : 'Loading usage…'}
+ </p>
+ <Show when={props.context.failed()}>
+ <Button
+ class="self-start"
+ variant="outline"
+ depth={3}
+ onClick={props.context.refresh}
+ >
+ Try again
+ </Button>
+ </Show>
+ </div>
+ </SettingsCard>
+ }
+ >
+ {(summary) => (
+ <>
+ <SettingsCard>
+ <div class="p-6">
+ <MonthlyLimit
+ percentage={summary().monthlyPercent}
+ periodEnd={summary().periodEnd}
+ unlimited={summary().unlimited}
+ onInfo={() => setInfoOpen(true)}
+ infoButtonRef={(button) => {
+ infoTrigger = button;
+ }}
+ />
+ </div>
+ </SettingsCard>
+ <Show
+ when={
+ summary().billingAccess === 'free' &&
+ !props.context.autoReload.preview()
+ }
+ >
+ <SettingsCard>
+ <SettingsRow
+ label="Need more AI usage?"
+ description="Subscribe to a paid plan to keep going."
+ >
+ <Button
+ variant="accent"
+ depth={3}
+ size="sm"
+ onClick={props.context.openPlans}
+ >
+ View plans
+ </Button>
+ </SettingsRow>
+ </SettingsCard>
+ </Show>
+ <Show
+ when={
+ (!summary().unlimited &&
+ summary().billingAccess !== 'free') ||
+ props.context.autoReload.preview()
+ }
+ >
+ <SettingsSection
+ title="Usage Credits"
+ description="Buy credits or turn on automatic reload to continue using Macro AI when you reach usage limits"
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={
+ <span class="font-medium">
+ {formatCreditBalance(summary().creditBalanceCents)}{' '}
+ credits remaining
+ </span>
+ }
+ description="Current balance"
+ >
+ <Button
+ ref={(button) => {
+ purchaseTrigger = button;
+ }}
+ variant="outline"
+ depth={3}
+ size="sm"
+ class="rounded-full px-4"
+ onClick={() => setPurchaseOpen(true)}
+ >
+ Add more
+ </Button>
+ </SettingsRow>
+ <SettingsRow label="Automatic reload">
+ <button
+ ref={(button) => {
+ autoReloadTrigger = button;
+ }}
+ type="button"
+ aria-label="Configure Automatic reload"
+ aria-haspopup="dialog"
+ aria-expanded={autoReloadOpen()}
+ class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full transition-colors focus-visible:outline-2 focus-visible:outline-accent focus-visible:outline-offset-2"
+ classList={{
+ 'bg-accent':
+ props.context.autoReload.settings().enabled,
+ 'bg-ink-muted/40':
+ !props.context.autoReload.settings().enabled,
+ }}
+ onClick={() => setAutoReloadOpen(true)}
+ >
+ <span
+ aria-hidden="true"
+ class={cn(
+ 'absolute left-0.5 size-4 rounded-full bg-surface transition-transform',
+ props.context.autoReload.settings().enabled &&
+ 'translate-x-4'
+ )}
+ />
+ <span class="sr-only">
+ Currently{' '}
+ {props.context.autoReload.settings().enabled
+ ? 'on'
+ : 'off'}
+ </span>
+ </button>
+ </SettingsRow>
+ </SettingsCard>
+ </SettingsSection>
+ </Show>
+ <Show when={summary().existingUsageBilling}>
+ {(billing) => (
+ <SettingsSection
+ title="Existing usage billing"
+ description="This bills additional usage to your card after it happens. It does not automatically reload credits."
+ >
+ <SettingsCard>
+ <SettingsRow
+ label={
+ billing().suspended
+ ? 'Usage billing paused'
+ : 'Usage billing enabled'
+ }
+ description={`Limit: ${formatCreditBalance(billing().limitCents)} per period`}
+ >
+ <Show when={summary().billingAccess === 'payer'}>
+ <Button
+ variant="outline"
+ depth={3}
+ size="sm"
+ disabled={
+ props.context.existingUsageBilling.pending() ||
+ props.context.developer?.active() ||
+ props.context.autoReload.preview()
+ }
+ onClick={() => void turnOffUsageBilling()}
+ >
+ Turn off usage billing
+ </Button>
+ </Show>
+ </SettingsRow>
+ </SettingsCard>
+ <Show when={billingError()}>
+ <p class="text-sm text-failure" role="alert">
+ {billingError()}
+ </p>
+ </Show>
+ </SettingsSection>
+ )}
+ </Show>
+ </>
+ )}
+ </Show>
+ </fieldset>
+ <Show when={props.context.developer}>
+ {(developer) => (
+ <SettingsSection
+ title="Developer tools"
+ description="Preview usage states without changing account billing."
+ >
+ <SettingsCard>
+ <div class="flex flex-col gap-3 p-4">
+ <div class="flex flex-wrap gap-2">
+ <Button
+ variant={
+ developer().plan() === 'free' ? 'accent' : 'outline'
+ }
+ depth={3}
+ size="sm"
+ aria-pressed={developer().plan() === 'free'}
+ onClick={() => developer().previewPlan('free')}
+ >
+ Preview Free plan
+ </Button>
+ <Button
+ variant={
+ developer().plan() === 'paid' ? 'accent' : 'outline'
+ }
+ depth={3}
+ size="sm"
+ aria-pressed={developer().plan() === 'paid'}
+ onClick={() => developer().previewPlan('paid')}
+ >
+ Preview paid plan
+ </Button>
+ <Button
+ variant="outline"
+ depth={3}
+ size="sm"
+ disabled={developer().beforeLaunch()}
+ onClick={() => developer().openLimitDialog('free')}
+ >
+ Open Free usage-limit dialog
+ </Button>
+ <Button
+ variant="outline"
+ depth={3}
+ size="sm"
+ disabled={developer().beforeLaunch()}
+ onClick={() => developer().openLimitDialog('paid')}
+ >
+ Open paid usage-limit dialog
+ </Button>
+ <Button
+ variant={developer().beforeLaunch() ? 'accent' : 'outline'}
+ depth={3}
+ size="sm"
+ aria-pressed={developer().beforeLaunch()}
+ onClick={developer().previewBeforeLaunch}
+ >
+ Preview production before Oct 8
+ </Button>
+ <Button
+ variant="ghost"
+ depth={3}
+ size="sm"
+ disabled={!developer().active()}
+ onClick={developer().reset}
+ >
+ Reset preview
+ </Button>
+ </div>
+ <Show when={developer().active()}>
+ <p class="text-xs text-ink-muted" role="status">
+ Developer preview active. No purchases or automatic charges
+ can be made. Reset the preview to restore real usage.
+ </p>
+ </Show>
+ </div>
+ </SettingsCard>
+ </SettingsSection>
+ )}
+ </Show>
+ <Show when={props.context.available() && infoOpen()}>
+ <UsageInfoDialog
+ open={infoOpen()}
+ onClose={() => setInfoOpen(false)}
+ onRestoreFocus={() => infoTrigger?.focus()}
+ />
+ </Show>
+ <Show when={props.context.available() && purchaseOpen()}>
+ <CreditPurchaseView
+ context={props.context}
+ onClose={() => setPurchaseOpen(false)}
+ onRestoreFocus={() => purchaseTrigger?.focus()}
+ />
+ </Show>
+ <Show when={props.context.available() && autoReloadOpen()}>
+ <AutoReloadView
+ context={props.context}
+ onClose={() => setAutoReloadOpen(false)}
+ onRestoreFocus={() => autoReloadTrigger?.focus()}
+ />
+ </Show>
+ </SettingsPage>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx
deleted file mode 100644
index dab9985123..0000000000
--- a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.test.tsx
+++ /dev/null
@@ -1,281 +0,0 @@
-/**
- * @vitest-environment jsdom
- */
-
-import {
- MODEL_PRETTYNAME,
- Model,
- modelsForPlan,
- PAID_MODELS,
- type TModel,
-} from '@core/component/AI/constant';
-import { cleanup, fireEvent, render } from '@solidjs/testing-library';
-import { createSignal, type JSX } from 'solid-js';
-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-import { type ModelOption, ModelSelector } from './ModelSelector';
-
-const state = vi.hoisted(() => ({ aiUsageBilling: false, mobile: false }));
-vi.mock('@core/constant/featureFlags', () => ({
- enableAiUsageBilling: { key: 'enable-ai-usage-billing', override: undefined },
-}));
-vi.mock('@app/lib/analytics/posthog', () => ({
- useFeatureFlag: () => () => ({
- enabled: state.aiUsageBilling,
- payload: undefined,
- loading: false,
- }),
-}));
-vi.mock('@core/mobile/isMobile', () => ({ isMobile: () => state.mobile }));
-vi.mock('@components/app/mobile/MobileDrawer', () => {
- const Slot = (props: { children?: JSX.Element }) => (
- <div>{props.children}</div>
- );
- return {
- MobileDrawer: Object.assign(Slot, {
- Trigger: Slot,
- Portal: Slot,
- Overlay: Slot,
- Content: Slot,
- Handle: Slot,
- Close: Slot,
- ScrollBody: Slot,
- Section: Slot,
- Item: Slot,
- }),
- };
-});
-
-beforeEach(() => {
- state.aiUsageBilling = false;
- state.mobile = false;
-});
-afterEach(cleanup);
-
-// Render the Kobalte dropdown as a transparent passthrough so the menu items
-// are always in the DOM — we're testing ModelSelector's own logic (which models
-// render, lock state, select vs. paywall routing), not the dropdown primitive.
-vi.mock('@ui', () => {
- const cn = (...args: unknown[]) =>
- args.flat(Infinity).filter(Boolean).join(' ');
- const Dropdown: any = (p: any) => <div>{p.children}</div>;
- Dropdown.Trigger = (p: any) => (
- <button type="button" data-trigger class={p.class}>
- {p.children}
- </button>
- );
- Dropdown.Content = (p: any) => <div>{p.children}</div>;
- Dropdown.Group = (p: any) => <div>{p.children}</div>;
- Dropdown.Item = (p: any) => (
- <div role="menuitem" class={p.class} onClick={() => p.onSelect?.()}>
- {p.children}
- </div>
- );
- return {
- cn,
- Dropdown,
- Button: (props: { children?: JSX.Element }) => (
- <button type="button">{props.children}</button>
- ),
- };
-});
-
-// Neutralize SVG imports; tag the lock so we can assert it renders.
-vi.mock('@icon/wide-claude.svg', () => ({
- default: () => null,
-}));
-vi.mock('@core/component/AI/assets/openai.svg', () => ({
- default: () => null,
-}));
-vi.mock('@phosphor-icons/core/regular/caret-down.svg?component-solid', () => ({
- default: () => null,
-}));
-vi.mock('@phosphor-icons/core/regular/lock-simple.svg?component-solid', () => ({
- default: () => <span data-testid="lock-icon" />,
-}));
-
-const ALL_PAID: ModelOption[] = PAID_MODELS.map((id) => ({
- id,
- available: true,
-}));
-
-/** Find the menu item row for a model by its pretty name. */
-function itemFor(container: HTMLElement, model: TModel): HTMLElement {
- const rows = Array.from(
- container.querySelectorAll('[role="menuitem"]')
- ) as HTMLElement[];
- const row = rows.find((r) =>
- r.textContent?.includes(MODEL_PRETTYNAME[model])
- );
- if (!row) throw new Error(`no menu item for ${model}`);
- return row;
-}
-
-describe('ModelSelector: availability', () => {
- it('lists every provided model', () => {
- const { container } = render(() => (
- <ModelSelector models={ALL_PAID} onSelect={() => {}} />
- ));
- expect(container.querySelectorAll('[role="menuitem"]')).toHaveLength(
- ALL_PAID.length
- );
- });
-
- it('does not list retired Anthropic models', () => {
- const { container } = render(() => (
- <ModelSelector models={ALL_PAID} onSelect={() => {}} />
- ));
- for (const retired of ['Fable', 'Sonnet 5 ', 'Opus 5 ']) {
- expect(container.textContent).not.toContain(retired);
- }
- expect(container.textContent).toContain('Sonnet 5.5');
- expect(container.textContent).toContain('Opus 5.5');
- expect(container.textContent).toContain('Haiku 4.5');
- });
-
- it.each([
- { aiUsageBilling: false, mobile: false },
- { aiUsageBilling: true, mobile: false },
- { aiUsageBilling: false, mobile: true },
- { aiUsageBilling: true, mobile: true },
- ])(
- 'gates usage multipliers on enable-ai-usage-billing ($aiUsageBilling), mobile=$mobile',
- ({ aiUsageBilling, mobile }) => {
- state.aiUsageBilling = aiUsageBilling;
- state.mobile = mobile;
- const { container } = render(() => (
- <ModelSelector models={ALL_PAID} onSelect={() => {}} />
- ));
- expect(container.textContent?.includes('× usage')).toBe(aiUsageBilling);
- }
- );
-
- it('grays out and locks inaccessible models, leaving accessible ones clean', () => {
- // A free user: only the fast model is available.
- const freeAllowed = modelsForPlan(false);
- const options: ModelOption[] = PAID_MODELS.map((id) => ({
- id,
- available: freeAllowed.includes(id),
- }));
- const { container } = render(() => (
- <ModelSelector models={options} onSelect={() => {}} />
- ));
-
- const available = itemFor(container, Model.haiku45);
- expect(available.className).not.toContain('opacity-50');
- expect(available.querySelector('[data-testid="lock-icon"]')).toBeNull();
-
- const locked = itemFor(container, Model.opus55);
- expect(locked.className).toContain('opacity-50');
- expect(locked.querySelector('[data-testid="lock-icon"]')).not.toBeNull();
- });
-});
-
-describe('ModelSelector: selection routing', () => {
- it('selecting an available model calls onSelect, not onLocked', () => {
- const onSelect = vi.fn();
- const onLocked = vi.fn();
- const { container } = render(() => (
- <ModelSelector
- models={ALL_PAID}
- onSelect={onSelect}
- onLocked={onLocked}
- />
- ));
-
- fireEvent.click(itemFor(container, Model.gpt56));
- expect(onSelect).toHaveBeenCalledWith(Model.gpt56);
- expect(onLocked).not.toHaveBeenCalled();
- });
-
- it('selecting an inaccessible model triggers the paywall (onLocked), not a send', () => {
- const onSelect = vi.fn();
- const onLocked = vi.fn();
- const freeAllowed = modelsForPlan(false);
- const options: ModelOption[] = PAID_MODELS.map((id) => ({
- id,
- available: freeAllowed.includes(id),
- }));
- const { container } = render(() => (
- <ModelSelector models={options} onSelect={onSelect} onLocked={onLocked} />
- ));
-
- fireEvent.click(itemFor(container, Model.opus55)); // locked for a free user
- expect(onLocked).toHaveBeenCalledWith(Model.opus55);
- expect(onSelect).not.toHaveBeenCalled();
- });
-});
-
-describe('ModelSelector: what is shown is what is sent', () => {
- // The selector's trigger and the message it would send both read the same
- // model accessor. Picking a model updates that single source, so the request
- // can never diverge from what the selector displays.
- function Harness() {
- const [model, setModel] = createSignal<TModel>(Model.opus55);
- return (
- <>
- {/* stand-in for the value sendMessage() reads */}
- <span data-testid="would-send">{model()}</span>
- <ModelSelector
- selectedModel={model()}
- models={ALL_PAID}
- onSelect={setModel}
- />
- </>
- );
- }
-
- it('reflects the selected model in the trigger and in the would-send value', () => {
- const { container, getByTestId } = render(() => <Harness />);
-
- // Initial state: trigger shows the selected model.
- const trigger = container.querySelector('[data-trigger]')!;
- expect(trigger.textContent).toContain(MODEL_PRETTYNAME[Model.opus55]);
- expect(getByTestId('would-send').textContent).toBe(Model.opus55);
-
- // Select a different model -> both the trigger and the would-send value move
- // together to exactly that model.
- fireEvent.click(itemFor(container, Model.sonnet55));
- expect(getByTestId('would-send').textContent).toBe(Model.sonnet55);
- expect(trigger.textContent).toContain(MODEL_PRETTYNAME[Model.sonnet55]);
- });
-
- it('a free user cannot select an inaccessible model into the would-send value', () => {
- const onLocked = vi.fn();
- const freeAllowed = modelsForPlan(false);
- const options: ModelOption[] = PAID_MODELS.map((id) => ({
- id,
- available: freeAllowed.includes(id),
- }));
- function FreeHarness() {
- const [model, setModel] = createSignal<TModel>(Model.haiku45);
- return (
- <>
- <span data-testid="would-send">{model()}</span>
- <ModelSelector
- selectedModel={model()}
- models={options}
- onSelect={setModel}
- onLocked={onLocked}
- />
- </>
- );
- }
- const { container, getByTestId } = render(() => <FreeHarness />);
-
- fireEvent.click(itemFor(container, Model.opus55)); // locked
- // The would-send value is unchanged; only the paywall fired.
- expect(getByTestId('would-send').textContent).toBe(Model.haiku45);
- expect(onLocked).toHaveBeenCalledWith(Model.opus55);
- });
-});
-
-// GAP / out of unit scope: the on-mount reconcile that forces a *persisted or
-// chat-provided* inaccessible model down to the plan default lives in
-// ChatInput's effect (src/lib/core/.../input/ChatInput.tsx), and the
-// stored-draft > chat-model > default precedence lives in Chat.tsx (block-chat,
-// outside this test runner's projects). Both are exercised here only indirectly
-// via modelsForPlan + the selector's locking. Cover them with a ChatInput-level
-// render test (heavy: editor/markdown/upload mocks) when that harness exists.
-it.todo(
- 'ChatInput reconciles a persisted/chat inaccessible model down to the plan default on mount'
-);
diff --git a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
index ae1114d14c..83e1b435c3 100644
--- a/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
+++ b/apps/web/src/lib/core/component/AI/component/input/ModelSelector.tsx
@@ -1,15 +1,12 @@
-import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
import {
DEFAULT_MODEL,
MODEL_PRETTYNAME,
MODEL_PROVIDER_ICON,
Model,
- modelUsageHint,
PAID_MODELS,
} from '@core/component/AI/constant';
import type { TModel } from '@core/component/AI/types';
-import { enableAiUsageBilling } from '@core/constant/featureFlags';
import { isMobile } from '@core/mobile/isMobile';
import { virtualKeyboardVisible } from '@core/mobile/virtualKeyboard';
import CheckIcon from '@phosphor/check.svg';
@@ -51,7 +48,6 @@ const MODEL_DESCRIPTION: Record<TModel, string> = {
export function ModelSelector(props: ModelSelectorProps) {
const [open, setOpen] = createSignal(false);
- const aiUsageBilling = useFeatureFlag(enableAiUsageBilling);
const model = () => props.selectedModel ?? DEFAULT_MODEL;
const options = () =>
props.models && props.models.length > 0 ? props.models : ALL_AVAILABLE;
@@ -103,21 +99,6 @@ export function ModelSelector(props: ModelSelectorProps) {
<span class="flex-1 truncate">
{MODEL_PRETTYNAME[option.id]}
</span>
- {/* Decorative: the item's accessible name stays the model. */}
- <Show
- when={
- aiUsageBilling().enabled && modelUsageHint(option.id)
- }
- >
- {(hint) => (
- <span
- aria-hidden="true"
- class="shrink-0 text-[10px] text-ink-extra-muted"
- >
- {hint()}
- </span>
- )}
- </Show>
<Show when={!option.available}>
<LockIcon class="size-3.5 shrink-0 text-ink-extra-muted" />
</Show>
@@ -194,22 +175,8 @@ export function ModelSelector(props: ModelSelectorProps) {
class="size-6 shrink-0 text-ink-muted"
/>
<span class="flex min-w-0 flex-1 flex-col gap-1">
- <span class="flex items-baseline gap-2">
- <span class="text-base font-medium leading-5">
- {MODEL_PRETTYNAME[option.id]}
- </span>
- <Show
- when={
- aiUsageBilling().enabled &&
- modelUsageHint(option.id)
- }
- >
- {(hint) => (
- <span class="text-xs text-ink-extra-muted">
- {hint()}
- </span>
- )}
- </Show>
+ <span class="text-base font-medium leading-5">
+ {MODEL_PRETTYNAME[option.id]}
</span>
<span class="text-[13px] leading-[18px] text-ink-muted">
{MODEL_DESCRIPTION[option.id]}
diff --git a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
index 00d5d7f230..4fd792ecd7 100644
--- a/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
+++ b/apps/web/src/lib/core/component/AI/component/input/buildRequest.ts
@@ -1,13 +1,10 @@
import { analytics } from '@app/lib/analytics';
+import { isAiUsageLimitError } from '@app/lib/service-clients/ai-usage-limit';
import { DEFAULT_MODEL } from '@core/component/AI/constant';
import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';
import type { Attachment, Model, ToolSet } from '@core/component/AI/types';
import { isPaymentError } from '@core/util/handlePaymentError';
-
-import {
- AI_USAGE_LIMIT_ERROR,
- cognitionApiServiceClient,
-} from '@service-cognition/client';
+import { cognitionApiServiceClient } from '@service-cognition/client';
import type { ChatMessageStream } from '@service-connection/stream';
import { subscribe } from '@service-connection/stream';
@@ -48,11 +45,9 @@ export function useSendChatMessage() {
});
if (response.isErr()) {
- const usageLimit = response.error.find(
- (e) => e.code === AI_USAGE_LIMIT_ERROR
- );
+ const usageLimit = response.error.find(isAiUsageLimitError);
if (usageLimit) {
- return { error: true, usageLimit: usageLimit.message };
+ return { error: true, usageLimit: usageLimit.reason };
}
}
if (isPaymentError(response)) {
diff --git a/apps/web/src/lib/core/component/AI/constant/model.test.ts b/apps/web/src/lib/core/component/AI/constant/model.test.ts
index 75122a4312..7ed1b504c0 100644
--- a/apps/web/src/lib/core/component/AI/constant/model.test.ts
+++ b/apps/web/src/lib/core/component/AI/constant/model.test.ts
@@ -11,7 +11,6 @@ import {
MODEL_PROVIDER,
Model,
modelsForPlan,
- modelUsageHint,
PAID_MODELS,
type TModel,
} from './model';
@@ -59,17 +58,6 @@ describe('databaseModelForPlan', () => {
});
});
-describe('modelUsageHint', () => {
- it('flags the heavy paid models and stays quiet for the default and cheaper', () => {
- expect(modelUsageHint(Model.gpt6Astra)).toBe('5× usage');
- expect(modelUsageHint(Model.gpt56)).toBe('3× usage');
- expect(modelUsageHint(Model.opus55)).toBe('2.5× usage');
- expect(modelUsageHint(Model.sonnet55)).toBeUndefined();
- expect(modelUsageHint(Model.haiku45)).toBeUndefined();
- expect(modelUsageHint(Model.gpt56Mini)).toBeUndefined();
- });
-});
-
describe('parseModel', () => {
it('passes through known model ids', () => {
for (const id of Object.values(Model)) {
diff --git a/apps/web/src/lib/core/component/AI/constant/model.ts b/apps/web/src/lib/core/component/AI/constant/model.ts
index a07d9388dc..2fc6366c96 100644
--- a/apps/web/src/lib/core/component/AI/constant/model.ts
+++ b/apps/web/src/lib/core/component/AI/constant/model.ts
@@ -52,34 +52,6 @@ export const MODEL_PROVIDER_ICON: ExhaustiveMap = {
'google/gemini-3.8-flash': GoogleIcon,
};
-/**
- * How fast each model draws down a paid plan's included AI, relative to the
- * default model (Sonnet 5.5 = 1). Mirrors the per-token rates in `ai_pricing`
- * (output price, which dominates chat cost): Haiku $5, Sonnet $10, Opus $25,
- * GPT-6 Astra $50, GPT-5.6 $30, GPT-5.6 mini $4.50, Gemini 3.8 Flash $3.75
- * per million tokens. Shown in the picker so choosing a heavy model is a
- * deliberate trade.
- */
-export const MODEL_USAGE_MULTIPLIER: { [K in TModel]: number } = {
- 'anthropic/claude-sonnet-5-5': 1,
- 'anthropic/claude-opus-5-5': 2.5,
- 'anthropic/claude-haiku-4-5': 0.5,
- 'openai/gpt-6-astra': 5,
- 'openai/gpt-5.6': 3,
- 'openai/gpt-5.6-mini': 0.45,
- 'google/gemini-3.8-flash': 0.375,
-};
-
-/**
- * The picker's usage hint for a model: "2.5× usage" for models that burn the
- * allowance faster than the default, nothing for the default and cheaper.
- */
-export function modelUsageHint(model: TModel): string | undefined {
- const multiplier = MODEL_USAGE_MULTIPLIER[model];
- if (multiplier <= 1) return undefined;
- return `${Number.isInteger(multiplier) ? multiplier : multiplier.toFixed(1)}× usage`;
-}
-
/** Default model for paid users. */
export const DEFAULT_MODEL: TModel = Model.sonnet55;
@@ -102,9 +74,7 @@ export const DATABASE_MODEL: TModel = Model.gemini38Flash;
* Models a free user may select. Free users only get Haiku
* (`FREE_DEFAULT_MODEL`); every other model is paid-only and shows locked in
* the selector, where selecting one opens the paywall instead of being sent
- * and rejected by the backend. The heavy models (Opus, GPT-6 Astra) are on
- * every paid plan; they just draw the included AI down faster, see
- * `MODEL_USAGE_MULTIPLIER`.
+ * and rejected by the backend.
*/
export const FREE_MODELS: readonly TModel[] = [FREE_DEFAULT_MODEL];
diff --git a/apps/web/src/lib/core/component/AI/state/createChatController.ts b/apps/web/src/lib/core/component/AI/state/createChatController.ts
index b2b3e355cb..0c3859c150 100644
--- a/apps/web/src/lib/core/component/AI/state/createChatController.ts
+++ b/apps/web/src/lib/core/component/AI/state/createChatController.ts
@@ -1,3 +1,4 @@
+import { isAiDenyCode } from '@app/lib/service-clients/ai-usage-limit';
import type { ChatMessageWithAttachments } from '@core/component/AI/types';
import { asChatMessage } from '@core/component/AI/util/message';
import {
@@ -138,32 +139,47 @@ export function createChatController(
}
function watchStream(newStream: ChatMessageStream) {
+ let processedPartCount = 0;
// Watch stream data for user messages and errors
createEffect(
on(
() => newStream.data(),
(data) => {
- const latest = data.at(-1);
- if (!latest) return;
+ while (processedPartCount < data.length) {
+ const part = data[processedPartCount++];
- match(latest)
- .with({ type: 'error' }, (r) => {
- const streamError =
- 'stream_error' in r ? r.stream_error : undefined;
- dispatch({
- type: 'stream_error',
- streamError: streamError as string | undefined,
- });
- })
- .with({ type: 'chat_user_message' }, (r) => {
- dispatch({
- type: 'stream_user_message',
- messageId: r.message_id,
- content: r.content,
- attachments: r.attachments,
- });
- })
- .otherwise(() => {});
+ match(part)
+ .with({ type: 'error' }, (r) => {
+ const streamError =
+ 'stream_error' in r ? r.stream_error : undefined;
+ dispatch({
+ type: 'stream_error',
+ streamError: streamError as string | undefined,
+ });
+ })
+ .with({ type: 'chat_user_message' }, (r) => {
+ dispatch({
+ type: 'stream_user_message',
+ messageId: r.message_id,
+ content: r.content,
+ attachments: r.attachments,
+ });
+ })
+ .with(
+ {
+ type: 'chat_message_response',
+ content: { type: 'toolCallErr' },
+ },
+ ({ content }) => {
+ // Tool refusals can arrive inside an otherwise successful
+ // stream. The backend prefixes their description with its
+ // stable admission code.
+ const code = content.description.split(':', 1)[0];
+ if (isAiDenyCode(code)) options?.onShowUsageLimit?.(code);
+ }
+ )
+ .otherwise(() => {});
+ }
}
)
);
diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
index 1083fff7e8..93d0cdabe6 100644
--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/decorator/MagicChip/create-magic-chip-model.ts
@@ -10,6 +10,7 @@ import {
} from '@app/features/block-agent/component/parts/shared';
import type { InteractionController } from '@app/features/block-agent/context/interaction';
import { createInteractionController } from '@app/features/block-agent/primitives/create-interaction-controller';
+import { issueSessionAction } from '@app/features/block-agent/queries/issue-session-action';
import { describeToolCall } from '@app/features/block-agent/state/tool-approval-wording';
import { AgentSession } from '@core/agent-session/AgentSession';
import { toast } from '@core/component/Toast/Toast';
@@ -181,7 +182,7 @@ export function createMagicChipModel(props: MagicChipData): {
sessionId: () => props.agentSessionId,
pending: pendingForTurn,
canEdit,
- issue: (action) => live.issue(action),
+ issue: (action) => issueSessionAction(live, action),
onFailure: toast.failure,
});
const asking = (): MagicChipInteraction | undefined => {
diff --git a/apps/web/src/lib/core/constant/AiUsageLimitState.tsx b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
index 472a51a6e9..f98fc14d16 100644
--- a/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
+++ b/apps/web/src/lib/core/constant/AiUsageLimitState.tsx
@@ -1,9 +1,10 @@
+import { isAiDenyCode } from '@app/lib/service-clients/ai-usage-limit';
import type { AiDenyCode } from '@service-auth/ai-billing-types';
import { createSignal } from 'solid-js';
/**
* Global open state for the AI usage-limit dialog, mirroring `PaywallState`:
- * the chat surfaces raise it when the backend answers 402 with one of the
+ * AI surfaces raise it when the backend answers 402 with one of the
* billing codes, and the app layout mounts the dialog once.
*/
const [usageLimitOpen, setUsageLimitOpen] = createSignal(false);
@@ -11,17 +12,6 @@ const [usageLimitCode, setUsageLimitCode] = createSignal<AiDenyCode | null>(
null
);
-const KNOWN_CODES: readonly AiDenyCode[] = [
- 'ai_allowance_exhausted',
- 'ai_free_allowance_exhausted',
- 'ai_overage_limit_reached',
- 'ai_overage_payment_failed',
-];
-
-export function isAiDenyCode(code: string | undefined): code is AiDenyCode {
- return !!code && (KNOWN_CODES as readonly string[]).includes(code);
-}
-
export const useAiUsageLimitState = () => {
const showUsageLimit = (code?: string) => {
setUsageLimitCode(isAiDenyCode(code) ? code : 'ai_allowance_exhausted');
diff --git a/apps/web/src/lib/core/constant/SettingsState.tsx b/apps/web/src/lib/core/constant/SettingsState.tsx
index 6e5aee3bf2..0dbd211bfd 100644
--- a/apps/web/src/lib/core/constant/SettingsState.tsx
+++ b/apps/web/src/lib/core/constant/SettingsState.tsx
@@ -17,6 +17,7 @@ export type SettingsTab =
| 'Account'
| 'API Keys'
| 'Notifications'
+ | 'Usage'
| 'Billing'
| 'Subscription'
| 'Organization'
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index bf66d3f776..4f23e30852 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -773,9 +773,9 @@ export const enableDictation = defineFlag({
});
/**
- * AI usage billing UI: the Billing settings usage meter, credit packs and
- * usage-billing controls, the out-of-credits dialog, the "$N of AI usage"
- * plan copy, and the model picker's usage multipliers. Presentation only:
+ * AI usage billing UI: enables production Usage controls and the usage-limit
+ * dialog, plus the "$N of AI usage" plan copy. Dev and local Usage remain
+ * interactive regardless of this flag. Presentation only:
* backend quota admission and settlement are gated separately by
* `ENABLE_AI_USAGE_ENFORCEMENT` and `ENABLE_AI_USAGE_BILLING`. On in dev;
* production follows PostHog. Override with VITE_ENABLE_AI_USAGE_BILLING.
diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts b/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
index c529bac0c3..4ce74d9504 100644
--- a/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.test.ts
@@ -5,6 +5,17 @@ import {
settingsTabToSlug,
} from './settingsTabsConfig';
+describe('settings Usage tab', () => {
+ it('routes Usage and places it directly before Billing', () => {
+ expect(settingsSlugToTab('usage')).toBe('Usage');
+ expect(settingsTabToSlug('Usage')).toBe('usage');
+ const tabs = SETTINGS_TAB_GROUPS.flatMap((group) =>
+ group.items.map((item) => item.tab)
+ );
+ expect(tabs[tabs.indexOf('Billing') - 1]).toBe('Usage');
+ });
+});
+
describe('settings navigation', () => {
it('gives calendar connections and booking links separate routes', () => {
expect(settingsSlugToTab('calendar')).toBe('Calendar');
diff --git a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
index b2bc3cb85d..0e9a646620 100644
--- a/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
+++ b/apps/web/src/lib/core/constant/settingsTabsConfig.tsx
@@ -7,6 +7,7 @@ import CpuIcon from '@phosphor/cpu.svg';
import CreditCardIcon from '@phosphor/credit-card.svg';
import DeviceMobileIcon from '@phosphor/device-mobile-speaker.svg';
import EmailIcon from '@phosphor/envelope-simple.svg';
+import GaugeIcon from '@phosphor/gauge.svg';
import HardDrivesIcon from '@phosphor/hard-drives.svg';
import KeyIcon from '@phosphor/key.svg';
import KeyboardIcon from '@phosphor/keyboard.svg';
@@ -128,6 +129,12 @@ export const SETTINGS_TAB_GROUPS: SettingsTabGroup[] = [
icon: KeyboardIcon,
keywords: ['keyboard', 'hotkey', 'keybinding'],
},
+ {
+ tab: 'Usage',
+ label: 'Usage',
+ icon: GaugeIcon,
+ keywords: ['ai', 'limit', 'credits', 'reload', 'usage'],
+ },
{
tab: 'Billing',
label: 'Billing',
@@ -216,6 +223,7 @@ const SETTINGS_TAB_SLUGS: Record<SettingsTab, string> = {
Account: 'account',
'API Keys': 'api-keys',
Notifications: 'notifications',
+ Usage: 'usage',
Billing: 'billing',
Subscription: 'subscription',
Organization: 'organization',
@@ -279,6 +287,7 @@ export const useSettingsTabAvailable = () => {
switch (tab) {
case 'Appearance':
case 'Account':
+ case 'Usage':
case 'Billing':
return true;
case 'Email':
diff --git a/apps/web/src/lib/queries/auth/ai-billing.ts b/apps/web/src/lib/queries/auth/ai-billing.ts
index 3cbee62862..2e213d3725 100644
--- a/apps/web/src/lib/queries/auth/ai-billing.ts
+++ b/apps/web/src/lib/queries/auth/ai-billing.ts
@@ -63,7 +63,7 @@ export function useIncludedAiCentsByTier(): () => Partial<
const plans = useAiBillingPlansQuery();
return () =>
Object.fromEntries(
- (plans.data?.plans ?? []).map((plan) => [
+ (plans.isSuccess ? plans.data.plans : []).map((plan) => [
plan.tier,
plan.included_ai_cents_per_seat,
])
diff --git a/apps/web/src/lib/queries/auth/index.ts b/apps/web/src/lib/queries/auth/index.ts
index 5207c3825a..25161accbb 100644
--- a/apps/web/src/lib/queries/auth/index.ts
+++ b/apps/web/src/lib/queries/auth/index.ts
@@ -28,6 +28,7 @@ export { useSendMobileWelcomeEmail } from './mobile-welcome-email';
export {} from './mutations';
export {
type CreateCheckoutSessionArgs,
+ useCreateBillingPortalMutation,
useCreateCheckoutSessionMutation,
} from './stripe-checkout';
export type { UserInfoData } from './user-info';
diff --git a/apps/web/src/lib/queries/auth/stripe-checkout.ts b/apps/web/src/lib/queries/auth/stripe-checkout.ts
index a3694175de..4b8ee1cf4d 100644
--- a/apps/web/src/lib/queries/auth/stripe-checkout.ts
+++ b/apps/web/src/lib/queries/auth/stripe-checkout.ts
@@ -1,3 +1,5 @@
+import { throwOnErr } from '@core/util/result';
+import { authServiceClient } from '@service-auth/client';
import { stripeServiceClient } from '@service-stripe/client';
import { useMutation } from '@tanstack/solid-query';
@@ -22,3 +24,13 @@ export function useCreateCheckoutSessionMutation() {
},
}));
}
+
+/** Open Stripe's hosted payment-method management, returning to the calling settings page. */
+export function useCreateBillingPortalMutation() {
+ return useMutation(() => ({
+ mutationFn: async (args: { returnUrl: string }) =>
+ await throwOnErr(
+ async () => await authServiceClient.createPortalSession(args)
+ ),
+ }));
+}
diff --git a/apps/web/src/lib/service-clients/ai-editing-worker/client.test.ts b/apps/web/src/lib/service-clients/ai-editing-worker/client.test.ts
new file mode 100644
index 0000000000..10d7ce084d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/ai-editing-worker/client.test.ts
@@ -0,0 +1,122 @@
+import { toastAiEditResult } from '@app/features/block-md/queries/ai-edit';
+import { useAiUsageLimitState } from '@core/constant/AiUsageLimitState';
+import { afterEach, beforeEach, expect, test, vi } from 'vitest';
+import { hasActiveAiEdit, requestAiEdit } from './client';
+
+const { failure, permissionToken, span } = vi.hoisted(() => ({
+ failure: vi.fn(),
+ permissionToken: vi.fn(),
+ span: {
+ setAttr: vi.fn(),
+ injectTraceHeaders: vi.fn(),
+ error: vi.fn(),
+ end: vi.fn(),
+ },
+}));
+
+vi.mock('@core/component/Toast/Toast', () => ({ toast: { failure } }));
+vi.mock('@block-md/observability', () => ({
+ resumeDocumentSpan: () => undefined,
+}));
+vi.mock('@service-storage/client', () => ({
+ getDocumentPermissionToken: permissionToken,
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { clientSpan: () => span },
+}));
+
+const state = useAiUsageLimitState();
+const fetch = vi.fn<typeof window.fetch>();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ state.hideUsageLimit();
+ permissionToken.mockResolvedValue('test-document-permission');
+ vi.stubGlobal('fetch', fetch);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ state.hideUsageLimit();
+ vi.unstubAllGlobals();
+ vi.restoreAllMocks();
+});
+
+test.each([
+ 'ai_allowance_exhausted',
+ 'ai_free_allowance_exhausted',
+ 'ai_overage_limit_reached',
+ 'ai_overage_payment_failed',
+])(
+ 'opens the usage dialog for a rejected edit (%s) without applying ops or showing a generic toast',
+ async (code) => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code, error: 'Usage blocked' }, { status: 402 })
+ );
+ const onOps = vi.fn();
+
+ const result = await requestAiEdit({
+ documentId: 'document',
+ prompt: 'Improve this',
+ onOps,
+ });
+ expect(state.usageLimitOpen()).toBe(false);
+ toastAiEditResult(result);
+
+ expect(result).toEqual({
+ kind: 'usage-limit',
+ error: { code: 'AI_USAGE_LIMIT', reason: code, message: 'Usage blocked' },
+ });
+ expect(state.usageLimitOpen()).toBe(true);
+ expect(state.usageLimitCode()).toBe(code);
+ expect(failure).not.toHaveBeenCalled();
+ expect(onOps).not.toHaveBeenCalled();
+ expect(hasActiveAiEdit('document')).toBe(false);
+ expect(span.end).toHaveBeenCalledOnce();
+ }
+);
+
+test.each([403, 500, 503])(
+ 'keeps non-quota HTTP %i edit failures as generic errors',
+ async (status) => {
+ fetch.mockResolvedValueOnce(
+ Response.json({ code: 'ai_billing_unavailable' }, { status })
+ );
+
+ const result = await requestAiEdit({
+ documentId: 'document',
+ prompt: 'Improve this',
+ });
+ toastAiEditResult(result);
+
+ expect(result).toEqual({ kind: 'failed' });
+ expect(state.usageLimitOpen()).toBe(false);
+ expect(failure).toHaveBeenCalledWith('AI edit failed');
+ expect(hasActiveAiEdit('document')).toBe(false);
+ }
+);
+
+test('keeps successful edits and clarification requests distinct from quota failures', async () => {
+ const onOps = vi.fn();
+ fetch.mockResolvedValueOnce(Response.json({ ops: [] }));
+ expect(
+ await requestAiEdit({
+ documentId: 'document',
+ prompt: 'Improve this',
+ onOps,
+ })
+ ).toEqual({ kind: 'ok' });
+ expect(onOps).toHaveBeenCalledWith([]);
+
+ fetch.mockResolvedValueOnce(
+ Response.json({ ops: [], clarification: 'Which paragraph?' })
+ );
+ const result = await requestAiEdit({
+ documentId: 'document',
+ prompt: 'Improve this',
+ });
+ toastAiEditResult(result);
+
+ expect(failure).toHaveBeenCalledWith('Which paragraph?');
+ expect(state.usageLimitOpen()).toBe(false);
+});
diff --git a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
index 99bffe6ed3..b34525e2b3 100644
--- a/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
+++ b/apps/web/src/lib/service-clients/ai-editing-worker/client.ts
@@ -1,11 +1,14 @@
import type { DocumentOp } from '@ai-ops/editor';
import { resumeDocumentSpan } from '@block-md/observability';
-import { toast } from '@core/component/Toast/Toast';
import { MACRO_AGENT_NAME } from '@core/constant/macroAgent';
import { Telemetry } from '@macro-inc/observability';
import { getDocumentPermissionToken } from '@service-storage/client';
import { createSignal } from 'solid-js';
import { developmentProxyUrl } from '../../core/constant/developmentProxy';
+import {
+ type AiUsageLimitError,
+ readAiUsageLimitError,
+} from '../ai-usage-limit';
// Full-URL override (scheme included) for pointing at a local wrangler dev
// worker, e.g. VITE_AI_EDITING_WORKER_URL=http://localhost:8788 bun run dev
@@ -62,6 +65,7 @@ export type AiEditMode = 'supervised' | 'fast';
export type AiEditResult =
| { kind: 'ok' }
| { kind: 'failed' }
+ | { kind: 'usage-limit'; error: AiUsageLimitError }
| { kind: 'cancelled' }
/** The worker stopped to ask for something only the user can supply. No
* edits were made; `message` says what to add to the request. */
@@ -147,6 +151,11 @@ export async function requestAiEdit(args: {
});
span.setAttr('http.status_code', res.status);
if (!res.ok) {
+ const error = await readAiUsageLimitError(res);
+ if (error) {
+ span.setAttr('edit.blocked', true);
+ return { kind: 'usage-limit', error };
+ }
const body = await res.text().catch(() => '');
console.error('ai edit request failed', res.status, body);
const message = `HTTP ${res.status} for POST /edit`;
@@ -183,21 +192,3 @@ export async function requestAiEdit(args: {
}
}
}
-
-/** Toast for a result that did not apply the edit; a user cancel stays silent. */
-export function toastAiEditResult(result: AiEditResult): void {
- if (result.kind === 'failed') toast.failure('AI edit failed');
- if (result.kind === 'blocked') toast.failure(result.message);
-}
-
-/**
- * `requestAiEdit` wrapper that toasts on failure or a request for more detail
- * (a user cancel stays silent). The caller supplies a `finally` callback for
- * any post-edit cleanup (e.g. clearing a loading signal).
- */
-export function requestAiEditWithToast(
- args: { documentId: string; prompt: string },
- onSettled: () => void
-): void {
- requestAiEdit(args).then(toastAiEditResult).finally(onSettled);
-}
diff --git a/apps/web/src/lib/service-clients/ai-usage-limit.ts b/apps/web/src/lib/service-clients/ai-usage-limit.ts
new file mode 100644
index 0000000000..40f154cea5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/ai-usage-limit.ts
@@ -0,0 +1,71 @@
+import type { ResultError } from '@core/util/result';
+import { statusError } from '@core/util/safeFetch';
+import type { AiDenyCode } from './service-auth/ai-billing-types';
+
+export const AI_USAGE_LIMIT_ERROR = 'AI_USAGE_LIMIT' as const;
+
+export type AiUsageLimitError = ResultError<typeof AI_USAGE_LIMIT_ERROR> & {
+ reason: AiDenyCode;
+};
+
+const KNOWN_CODES: readonly AiDenyCode[] = [
+ 'ai_allowance_exhausted',
+ 'ai_free_allowance_exhausted',
+ 'ai_overage_limit_reached',
+ 'ai_overage_payment_failed',
+];
+
+export function isAiDenyCode(code: unknown): code is AiDenyCode {
+ return (
+ typeof code === 'string' && KNOWN_CODES.some((known) => known === code)
+ );
+}
+
+export function isAiUsageLimitError(
+ error: unknown
+): error is AiUsageLimitError {
+ return (
+ typeof error === 'object' &&
+ error !== null &&
+ 'code' in error &&
+ error.code === AI_USAGE_LIMIT_ERROR &&
+ 'reason' in error &&
+ isAiDenyCode(error.reason) &&
+ 'message' in error &&
+ typeof error.message === 'string'
+ );
+}
+
+/** Only explicit quota refusals are usage limits; other 402s are unrelated. */
+export async function readAiUsageLimitError(
+ response: Response
+): Promise<AiUsageLimitError | undefined> {
+ if (response.status !== 402) return;
+ try {
+ const body: unknown = await response.clone().json();
+ if (
+ typeof body === 'object' &&
+ body !== null &&
+ 'code' in body &&
+ isAiDenyCode(body.code)
+ ) {
+ return {
+ code: AI_USAGE_LIMIT_ERROR,
+ reason: body.code,
+ message:
+ 'error' in body && typeof body.error === 'string'
+ ? body.error
+ : 'AI usage limit reached.',
+ };
+ }
+ } catch {
+ // A malformed or non-JSON payment response is not a quota refusal.
+ }
+}
+
+/** Used only by endpoints that spend AI usage; it has no presentation effects. */
+export async function aiUsageErrorResponseHandler(response: Response) {
+ return (
+ (await readAiUsageLimitError(response)) ?? statusError(response.status)
+ );
+}
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
index 8f95831001..c90759ea9d 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.test.ts
@@ -4,6 +4,7 @@ import { agentHarnessServiceClient } from './client';
vi.mock('@core/constant/servers', () => ({
SERVER_HOSTS: { 'agent-harness': 'https://harness.example.com' },
+ SYNC_SERVICE_HOSTS: { worker: 'https://sync.example.com' },
}));
vi.mock('@core/util/fetchWithToken', () => ({ fetchWithToken: vi.fn() }));
diff --git a/apps/web/src/lib/service-clients/service-agent-harness/client.ts b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
index ac616f1c23..507f733337 100644
--- a/apps/web/src/lib/service-clients/service-agent-harness/client.ts
+++ b/apps/web/src/lib/service-clients/service-agent-harness/client.ts
@@ -1,6 +1,10 @@
import { SERVER_HOSTS } from '@core/constant/servers';
import { fetchWithToken } from '@core/util/fetchWithToken';
import type { ErrorResponseHandler } from '@core/util/safeFetch';
+import {
+ type AI_USAGE_LIMIT_ERROR,
+ readAiUsageLimitError,
+} from '../ai-usage-limit';
import type {
AgentRepositoriesResponse,
AgentRepositoryBranchesResponse,
@@ -46,6 +50,11 @@ const sessionError: ErrorResponseHandler<never> = async (response) => {
};
};
+const sessionAiError: ErrorResponseHandler<
+ typeof AI_USAGE_LIMIT_ERROR
+> = async (response) =>
+ (await readAiUsageLimitError(response)) ?? (await sessionError(response));
+
/** Authenticated client for controlling live agent sessions. */
export const agentHarnessServiceClient = {
preview(sessionIds: string[]) {
@@ -87,15 +96,15 @@ export const agentHarnessServiceClient = {
},
create(request: CreateAgentSessionRequest) {
- return fetchWithToken<CreateAgentSessionResponse>(
- `${agentHarnessHost}/agent-sessions`,
- {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(request),
- errorResponseHandler: sessionError,
- }
- );
+ return fetchWithToken<
+ CreateAgentSessionResponse,
+ typeof AI_USAGE_LIMIT_ERROR
+ >(`${agentHarnessHost}/agent-sessions`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(request),
+ errorResponseHandler: sessionAiError,
+ });
},
/**
@@ -187,13 +196,13 @@ export const agentHarnessServiceClient = {
* out (`sent`) or waits in the session's queue (`queued`).
*/
control(sessionId: string, request: ControlRequest) {
- return fetchWithToken<ControlResponse>(
+ return fetchWithToken<ControlResponse, typeof AI_USAGE_LIMIT_ERROR>(
`${agentHarnessHost}/agent-sessions/${sessionId}/control`,
{
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
- errorResponseHandler: sessionError,
+ errorResponseHandler: sessionAiError,
}
);
},
diff --git a/apps/web/src/lib/service-clients/service-auth/client.test.ts b/apps/web/src/lib/service-clients/service-auth/client.test.ts
index 1e63c21679..5d72a1fb4f 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.test.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.test.ts
@@ -2,8 +2,16 @@
* @vitest-environment jsdom
*/
-import { describe, expect, test } from 'vitest';
-import { getExpiresAt } from './client';
+import type { FetchWithTokenInit } from '@core/util/fetchWithToken';
+import { err, ok } from 'neverthrow';
+import { beforeEach, describe, expect, test, vi } from 'vitest';
+import { authServiceClient, getExpiresAt } from './client';
+
+const { fetchCheckout } = vi.hoisted(() => ({ fetchCheckout: vi.fn() }));
+vi.mock('@core/util/fetchWithToken', () => ({ fetchWithToken: fetchCheckout }));
+vi.mock('./fetch', () => ({ fetchWithAuth: fetchCheckout }));
+
+beforeEach(() => fetchCheckout.mockReset());
function jwt(exp: unknown) {
const payload = btoa(JSON.stringify({ exp }));
@@ -23,3 +31,54 @@ describe('getExpiresAt', () => {
expect(getExpiresAt(jwt(exp))).toBe(0);
});
});
+
+describe('credit checkout', () => {
+ const args = {
+ amountCents: 2_500,
+ successUrl:
+ 'https://localhost:3000/app/settings/usage?aiCreditsSuccess=true',
+ cancelUrl: 'https://localhost:3000/app/settings/usage?aiCreditsCancel=true',
+ };
+
+ test('sends the selected pack and return URLs and resolves to the hosted checkout URL', async () => {
+ fetchCheckout.mockResolvedValueOnce(
+ ok({ url: 'https://checkout.stripe.com/test' })
+ );
+ const result = await authServiceClient.createAiCreditCheckout(args);
+ expect(result._unsafeUnwrap()).toBe('https://checkout.stripe.com/test');
+ expect(fetchCheckout).toHaveBeenCalledWith(
+ expect.stringMatching(/\/ai-billing\/credits\/checkout$/),
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify(args),
+ })
+ );
+ });
+
+ test.each([
+ [402, 'PAID_PLAN_REQUIRED'],
+ [401, 'UNAUTHORIZED'],
+ [403, 'FORBIDDEN'],
+ [500, 'SERVER_ERROR'],
+ ])(
+ 'preserves a %i response as %s for the checkout view',
+ async (status, code) => {
+ fetchCheckout.mockImplementationOnce(
+ async (
+ _input: RequestInfo,
+ init: FetchWithTokenInit<'PAID_PLAN_REQUIRED'>
+ ) => {
+ const error = await init.errorResponseHandler?.(
+ new Response(JSON.stringify({ error: 'a paid plan is required' }), {
+ status,
+ })
+ );
+ if (!error) throw new Error('Expected a checkout error handler');
+ return err([error]);
+ }
+ );
+ const result = await authServiceClient.createAiCreditCheckout(args);
+ expect(result._unsafeUnwrapErr()[0].code).toBe(code);
+ }
+ );
+});
diff --git a/apps/web/src/lib/service-clients/service-auth/client.ts b/apps/web/src/lib/service-clients/service-auth/client.ts
index 5c27f296b8..b05186c2bc 100644
--- a/apps/web/src/lib/service-clients/service-auth/client.ts
+++ b/apps/web/src/lib/service-clients/service-auth/client.ts
@@ -7,6 +7,7 @@ import {
type ErrorResponseHandler,
type SafeFetchInit,
safeFetch,
+ statusError,
} from '@core/util/safeFetch';
import { Telemetry } from '@macro-inc/observability';
@@ -743,7 +744,7 @@ export const authServiceClient = {
cancelUrl: string;
}) {
return (
- await fetchWithAuth<{ url: string }>(
+ await fetchWithAuth<{ url: string }, 'PAID_PLAN_REQUIRED'>(
`${authHost}/ai-billing/credits/checkout`,
{
method: 'POST',
@@ -752,6 +753,15 @@ export const authServiceClient = {
successUrl: args.successUrl,
cancelUrl: args.cancelUrl,
}),
+ errorResponseHandler: async (response) => {
+ if (response.status === 402) {
+ return {
+ code: 'PAID_PLAN_REQUIRED',
+ message: 'A paid plan is required',
+ };
+ }
+ return statusError(response.status);
+ },
}
)
).map((result) => result.url);
diff --git a/apps/web/src/lib/service-clients/service-cognition/client.ts b/apps/web/src/lib/service-clients/service-cognition/client.ts
index 0e9f5ea5dd..c8e2694f34 100644
--- a/apps/web/src/lib/service-clients/service-cognition/client.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/client.ts
@@ -11,6 +11,10 @@ import type { SafeFetchInit } from '@core/util/safeFetch';
import type { DocumentTextPart } from '@service-cognition/generated/schemas/documentTextPart';
import { err, ok, type Result } from 'neverthrow';
import type OpenAI from 'openai';
+import {
+ type AI_USAGE_LIMIT_ERROR,
+ aiUsageErrorResponseHandler,
+} from '../ai-usage-limit';
import type { AddServerRequest } from './generated/schemas/addServerRequest';
import type { CreateChatRequest } from './generated/schemas/createChatRequest';
import type { GetBatchPreviewRequest } from './generated/schemas/getBatchPreviewRequest';
@@ -65,50 +69,6 @@ function dcsFetch<T extends ObjectLike = never>(
}
type Success = { success: boolean };
-/**
- * Error code for a chat send refused by the AI billing gate (HTTP 402). The
- * error's `message` carries the backend's reason code
- * (`ai_allowance_exhausted`, `ai_free_allowance_exhausted`,
- * `ai_overage_limit_reached`, `ai_overage_payment_failed`) so the UI can
- * explain and offer the fix.
- */
-export const AI_USAGE_LIMIT_ERROR = 'AI_USAGE_LIMIT' as const;
-
-async function chatSendErrorHandler(
- response: Response
-): Promise<ResultError<FetchWithTokenErrorCode | typeof AI_USAGE_LIMIT_ERROR>> {
- switch (response.status) {
- case 402: {
- let body: { error?: string; code?: string } | null = null;
- try {
- body = (await response.json()) as { error?: string; code?: string };
- } catch {
- body = null;
- }
- return {
- code: AI_USAGE_LIMIT_ERROR,
- message: body?.code ?? 'ai_allowance_exhausted',
- description: body?.error,
- };
- }
- case 401:
- return { code: 'UNAUTHORIZED', message: 'Unauthorized access' };
- case 403:
- return { code: 'FORBIDDEN', message: 'Forbidden' };
- case 404:
- return { code: 'NOT_FOUND', message: 'Resource not found' };
- case 409:
- return { code: 'CONFLICT', message: 'Resource conflict' };
- case 500:
- return { code: 'SERVER_ERROR', message: 'Internal server error' };
- default:
- return {
- code: 'HTTP_ERROR',
- message: `HTTP error! status: ${response.status}`,
- };
- }
-}
-
type IdMappingResponse = { target_id: string | null };
// Hand-written mirrors of the DCS OpenAPI types for the Pipedream MCP
@@ -389,7 +349,7 @@ export const cognitionApiServiceClient = {
>(`${dcsHost}/stream/chat/message`, {
method: 'POST',
body: JSON.stringify(args),
- errorResponseHandler: chatSendErrorHandler,
+ errorResponseHandler: aiUsageErrorResponseHandler,
})
).map((result) => result);
},
@@ -539,9 +499,13 @@ export const cognitionApiServiceClient = {
async structuredCompletion(args: StructuredCompletionRequest) {
return (
- await dcsFetch<StructuredCompletionResponse>(`/structured-completion`, {
+ await fetchWithToken<
+ StructuredCompletionResponse,
+ typeof AI_USAGE_LIMIT_ERROR
+ >(`${dcsHost}/structured-completion`, {
method: 'POST',
body: JSON.stringify(args),
+ errorResponseHandler: aiUsageErrorResponseHandler,
})
).map((result) => result);
},
diff --git a/apps/web/src/lib/service-clients/service-cognition/import.ts b/apps/web/src/lib/service-clients/service-cognition/import.ts
index 10e71634ee..1066c7220e 100644
--- a/apps/web/src/lib/service-clients/service-cognition/import.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/import.ts
@@ -13,6 +13,10 @@ import {
import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { Result } from 'neverthrow';
+import {
+ type AI_USAGE_LIMIT_ERROR,
+ aiUsageErrorResponseHandler,
+} from '../ai-usage-limit';
const dcsHost: string = SERVER_HOSTS['cognition-service'];
@@ -132,10 +136,14 @@ export const importClient = {
/** Accept staged rows (starts import jobs) and/or discard staged rows. */
async runImport(args: { import_ids: string[]; discard_ids: string[] }) {
- return await importFetch<RunImportOutcome>('/import/run', {
- method: 'POST',
- body: JSON.stringify(args),
- });
+ return await fetchWithToken<RunImportOutcome, typeof AI_USAGE_LIMIT_ERROR>(
+ `${dcsHost}/import/run`,
+ {
+ method: 'POST',
+ body: JSON.stringify(args),
+ errorResponseHandler: aiUsageErrorResponseHandler,
+ }
+ );
},
/** Discover candidates for manual selection. */
@@ -147,9 +155,13 @@ export const importClient = {
/** Restart a failed gather run for one source. */
async retryGather(source: ImportSource) {
- return await importFetch(`/import/runs/${source}/retry`, {
- method: 'POST',
- });
+ return await fetchWithToken<{}, typeof AI_USAGE_LIMIT_ERROR>(
+ `${dcsHost}/import/runs/${source}/retry`,
+ {
+ method: 'POST',
+ errorResponseHandler: aiUsageErrorResponseHandler,
+ }
+ );
},
/** Dismiss one source's import section. */
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
index 4f2674d197..9f80696588 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/client.ts
@@ -6,6 +6,10 @@ import {
import type { ObjectLike, ResultError } from '@core/util/result';
import type { SafeFetchInit } from '@core/util/safeFetch';
import type { Result } from 'neverthrow';
+import {
+ type AI_USAGE_LIMIT_ERROR,
+ aiUsageErrorResponseHandler,
+} from '../ai-usage-limit';
import type {
ActionExecutionRecord,
CreateScheduledAction,
@@ -86,9 +90,9 @@ export const scheduledActionClient = {
},
runNow: async (args: { scheduleId: string }) =>
- scheduledActionFetch<InProgressExecution>(
- `/scheduled-actions/${args.scheduleId}/execute`,
- { method: 'POST' }
+ fetchWithToken<InProgressExecution, typeof AI_USAGE_LIMIT_ERROR>(
+ `${scheduledActionHost}/scheduled-actions/${args.scheduleId}/execute`,
+ { method: 'POST', errorResponseHandler: aiUsageErrorResponseHandler }
),
listHistory: async (args: { scheduleId: string }) =>
diff --git a/docs/AGENT_GUIDE/ai-chat.md b/docs/AGENT_GUIDE/ai-chat.md
index d254a075d3..0ce539d5cd 100644
--- a/docs/AGENT_GUIDE/ai-chat.md
+++ b/docs/AGENT_GUIDE/ai-chat.md
@@ -535,12 +535,15 @@ than treating it as approval or repeatedly sending the prompt.
Automatic chat naming is admitted independently. If naming is denied or validation
is unavailable, the successful chat continues with its existing/default title.
-Usage meters, credit controls, out-of-credit dialogs, and model usage multipliers
-are shown only when the `enable-ai-usage-billing` PostHog flag is on (default on
-in frontend development builds). Normal paid-model access rules
-still apply everywhere. Backend enforcement does not depend on those frontend
-controls, and enabling it does not enable credit collection; that needs
-`ENABLE_AI_USAGE_BILLING`. There is no new upgrade prompt in this rollout.
+Settings → Usage is visible for every plan. In production,
+`enable-ai-usage-billing` activates its controls and the AI usage-limit dialog;
+until then Usage shows the October 8, 2026 announcement and disabled controls.
+Dev and local remain active regardless of the flag.
+Usage displays the current period as a **Monthly limit** percentage; its info
+button explains that AI agent chat and AI document editing count toward the limit.
+Plan allowance copy and comparisons still follow `enable-ai-usage-billing`.
+Model pickers have no usage multipliers. Normal paid-model access rules still
+apply. Backend enforcement and credit collection remain independent policies.
Session creation and spending controls also return 402/503 for admission failures.
Waiting prompts are checked again before execution: exhaustion removes rejected
@@ -568,26 +571,32 @@ for Premium, `AI_USAGE_MAX_INCLUDED_ALLOWANCE_CENTS`, and
used up and no credits or usage billing cover the request, sending a message
answers HTTP 402 and the app opens the **AI usage limit** dialog (title
`You've used this month's included AI`, or the spending-limit / failed-charge
-variants). It shows the same meter and controls as Settings → Billing:
-credit-pack buttons, the `Usage billing` toggle, an `Open billing settings`
-button, and `Upgrade to Max` for Premium payers (on a team this moves only the
-payer's own seat). Team members who are not the payer see a note to ask the
-team owner to add credits or turn on usage billing.
+variants). It shows **Monthly limit**, the message `Add additional credits to
+keep going.`, and an `Open usage settings` button. Credit purchases live in
+Settings → Usage; subscription changes live in Settings → Billing.
The free plan is a hard cap: when its monthly allowance is used up, requests
-answer 402 with code `ai_free_allowance_exhausted` and the dialog (title
-`You've used this month's free AI`) shows the meter against the cap with an
-`Upgrade` button that opens Billing; there are no credit or usage-billing
-controls. The cap resets with the UTC calendar month.
+answer 402 with code `ai_free_allowance_exhausted`. The dialog title is
+`You've used this month's free AI`; it says `Subscribe to a paid plan to keep
+going.` and offers `View plans`, which opens Billing. This upgrade path remains
+available while the usage summary loads or fails. Free users cannot buy credits
+or enable Auto-Reload. The cap resets with the UTC calendar month.
Each team seat has its own allowance; unused allowance never moves between
members. The team owner's prepaid credits and usage-billing cap are shared.
+AI service clients return typed quota errors without opening UI. Foreground
+mutation failures and direct session/edit actions present the shared dialog;
+ordinary HTTP failures and background queries do not. Document AI-edit refusals
+apply no edits and open this dialog instead of the generic `AI edit failed`
+toast. Legacy chat tool errors carrying a recognized quota code also open it.
+
### Quota manual checks
Use an isolated local backend with local billing fixtures, not real hosted
accounts. See [quota rollout and coverage](../AI_QUOTA_ENFORCEMENT.md) for setup
and the full matrix. Record both browser behavior and the Network/protocol result;
-existing UI does not promise a dedicated quota dialog outside development mode.
+recognized foreground quota refusals open the shared dialog when the frontend
+rollout is active (always in dev and local; flag-controlled in production).
1. With the flag absent/false across all hosts, send a legacy chat and a managed
session prompt. Confirm ordinary behavior and new uncounted usage rows.
@@ -604,13 +613,21 @@ existing UI does not promise a dedicated quota dialog outside development mode.
work remains without a retry loop and that Stop still works.
4. Invoke AI editing on an editable document and an independent AI tool with the
exhausted fixture. Confirm failed results and unchanged document content. Check
- manual editing and dictation still work. A successful chat whose optional rename
+ the usage-limit dialog opens, with a subscription CTA for Free or a Usage
+ settings CTA for paid accounts. Check manual editing and dictation still work. A successful chat whose optional rename
is refused keeps its existing/default title rather than failing the chat.
5. Set false consistently and restart/redeploy all local processes. Retry refused
work explicitly and confirm recovery, new uncounted rows, and unchanged counted
history. Do not erase history to simulate rollback or claim that rollback is a
quota reset. Check cancellation in both flag states.
+For frontend-only checks against dev, use Settings → Usage → **Developer tools**
+to open the Free or paid usage-limit dialog directly, then reset the preview. This is
+a display override, not a quota change. To test actual refusal handling without
+hosted AI spending, intercept only the tested AI request in Chrome DevTools and
+return the matching 402 body; restore the response afterward. Backend admission
+and settlement tests still require the isolated backend fixtures above.
+
## Start a doc-scoped chat
Open a doc → side panel `Actions` → `Ask Macro`. Opens an agent session with the
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index e8b4ffdfc9..51b7a3627d 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -4,6 +4,13 @@ The document header has separate Share, Copy Share Link, and Side Panel buttons.
They are borderless with a soft rounded background on hover. Share opens the
sharing dialog; copying a link is a separate action.
+Both **Edit with AI** and selected-text AI edits open the shared usage-limit dialog
+when the backend refuses a request with a usage-limit code. Free users can choose
+**View plans**; paid users can choose **Open usage settings** to add credits. The
+failed edit leaves the document unchanged and clears its running state. Other edit
+failures still show **AI edit failed**. The dialog also opens for usage-limit failures
+from live document-editing tools in chat.
+
Snippet owners manage team sharing under **Share → Team access**. The details
panel has no separate Sharing section. Choose **Edit** to grant the access the
old snippet toggle provided, or **None** to remove team access.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index ced27a3d2c..b4dc8308ec 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -2012,7 +2012,7 @@ uses the shared workspace width.
Left nav (feature and platform gates still apply):
- **Blocks**: Email, Calendar, Agents, CRM.
-- **Personal**: Account, Appearance, Notifications, Keyboard shortcuts, Billing, Mobile App.
+- **Personal**: Account, Appearance, Notifications, Keyboard shortcuts, Usage, Billing, Mobile App.
- **Workspace**: Team, Tags, Integrations (personal Gmail/GitHub accounts).
- **Developer**: Agent connections, Runtimes, MCP server, API Keys, Bots.
@@ -2032,17 +2032,46 @@ retains theme search, editing, copying, and custom theme creation.
Existing settings URLs remain valid; `connections` still opens Integrations,
`agent-connections` opens Agent connections, and `harness` aliases Runtimes.
-`Billing` (current plan card with
-`Manage`; only in dev (`dev.macro.com/app` or a local frontend using the dev
-backend), every plan shows an **AI usage** card with the period meter; paid
-plans add the credit balance, credit-pack buttons `$10`/`$25`/`$50`/`$100` that
-redirect to Stripe Checkout, and a `Usage billing` toggle with per-period limit
-pills, while Free shows only the meter against its monthly cap; these controls
-and usage-billing promotional copy are hidden outside dev; an `Upgrade` section
-for Free users with a Premium card (`Upgrade now`) and a Max card (`Get Max`),
-an `Upgrade to Max` card on Premium (titled `Need more AI?` in dev), and a
-`Switch to Premium` link on Max; on a team a plan change moves only the viewer's
-own seat)
+`Usage` appears directly above Billing, including for Free accounts. In
+production, the `enable-ai-usage-billing` PostHog flag controls activation. While
+it is off or loading, the page shows **AI billing changes take effect on October
+8, 2026.** and all Usage controls are disabled. Turning the flag on activates the
+page and removes the announcement. Dev and local remain interactive even with
+the flag off. The production usage-limit dialog follows the same flag. Its
+**Monthly limit** meter displays a percentage using the backend's current-period
+usage and allowance. The info button explains AI agent chat and AI document
+editing. **Usage Credits** shows the dollar balance and `Add more`, which opens
+**Need more usage?** with `$25` / `$50` / `$100` / `Other`. Supported amounts
+redirect to Stripe Checkout; unsupported custom amounts are disabled. Free
+accounts see `View plans` instead of purchase or reload controls; paid team
+members who are not the payer cannot manage billing.
+Unlimited enterprise plans show `Unlimited` and do not offer credit purchases
+or automatic reload. The development paid-plan preview can still display
+those controls, with purchases disabled.
+
+The **Automatic reload** switch opens **Auto-Reload** without toggling directly.
+It contains Minimum balance (default `$10`), Target balance (default `$100`),
+optional Maximum monthly spend (`No limit`), a payment-method management link,
+and the automatic-charge warning. Balance-triggered reload is not implemented
+by the backend yet, so saving is disabled outside its explicit developer preview.
+Existing postpaid usage billing is shown separately and can be turned off by the
+payer. Local **Developer tools** offer `Preview Free plan` and `Preview paid plan`
+to display either Usage page with sample usage, regardless of the signed-in
+account's tier. `Open Free usage-limit dialog` and `Open paid usage-limit dialog`
+open the corresponding exhausted-usage prompt directly. The previews also work
+before the usage summary loads or when it fails. The paid-plan preview allows
+testing Auto-Reload settings. Purchases and payment management are disabled during any
+preview; `Reset preview` restores server data and closes the usage-limit dialog.
+`Preview production before Oct 8` shows the October 8 announcement and disables
+Usage controls, including usage-limit dialogs. Dev tools remain interactive:
+Free and paid previews can be combined with this state, and `Reset preview`
+restores the normal dev view.
+
+`Billing` shows the current plan and `Manage`, an `Upgrade` section for Free
+users with Premium (`Upgrade now`) and Max (`Get Max`), an `Upgrade to Max` card
+on Premium, and a `Switch to Premium` link on Max. On a team, a plan change moves
+only the viewer's own seat. Plan allowance copy uses the backend catalog and
+still follows the `enable-ai-usage-billing` flag; usage controls live in Usage.
`Team` (members list; on a paid team each row shows the seat's plan,
and admins/owners can move a seat between Premium and Max with the `Seat plan`
diff --git a/docs/AI_QUOTA_ENFORCEMENT.md b/docs/AI_QUOTA_ENFORCEMENT.md
index c1f56e885c..7c9914b682 100644
--- a/docs/AI_QUOTA_ENFORCEMENT.md
+++ b/docs/AI_QUOTA_ENFORCEMENT.md
@@ -109,13 +109,23 @@ settles on summary reads, overage changes, and credit purchases. Enable both
together. Settlement without `ENABLE_AI_USAGE_ENFORCEMENT` finds nothing to
settle, because only counted rows are chargeable.
-The frontend is not tied to this flag. The usage meter, credit packs,
-usage-billing controls, the out-of-credits dialog, the "$N of AI usage" plan
-copy, and model usage multipliers are gated by the frontend's
-`enable-ai-usage-billing` PostHog flag (`enableAiUsageBilling` in
-`apps/web/src/lib/core/constant/featureFlags.ts`). It defaults on in
-development builds and follows PostHog elsewhere, independent of backend
-settlement; `VITE_ENABLE_AI_USAGE_BILLING` overrides it locally.
+The frontend is not tied to this flag. Settings → Usage and the shared usage-limit
+dialog support all plans. Production activation follows the
+`enable-ai-usage-billing` PostHog flag: while off or loading, Usage shows the
+October 8, 2026 announcement with disabled controls and the dialog stays closed.
+Dev and local stay active regardless of the flag. No backend rollout endpoint is
+required. Foreground AI actions recognize the four quota
+codes below; clients return typed errors, and presentation happens in the app's
+mutation subscription or direct session/edit action handlers. Generic HTTP errors
+and background queries do not open dialogs. Free refusals offer a paid plan;
+paid refusals link to Usage settings. The monthly percentage uses
+`GET /ai-billing/summary`; plan allowances use `GET /ai-billing/plans`.
+Plan allowance copy and comparisons follow the `enable-ai-usage-billing` PostHog
+flag (`enableAiUsageBilling` in `apps/web/src/lib/core/constant/featureFlags.ts`),
+which defaults on in development builds and follows PostHog elsewhere;
+`VITE_ENABLE_AI_USAGE_BILLING` overrides it locally. Model usage multipliers have
+been removed. The Auto-Reload UI has no balance-triggered backend yet and cannot
+save outside its explicit display-only developer preview.
## Public failure contracts
diff --git a/rules/ast-grep/ts-feature-components-presentational.yml b/rules/ast-grep/ts-feature-components-presentational.yml
index 1eba8567a8..52dcb53d50 100644
--- a/rules/ast-grep/ts-feature-components-presentational.yml
+++ b/rules/ast-grep/ts-feature-components-presentational.yml
@@ -15,6 +15,7 @@ note: |-
files:
- apps/web/src/features/routines/components/**
- apps/web/src/features/scheduling/components/**
+ - apps/web/src/features/usage/components/**
- apps/web/src/features/crm/components/**
- apps/web/src/features/slack-import/components/**
- apps/web/src/features/channels-view/components/ChannelDetailView*
diff --git a/rules/ast-grep/ts-feature-core-pure.yml b/rules/ast-grep/ts-feature-core-pure.yml
index 492150cc39..13dc0063d2 100644
--- a/rules/ast-grep/ts-feature-core-pure.yml
+++ b/rules/ast-grep/ts-feature-core-pure.yml
@@ -17,6 +17,7 @@ note: |-
files:
- apps/web/src/features/routines/core/**
- apps/web/src/features/scheduling/core/**
+ - apps/web/src/features/usage/core/**
- apps/web/src/features/crm/core/**
- apps/web/src/features/slack-import/core/**
- apps/web/src/features/channel/core/channel-invite*
diff --git a/rules/ast-grep/ts-feature-data-no-ui.yml b/rules/ast-grep/ts-feature-data-no-ui.yml
index 3199c25d74..3df5da4f29 100644
--- a/rules/ast-grep/ts-feature-data-no-ui.yml
+++ b/rules/ast-grep/ts-feature-data-no-ui.yml
@@ -17,6 +17,8 @@ files:
- apps/web/src/features/scheduling/context/**
- apps/web/src/features/scheduling/queries/**
- apps/web/src/features/scheduling/primitives/**
+ - apps/web/src/features/usage/queries/**
+ - apps/web/src/features/usage/primitives/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/slack-import/queries/**
diff --git a/rules/ast-grep/ts-feature-layers-use-context.yml b/rules/ast-grep/ts-feature-layers-use-context.yml
index a7a59b32cd..5bf8df710c 100644
--- a/rules/ast-grep/ts-feature-layers-use-context.yml
+++ b/rules/ast-grep/ts-feature-layers-use-context.yml
@@ -24,6 +24,11 @@ files:
- apps/web/src/features/scheduling/primitives/**
- apps/web/src/features/scheduling/components/**
- apps/web/src/features/scheduling/views/**
+ - apps/web/src/features/usage/queries/**
+ - apps/web/src/features/usage/primitives/**
+ - apps/web/src/features/usage/components/**
+ - apps/web/src/features/usage/views/**
+ - apps/web/src/features/usage/context/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/crm/components/**
diff --git a/rules/ast-grep/tsx-feature-components-presentational.yml b/rules/ast-grep/tsx-feature-components-presentational.yml
index bc002968ff..912026afb1 100644
--- a/rules/ast-grep/tsx-feature-components-presentational.yml
+++ b/rules/ast-grep/tsx-feature-components-presentational.yml
@@ -15,6 +15,7 @@ note: |-
files:
- apps/web/src/features/routines/components/**
- apps/web/src/features/scheduling/components/**
+ - apps/web/src/features/usage/components/**
- apps/web/src/features/crm/components/**
- apps/web/src/features/slack-import/components/**
- apps/web/src/features/channels-view/components/ChannelDetailView*
diff --git a/rules/ast-grep/tsx-feature-core-pure.yml b/rules/ast-grep/tsx-feature-core-pure.yml
index e3313a926a..adc6201e69 100644
--- a/rules/ast-grep/tsx-feature-core-pure.yml
+++ b/rules/ast-grep/tsx-feature-core-pure.yml
@@ -17,6 +17,7 @@ note: |-
files:
- apps/web/src/features/routines/core/**
- apps/web/src/features/scheduling/core/**
+ - apps/web/src/features/usage/core/**
- apps/web/src/features/crm/core/**
- apps/web/src/features/slack-import/core/**
- apps/web/src/features/channel/core/channel-invite*
diff --git a/rules/ast-grep/tsx-feature-data-no-ui.yml b/rules/ast-grep/tsx-feature-data-no-ui.yml
index b340225271..3783c27bc9 100644
--- a/rules/ast-grep/tsx-feature-data-no-ui.yml
+++ b/rules/ast-grep/tsx-feature-data-no-ui.yml
@@ -17,6 +17,8 @@ files:
- apps/web/src/features/scheduling/context/**
- apps/web/src/features/scheduling/queries/**
- apps/web/src/features/scheduling/primitives/**
+ - apps/web/src/features/usage/queries/**
+ - apps/web/src/features/usage/primitives/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/slack-import/queries/**
diff --git a/rules/ast-grep/tsx-feature-layers-use-context.yml b/rules/ast-grep/tsx-feature-layers-use-context.yml
index 3cd4666dc9..a0ee0e1e26 100644
--- a/rules/ast-grep/tsx-feature-layers-use-context.yml
+++ b/rules/ast-grep/tsx-feature-layers-use-context.yml
@@ -24,6 +24,11 @@ files:
- apps/web/src/features/scheduling/primitives/**
- apps/web/src/features/scheduling/components/**
- apps/web/src/features/scheduling/views/**
+ - apps/web/src/features/usage/queries/**
+ - apps/web/src/features/usage/primitives/**
+ - apps/web/src/features/usage/components/**
+ - apps/web/src/features/usage/views/**
+ - apps/web/src/features/usage/context/**
- apps/web/src/features/crm/queries/**
- apps/web/src/features/crm/primitives/**
- apps/web/src/features/crm/components/**