Skip to content

Open source alternative to Semrush and Ahrefs

Tell out-of-credits users and agents how to get more credits (#788)

Ben Senescuec972cef90f2
diff --git a/src/client/components/QueryState.tsx b/src/client/components/QueryState.tsx
index ed8818f0..03f2dfea 100644
--- a/src/client/components/QueryState.tsx
+++ b/src/client/components/QueryState.tsx
@@ -1,19 +1,17 @@
import type { ReactNode } from "react";
-import { Link } from "@tanstack/react-router";
import type { UseQueryResult } from "@tanstack/react-query";
import {
getErrorCode,
getStandardErrorMessage,
} from "@/client/lib/error-messages";
-import { BILLING_ROUTE } from "@/shared/billing";
import { ErrorState } from "@/client/components/ErrorState";
-import { Button } from "@/client/components/ui/button";
+import { InsufficientCreditsError } from "@/client/features/billing/InsufficientCreditsError";
import { SkeletonCard } from "./SkeletonPresets";
/**
* A load failure with a retry button. The message goes through
- * `getStandardErrorMessage`. Out of credits, a retry can't succeed, so the
- * button goes to Billing instead.
+ * `getStandardErrorMessage`. Out of credits, a retry can't succeed, so it
+ * says how to get more credits instead.
*/
export function QueryError({
error,
@@ -26,7 +24,10 @@ export function QueryError({
}: {
/** Omit to always show `fallback`, for errors the page words itself. */
error?: unknown;
- /** The error behind a `fallback` the page words itself; picks the button. */
+ /**
+ * The error behind a `fallback` the page words itself; picks the button.
+ * Out of credits, the plan's own copy replaces the fallback.
+ */
cause?: unknown;
/** Shown when the error has no message of its own. */
fallback: string;
@@ -35,6 +36,9 @@ export function QueryError({
variant?: "inline" | "card" | "page";
title?: string;
}) {
+ if (getErrorCode(error ?? cause) === "INSUFFICIENT_CREDITS") {
+ return <InsufficientCreditsError variant={variant} title={title} />;
+ }
return (
<ErrorState
variant={variant}
@@ -42,18 +46,6 @@ export function QueryError({
message={getStandardErrorMessage(error, fallback)}
onRetry={onRetry}
isRetrying={isRetrying}
- action={
- getErrorCode(error ?? cause) === "INSUFFICIENT_CREDITS" ? (
- <Button
- variant="outline"
- size="sm"
- nativeButton={false}
- render={<Link to={BILLING_ROUTE} />}
- >
- Go to Billing
- </Button>
- ) : undefined
- }
/>
);
}
diff --git a/src/client/features/backlinks/BacklinksPageContent.tsx b/src/client/features/backlinks/BacklinksPageContent.tsx
index 182626f4..d73346a8 100644
--- a/src/client/features/backlinks/BacklinksPageContent.tsx
+++ b/src/client/features/backlinks/BacklinksPageContent.tsx
@@ -7,10 +7,7 @@ import {
BacklinksScopeAlert,
} from "./BacklinksOverviewPanels";
import { BacklinksResultsCard } from "./BacklinksPageSections";
-import {
- BacklinksErrorState,
- BacklinksLoadingState,
-} from "./BacklinksPageStates";
+import { BacklinksLoadingState } from "./BacklinksPageStates";
import type { BacklinksSearchHistoryItem } from "@/client/hooks/useBacklinksSearchHistory";
import type {
BacklinksSearchState,
@@ -21,6 +18,7 @@ import type { BacklinksDomainExpansion } from "./useBacklinksDomainExpansion";
import type { BacklinksFiltersState } from "./useBacklinksFilters";
import type { BacklinksPageData } from "./useBacklinksPageData";
import { SearchTabStrip } from "@/client/features/search-tabs/SearchTabStrip";
+import { QueryError } from "@/client/components/QueryState";
import { Card } from "@/client/components/ui/card";
import { RecentSearches } from "@/client/components/RecentSearches";
import {
@@ -141,8 +139,12 @@ export function BacklinksBody({
return (
<>
{tabControls}
- <BacklinksErrorState
- errorMessage={data.overviewErrorMessage}
+ <QueryError
+ title="Could not load backlinks"
+ cause={data.overviewQuery.error}
+ fallback={
+ data.overviewErrorMessage ?? "Please try again in a moment."
+ }
onRetry={() => void data.overviewQuery.refetch()}
isRetrying={data.overviewQuery.isFetching}
/>
diff --git a/src/client/features/backlinks/BacklinksPageStates.tsx b/src/client/features/backlinks/BacklinksPageStates.tsx
index c6432113..9b082b52 100644
--- a/src/client/features/backlinks/BacklinksPageStates.tsx
+++ b/src/client/features/backlinks/BacklinksPageStates.tsx
@@ -1,4 +1,3 @@
-import { ErrorState } from "@/client/components/ErrorState";
import { SkeletonTableRows } from "@/client/components/SkeletonPresets";
import { Card } from "@/client/components/ui/card";
import { Skeleton } from "@/client/components/ui/skeleton";
@@ -39,22 +38,3 @@ export function BacklinksLoadingState() {
</Card>
);
}
-
-export function BacklinksErrorState({
- errorMessage,
- onRetry,
- isRetrying,
-}: {
- errorMessage: string | null;
- onRetry: () => void;
- isRetrying: boolean;
-}) {
- return (
- <ErrorState
- title="Could not load backlinks"
- message={errorMessage ?? "Please try again in a moment."}
- onRetry={onRetry}
- isRetrying={isRetrying}
- />
- );
-}
diff --git a/src/client/features/billing/FreePlanBanner.tsx b/src/client/features/billing/FreePlanBanner.tsx
index af755b09..c30101fc 100644
--- a/src/client/features/billing/FreePlanBanner.tsx
+++ b/src/client/features/billing/FreePlanBanner.tsx
@@ -1,16 +1,37 @@
import { Link } from "@tanstack/react-router";
import { AppBanner } from "@/client/layout/AppBanner";
+import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";
import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
+import { useCanManageBilling } from "@/client/features/team/organizationQueries";
import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";
export function FreePlanBanner() {
- const { customerQuery, isFreePlan, isOutOfCredits, isLowCredits } =
- useCreditBalance();
+ const {
+ customerQuery,
+ isFreePlan,
+ isOutOfCredits,
+ isLowCredits,
+ refillDate,
+ } = useCreditBalance();
+ const canManageBilling = useCanManageBilling();
if (customerQuery.isLoading || !customerQuery.data) {
return null;
}
+ // Only the owner can change the plan or buy credits, so a link would lead
+ // everyone else to a page where they can't act.
+ if (!canManageBilling && (isOutOfCredits || isLowCredits)) {
+ return (
+ <AppBanner variant={isOutOfCredits ? "destructive" : "warning"}>
+ {isOutOfCredits
+ ? "Your organization has used its credits."
+ : "Your organization is running low on credits."}{" "}
+ Ask your organization owner to add more.
+ </AppBanner>
+ );
+ }
+
const creditsActionLink = isFreePlan ? (
<Link
to={SUBSCRIBE_ROUTE}
@@ -31,8 +52,18 @@ export function FreePlanBanner() {
if (isOutOfCredits) {
return (
<AppBanner variant="destructive">
- You&rsquo;ve used all your credits. {creditsActionLink} to continue
- using OpenSEO.
+ {isFreePlan ? (
+ <>
+ You&rsquo;ve used your free credits. {creditsActionLink} to get $
+ {BASE_PLAN_OFFER.monthlyCreditsUsd} of credits every month.
+ </>
+ ) : (
+ <>
+ You&rsquo;ve used this month&rsquo;s credits. {creditsActionLink} to
+ keep going
+ {refillDate ? `, or wait for them to refill on ${refillDate}` : ""}.
+ </>
+ )}
</AppBanner>
);
}
diff --git a/src/client/features/billing/InsufficientCreditsError.tsx b/src/client/features/billing/InsufficientCreditsError.tsx
new file mode 100644
index 00000000..7b28367c
--- /dev/null
+++ b/src/client/features/billing/InsufficientCreditsError.tsx
@@ -0,0 +1,68 @@
+import type { ReactElement } from "react";
+import { Link } from "@tanstack/react-router";
+import { ErrorState } from "@/client/components/ErrorState";
+import { Button } from "@/client/components/ui/button";
+import { BASE_PLAN_OFFER } from "@/client/features/billing/plan-offers";
+import { useCreditBalance } from "@/client/features/billing/useCreditBalance";
+import { getStandardErrorMessage } from "@/client/lib/error-messages";
+import { BILLING_ROUTE, SUBSCRIBE_ROUTE } from "@/shared/billing";
+
+/**
+ * An out-of-credits failure that says how to get more: a free plan upgrades,
+ * a paid plan buys credits, and until the customer loads the generic copy
+ * points at Billing. A retry can't fix it, so there is no retry button.
+ *
+ * The member role is left to the banner and the billing page: reading it here
+ * would pull a server function into every page error (and every test that
+ * renders one).
+ */
+export function InsufficientCreditsError({
+ variant,
+ title,
+}: {
+ variant?: "inline" | "card" | "page";
+ title?: string;
+}) {
+ const { customerQuery, isFreePlan, refillDate } = useCreditBalance();
+
+ let message: string;
+ let action: ReactElement;
+ if (!customerQuery.data) {
+ message = getStandardErrorMessage(new Error("INSUFFICIENT_CREDITS"));
+ action = (
+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Go to Billing" />
+ );
+ } else if (isFreePlan) {
+ message = `You don't have enough credits for this. Upgrade to get $${BASE_PLAN_OFFER.monthlyCreditsUsd} of credits every month.`;
+ action = (
+ <CreditsButton
+ link={<Link to={SUBSCRIBE_ROUTE} search={{ upgrade: true }} />}
+ label="Upgrade plan"
+ />
+ );
+ } else {
+ message = refillDate
+ ? `You don't have enough credits for this. Buy more credits to keep going, or wait for your monthly credits to refill on ${refillDate}.`
+ : "You don't have enough credits for this. Buy more credits to keep going.";
+ action = (
+ <CreditsButton link={<Link to={BILLING_ROUTE} />} label="Buy credits" />
+ );
+ }
+
+ return (
+ <ErrorState
+ variant={variant}
+ title={title}
+ message={message}
+ action={action}
+ />
+ );
+}
+
+function CreditsButton({ link, label }: { link: ReactElement; label: string }) {
+ return (
+ <Button variant="outline" size="sm" nativeButton={false} render={link}>
+ {label}
+ </Button>
+ );
+}
diff --git a/src/client/features/billing/useCreditBalance.ts b/src/client/features/billing/useCreditBalance.ts
index c17143b9..e1fc9db9 100644
--- a/src/client/features/billing/useCreditBalance.ts
+++ b/src/client/features/billing/useCreditBalance.ts
@@ -1,6 +1,9 @@
import { useCustomer } from "autumn-js/react";
import { useSession } from "@/lib/auth-client";
-import { getCustomerPlanStatus } from "@/client/features/billing/plan-detection";
+import {
+ getCustomerPaidPlanId,
+ getCustomerPlanStatus,
+} from "@/client/features/billing/plan-detection";
import {
AUTUMN_SEO_DATA_BALANCE_FEATURE_ID,
AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID,
@@ -22,24 +25,39 @@ export function useCreditBalance({
},
});
- const balances = customerQuery.data?.balances;
+ const customer = customerQuery.data;
+ const balances = customer?.balances;
+ const monthlyBalance = balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID];
const monthlyRemaining = autumnSeoDataCreditsToUsd(
- balances?.[AUTUMN_SEO_DATA_BALANCE_FEATURE_ID]?.remaining ?? 0,
+ monthlyBalance?.remaining ?? 0,
);
const topUpRemaining = autumnSeoDataCreditsToUsd(
balances?.[AUTUMN_SEO_DATA_TOPUP_BALANCE_FEATURE_ID]?.remaining ?? 0,
);
const totalRemaining = monthlyRemaining + topUpRemaining;
+ // A paid plan canceled at period end ends then instead of refilling.
+ const paidSubscription = customer?.subscriptions?.find(
+ (subscription) => subscription.planId === getCustomerPaidPlanId(customer),
+ );
const isOutOfCredits = totalRemaining <= 0;
return {
session,
customerQuery,
- isFreePlan: getCustomerPlanStatus(customerQuery.data) === "free",
+ isFreePlan: getCustomerPlanStatus(customer) === "free",
monthlyRemaining,
topUpRemaining,
totalRemaining,
isOutOfCredits,
isLowCredits: !isOutOfCredits && totalRemaining < LOW_CREDITS_THRESHOLD_USD,
+ // When monthly credits refill, e.g. "Oct 12". Null for the free plan's
+ // one-time credits and for a canceled plan, which never refill.
+ refillDate:
+ monthlyBalance?.nextResetAt && !paidSubscription?.canceledAt
+ ? new Date(monthlyBalance.nextResetAt).toLocaleDateString(undefined, {
+ month: "short",
+ day: "numeric",
+ })
+ : null,
};
}
diff --git a/src/client/features/keywords/page/KeywordResearchPage.tsx b/src/client/features/keywords/page/KeywordResearchPage.tsx
index 20e70e54..5839c076 100644
--- a/src/client/features/keywords/page/KeywordResearchPage.tsx
+++ b/src/client/features/keywords/page/KeywordResearchPage.tsx
@@ -1,11 +1,10 @@
-import { Link } from "@tanstack/react-router";
import { useCallback, useMemo } from "react";
import { ErrorState } from "@/client/components/ErrorState";
import { FormDialog } from "@/client/components/FormDialog";
import { BackButton, PageHeader } from "@/client/components/PageHeader";
import { Button } from "@/client/components/ui/button";
+import { InsufficientCreditsError } from "@/client/features/billing/InsufficientCreditsError";
import { getErrorCode } from "@/client/lib/error-messages";
-import { BILLING_ROUTE } from "@/shared/billing";
import { formatLocationLabel } from "@/shared/keyword-locations";
import { useKeywordResearchController } from "@/client/features/keywords/state/useKeywordResearchController";
import type {
@@ -284,25 +283,19 @@ function ResearchErrorCard({
return (
<div className="mx-auto w-full max-w-xl pt-1">
- <ErrorState
- message={message}
- onRetry={
- errorCode === "UNKNOWN_LOCATION" ? undefined : controller.retrySearch
- }
- isRetrying={controller.researchRetrying}
- action={
- errorCode === "INSUFFICIENT_CREDITS" ? (
- <Button
- variant="outline"
- size="sm"
- nativeButton={false}
- render={<Link to={BILLING_ROUTE} />}
- >
- Go to Billing
- </Button>
- ) : undefined
- }
- />
+ {errorCode === "INSUFFICIENT_CREDITS" ? (
+ <InsufficientCreditsError />
+ ) : (
+ <ErrorState
+ message={message}
+ onRetry={
+ errorCode === "UNKNOWN_LOCATION"
+ ? undefined
+ : controller.retrySearch
+ }
+ isRetrying={controller.researchRetrying}
+ />
+ )}
</div>
);
}
diff --git a/src/client/lib/error-messages.ts b/src/client/lib/error-messages.ts
index 7973252a..0caf0f2a 100644
--- a/src/client/lib/error-messages.ts
+++ b/src/client/lib/error-messages.ts
@@ -8,7 +8,7 @@ const STANDARD_MESSAGES: Record<ErrorCode, string> = {
PAYMENT_REQUIRED:
"An active hosted subscription is required before you can use OpenSEO.",
INSUFFICIENT_CREDITS:
- "You've run out of credits. Add more credits or upgrade your plan to continue.",
+ "You don't have enough credits for this. Upgrade your plan or buy more credits to keep going.",
FORBIDDEN: "You do not have access to this resource.",
NOT_FOUND: "The requested resource was not found.",
AUDIT_CAPACITY_REACHED:
diff --git a/src/routes/_app/billing.tsx b/src/routes/_app/billing.tsx
index 3d33ea52..8389b697 100644
--- a/src/routes/_app/billing.tsx
+++ b/src/routes/_app/billing.tsx
@@ -69,6 +69,7 @@ function BillingPage() {
totalRemaining,
isOutOfCredits,
isLowCredits,
+ refillDate,
} = useCreditBalance({
// Expanded so the plan card can show the subscribed plan's name.
expand: ["subscriptions.plan"],
@@ -192,10 +193,13 @@ function BillingPage() {
) : null}
{isOutOfCredits ? (
<p className="mt-2 text-xs text-destructive">
- You&rsquo;ve used all your credits.{" "}
{isFreePlan
- ? "Upgrade your plan to continue."
- : "Buy more credits below to continue."}
+ ? "You’ve used your free credits. Upgrade your plan to continue."
+ : `You’ve used this month’s credits. Buy more below to keep going${
+ refillDate
+ ? `, or wait for them to refill on ${refillDate}`
+ : ""
+ }.`}
</p>
) : isLowCredits ? (
<p className="mt-2 text-xs text-amber-600">
diff --git a/src/server/features/sam/SamChatAgent.ts b/src/server/features/sam/SamChatAgent.ts
index 5baf6380..80ecceaf 100644
--- a/src/server/features/sam/SamChatAgent.ts
+++ b/src/server/features/sam/SamChatAgent.ts
@@ -342,7 +342,7 @@ export class SamChatAgent extends Think {
if (depleted) {
turn.refusal = "credits";
return this.refusalTurn(
- "You're out of credits. Top up to keep using SAM.",
+ "You're out of credits. Upgrade your plan or buy more credits on the Billing page to keep using SAM.",
);
}
this.turnMonthlyRemaining = monthlyRemaining;
diff --git a/src/server/mcp/instrumentation.test.ts b/src/server/mcp/instrumentation.test.ts
index bb40095d..b91817f9 100644
--- a/src/server/mcp/instrumentation.test.ts
+++ b/src/server/mcp/instrumentation.test.ts
@@ -98,6 +98,16 @@ describe("instrumentMcpToolHandler", () => {
expect(mocks.recordExternalMcpToolCall).not.toHaveBeenCalled();
});
+ it("explains an out-of-credits call to the agent instead of the bare code", async () => {
+ const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () => {
+ throw new AppError("INSUFFICIENT_CREDITS");
+ });
+
+ await expect(wrapped({}, toolContext)).rejects.toThrow(
+ "doesn't have enough credits for this request",
+ );
+ });
+
it("captures a usage event and the activation milestone for a successful external call", async () => {
const wrapped = instrumentMcpToolHandler("demo", outputSchema, async () =>
okResult({ items: [{ domain: "example.com" }] }),
diff --git a/src/server/mcp/instrumentation.ts b/src/server/mcp/instrumentation.ts
index 235bf9ab..a9dd9593 100644
--- a/src/server/mcp/instrumentation.ts
+++ b/src/server/mcp/instrumentation.ts
@@ -1,7 +1,7 @@
import { waitUntil } from "cloudflare:workers";
import type { CallToolResult } from "@modelcontextprotocol/server";
import type { z } from "zod";
-import { asAppError } from "@/server/lib/errors";
+import { AppError, asAppError } from "@/server/lib/errors";
import { recordExternalMcpToolCall } from "@/server/features/activation/mcpActivation";
import { captureServerError, captureServerEvent } from "@/server/lib/posthog";
import { shouldCaptureAppErrorCode } from "@/shared/error-codes";
@@ -195,7 +195,21 @@ export function instrumentMcpToolHandler<TArgs>(
),
);
}
- throw error;
+ throw agentFacingError(error, appError);
}
};
}
+
+// The agent sees only the error message, and a bare INSUFFICIENT_CREDITS code
+// gives it nothing to tell the user, so it tends to retry. Explain it instead,
+// without promoting upgrades or purchases (the server instructions forbid
+// that); every other error passes through unchanged.
+function agentFacingError(error: unknown, appError: AppError | null): unknown {
+ if (appError?.code !== "INSUFFICIENT_CREDITS") return error;
+ const detail =
+ appError.message === appError.code ? "" : `${appError.message} `;
+ return new AppError(
+ "INSUFFICIENT_CREDITS",
+ `${detail}This OpenSEO organization doesn't have enough credits for this request. Retrying won't help until the organization has more credits.`,
+ );
+}