Skip to content

Open source alternative to Semrush and Ahrefs

Check credits before starting an AI visibility check, and show the credits warning when it can't run (EVE-420) (#929)

Carter Smith81b39fe4acc6
diff --git a/src/client/features/ai-visibility/PromptTrackingPage.tsx b/src/client/features/ai-visibility/PromptTrackingPage.tsx
index f6f94063..39feaf86 100644
--- a/src/client/features/ai-visibility/PromptTrackingPage.tsx
+++ b/src/client/features/ai-visibility/PromptTrackingPage.tsx
@@ -41,6 +41,7 @@ import {
import type { ProjectMarket } from "@/client/features/projects/types";
import { DEFAULT_LOCATION_CODE } from "@/shared/keyword-locations";
import { scheduleLabel } from "@/shared/rank-tracking";
+import { InsufficientCreditsError } from "@/client/features/billing/InsufficientCreditsError";
export function PromptTrackingPage({
projectId,
@@ -228,10 +229,14 @@ function PromptTrackingContent({
</div>
</div>
<RunStatusLine run={progress.run} tracker={tracker} />
- {tracker?.lastSkipReason && (
- <p className="text-xs text-warning">
- Most recent scheduling notice: {tracker.lastSkipReason}
- </p>
+ {tracker?.lastSkipReason === "INSUFFICIENT_CREDITS" ? (
+ <InsufficientCreditsError variant="inline" />
+ ) : (
+ tracker?.lastSkipReason && (
+ <p className="text-xs text-warning">
+ Most recent scheduling notice: {tracker.lastSkipReason}
+ </p>
+ )
)}
</div>
<VisibilityTrend projectId={projectId} collecting={busy} />
diff --git a/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts b/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts
index dc556615..c19507d8 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityCollection.test.ts
@@ -333,7 +333,7 @@ describe("AI answer collection", () => {
branded: false,
});
- const plan = await prepareAiRun(runId, customer);
+ const plan = await prepareAiRun(runId);
expect(plan.modelBatches).toMatchObject([
{ engine: "claude", tasks: [{ tag: "answer-claude" }] },
@@ -344,7 +344,7 @@ describe("AI answer collection", () => {
});
it("collects a manual run live, saving answers and failing rejected calls", async () => {
- expect(await prepareAiRun(runId, customer)).toMatchObject({ live: true });
+ expect(await prepareAiRun(runId)).toMatchObject({ live: true });
dataforseo.trackingLiveBatch.mockResolvedValue([
liveAnswer,
{ status: "rejected", reason: new Error("Timed out") },
diff --git a/src/server/features/ai-visibility/services/aiVisibilityCollection.ts b/src/server/features/ai-visibility/services/aiVisibilityCollection.ts
index ecf7dbfb..952502da 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityCollection.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityCollection.ts
@@ -1,5 +1,4 @@
import type { BillingCustomerContext } from "@/server/billing/subscription";
-import { getUsageCreditsRemaining } from "@/server/billing/subscription";
import {
createDataforseoClient,
fetchAiTrackingTaskResult,
@@ -10,7 +9,6 @@ import {
import { DataforseoChargedTaskError } from "@/server/lib/dataforseo/envelope";
import { resolveLatestLlmModelName } from "@/server/lib/dataforseo/llm-models";
import { AppError, asAppError } from "@/server/lib/errors";
-import { isHostedServerAuthMode } from "@/server/lib/runtime-env";
import type { ErrorCode } from "@/shared/error-codes";
import { getIsoCountryCode } from "@/shared/keyword-locations";
import {
@@ -25,7 +23,6 @@ import {
type ParsedAiAnswer,
} from "../providers/dataforseoEvidence";
import { aiBrands } from "./aiVisibilityConfiguration";
-import { aiCostForAnswers } from "./aiVisibilityCost";
import { AI_ANSWER_FAILURES } from "./aiVisibilityErrors";
import { matchAiBrand } from "./aiVisibilityMatching";
import { failAiRun } from "./aiVisibilityRuns";
@@ -80,12 +77,11 @@ function errorMessage(error: unknown) {
* Marks the run running and groups its answers into batches. Manual and
* baseline runs collect live answers so the user sees results sooner.
* Scheduled runs use the cheaper standard queue. Claude and Perplexity have no
- * LLM Scraper, so every run asks their model API (`modelBatches`). Hosted runs
- * first check that credits cover the whole check, like rank checks.
+ * LLM Scraper, so every run asks their model API (`modelBatches`). startRun
+ * checked credits before the run was created.
*/
export async function prepareAiRun(
runId: string,
- customer: BillingCustomerContext,
): Promise<
{ market: AiRunMarket; modelBatches: AiTaskBatch[] } & (
| { live: false; batches: AiTaskBatch[] }
@@ -99,19 +95,6 @@ export async function prepareAiRun(
(row) => row.status === "pending",
);
const live = run.trigger !== "scheduled";
- if (await isHostedServerAuthMode()) {
- const required = aiCostForAnswers(
- pending.map((row) => row.engine),
- true,
- live ? "live" : "queued",
- ).costCredits;
- const credits = await getUsageCreditsRemaining(customer.organizationId);
- if (credits.monthlyRemaining + credits.topupRemaining < required)
- throw new AppError(
- "INSUFFICIENT_CREDITS",
- "Not enough credits for this AI visibility check.",
- );
- }
await repo.updateRun(runId, { status: "running" });
const market = {
locationCode: run.locationCode,
@@ -456,11 +439,8 @@ export async function finalizeAiRun(runId: string) {
}
/** The workflow's failure path: fail the run and say why on the tracker. */
-export async function markAiRunFailed(runId: string, error: unknown) {
- const message =
- error instanceof AppError && error.code === "INSUFFICIENT_CREDITS"
- ? AI_ANSWER_FAILURES.noCredits
- : AI_ANSWER_FAILURES.runFailed;
+export async function markAiRunFailed(runId: string) {
+ const message = AI_ANSWER_FAILURES.runFailed;
await failAiRun(runId, message);
const run = await repo.getRunInternal(runId);
if (run) await repo.updateTracker(run.trackerId, { lastSkipReason: message });
diff --git a/src/server/features/ai-visibility/services/aiVisibilityErrors.ts b/src/server/features/ai-visibility/services/aiVisibilityErrors.ts
index 11bdbc22..dac578b3 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityErrors.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityErrors.ts
@@ -18,7 +18,6 @@ export class AiVisibilityError extends AppError {
export const AI_ANSWER_FAILURES = {
notArrived: "No answer arrived within the collection window.",
runFailed: "The last check could not collect answers.",
- noCredits: "Not enough credits for the last check.",
notStarted: "Collection could not start.",
stoppedBeforeStart: "Collection stopped before it started.",
stopped: "Collection stopped before it finished.",
diff --git a/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts b/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
index 6a24cf35..66ddc8a3 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityRuns.test.ts
@@ -6,11 +6,13 @@ import { runCheck } from "./aiVisibilityRuns";
import { getTracker } from "./aiVisibilityState";
import { configuration, customer } from "./aiVisibilityTestFixtures";
-const { testDb, workflow } = await vi.hoisted(async () => {
+const { testDb, workflow, hosted, credits } = await vi.hoisted(async () => {
const { createAiVisibilityTestDb } = await import("../aiVisibilityTestDb");
return {
testDb: await createAiVisibilityTestDb(),
workflow: { create: vi.fn(), get: vi.fn() },
+ hosted: vi.fn(),
+ credits: vi.fn(),
};
});
vi.mock("cloudflare:workers", () => ({
@@ -20,7 +22,11 @@ vi.mock("@/db", () => ({ db: testDb.db }));
vi.mock("@/db/runBatch", () => ({ runBatch: testDb.runBatch }));
vi.mock("@/server/lib/runtime-env", () => ({
getOptionalEnvValue: async () => "dataforseo-key",
- isHostedServerAuthMode: async () => false,
+ isHostedServerAuthMode: hosted,
+}));
+vi.mock("@/server/billing/subscription", () => ({
+ getOrCreateOrganizationCustomer: async () => ({ id: "organization" }),
+ getUsageCreditsRemaining: credits,
}));
const projectId = "project";
@@ -36,6 +42,8 @@ beforeEach(async () => {
}),
);
workflowStatus("running");
+ hosted.mockResolvedValue(false);
+ credits.mockResolvedValue({ monthlyRemaining: 0, topupRemaining: 0 });
});
describe("AI visibility checks", () => {
@@ -102,4 +110,30 @@ describe("AI visibility checks", () => {
).rejects.toMatchObject({ reason: "COST_LIMIT_EXCEEDED" });
expect(await repo.listRuns(projectId)).toEqual([]);
});
+
+ it("refuses a check the credits cannot cover before it starts, and says why on the tracker", async () => {
+ hosted.mockResolvedValue(true);
+
+ await expect(
+ runCheck({ projectId, maxCostUsd: 1 }, customer),
+ ).rejects.toMatchObject({ code: "INSUFFICIENT_CREDITS" });
+
+ expect(await repo.listRuns(projectId)).toEqual([]);
+ expect(workflow.create).not.toHaveBeenCalled();
+ expect((await repo.getTracker(projectId))?.lastSkipReason).toBe(
+ "INSUFFICIENT_CREDITS",
+ );
+ });
+
+ it("starts a check that top-up credits cover after research overdrew monthly credits", async () => {
+ hosted.mockResolvedValue(true);
+ credits.mockResolvedValue({
+ monthlyRemaining: -1000,
+ topupRemaining: 1000,
+ });
+
+ const run = await runCheck({ projectId, maxCostUsd: 1 }, customer);
+
+ expect(run.status).toBe("queued");
+ });
});
diff --git a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts b/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
index 70bc7687..d555ac5a 100644
--- a/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilityRuns.ts
@@ -10,7 +10,12 @@ import {
getOptionalEnvValue,
isHostedServerAuthMode,
} from "@/server/lib/runtime-env";
-import type { BillingCustomerContext } from "@/server/billing/subscription";
+import {
+ getOrCreateOrganizationCustomer,
+ getUsageCreditsRemaining,
+ type BillingCustomerContext,
+} from "@/server/billing/subscription";
+import { AppError } from "@/server/lib/errors";
import type { AiRun } from "@/shared/ai-visibility";
import type { RunAiCheckInput } from "@/types/schemas/ai-visibility";
import { requireConfiguration } from "./aiVisibilityMutation";
@@ -89,6 +94,32 @@ export async function startRun(
"NO_ACTIVE_PROMPTS",
"Add or unpause prompts before starting a check.",
);
+ // Hosted checks need credits for every answer before they start, like rank
+ // checks. The tracker says why no check ran, whichever path started it.
+ if (await isHostedServerAuthMode()) {
+ const required = aiCostForAnswers(
+ scope.prompts.flatMap(() => scope.engines),
+ true,
+ trigger === "scheduled" ? "queued" : "live",
+ ).costCredits;
+ // getOrCreate: an org's first check can come before its Autumn customer.
+ const { id } = await getOrCreateOrganizationCustomer(billing);
+ const credits = await getUsageCreditsRemaining(id);
+ // Clamp at 0: research setup can overdraw monthly credits, and top-up
+ // credits still pay for the check.
+ const available =
+ Math.max(credits.monthlyRemaining, 0) +
+ Math.max(credits.topupRemaining, 0);
+ if (available < required) {
+ await repo.updateTracker(config.tracker.id, {
+ lastSkipReason: "INSUFFICIENT_CREDITS",
+ });
+ throw new AppError(
+ "INSUFFICIENT_CREDITS",
+ "Not enough credits for this AI visibility check.",
+ );
+ }
+ }
const own = { name: project.name, domain: project.domain };
// Two attempts: once normally, once after failing a stale blocker.
for (let attempt = 0; attempt < 2; attempt++) {
diff --git a/src/server/features/ai-visibility/services/aiVisibilitySchedule.ts b/src/server/features/ai-visibility/services/aiVisibilitySchedule.ts
index 85939f9c..69353045 100644
--- a/src/server/features/ai-visibility/services/aiVisibilitySchedule.ts
+++ b/src/server/features/ai-visibility/services/aiVisibilitySchedule.ts
@@ -1,3 +1,4 @@
+import { AppError } from "@/server/lib/errors";
import { AiVisibilityRepository as repo } from "../repositories/AiVisibilityRepository";
import { AiVisibilityError } from "./aiVisibilityErrors";
import { activeAiPrompts } from "./aiVisibilityConfiguration";
@@ -56,12 +57,14 @@ export async function setSchedule(
try {
run = await startRun(config, "baseline", billing);
} catch (error) {
- // A check already running stands in for the baseline.
- if (
- !(error instanceof AiVisibilityError) ||
- error.reason !== "RUN_IN_PROGRESS"
- )
- throw error;
+ // A check already running stands in for the baseline. Without credits
+ // the schedule still saves, and the tracker says why no check ran.
+ const runInProgress =
+ error instanceof AiVisibilityError &&
+ error.reason === "RUN_IN_PROGRESS";
+ const noCredits =
+ error instanceof AppError && error.code === "INSUFFICIENT_CREDITS";
+ if (!runInProgress && !noCredits) throw error;
}
}
return { state: await getTracker(input), run };
diff --git a/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts b/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
index aa7f2114..5b8d99fc 100644
--- a/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
+++ b/src/server/features/ai-visibility/services/scheduledAiVisibility.test.ts
@@ -4,11 +4,12 @@ import { AiVisibilityRepository as repo } from "../repositories/AiVisibilityRepo
import { runScheduledAiVisibility } from "./scheduledAiVisibility";
import { configuration } from "./aiVisibilityTestFixtures";
-const { testDb, workflow } = await vi.hoisted(async () => {
+const { testDb, workflow, hosted } = await vi.hoisted(async () => {
const { createAiVisibilityTestDb } = await import("../aiVisibilityTestDb");
return {
testDb: await createAiVisibilityTestDb(),
workflow: { create: vi.fn(), get: vi.fn() },
+ hosted: vi.fn(),
};
});
vi.mock("cloudflare:workers", () => ({
@@ -18,7 +19,14 @@ vi.mock("@/db", () => ({ db: testDb.db }));
vi.mock("@/db/runBatch", () => ({ runBatch: testDb.runBatch }));
vi.mock("@/server/lib/runtime-env", () => ({
getOptionalEnvValue: async () => "dataforseo-key",
- isHostedServerAuthMode: async () => false,
+ isHostedServerAuthMode: hosted,
+}));
+vi.mock("@/server/billing/subscription", () => ({
+ getOrCreateOrganizationCustomer: async () => ({ id: "organization" }),
+ getUsageCreditsRemaining: async () => ({
+ monthlyRemaining: 0,
+ topupRemaining: 0,
+ }),
}));
vi.mock("./aiVisibilityRetention", () => ({ pruneAiVisibility: vi.fn() }));
@@ -36,6 +44,7 @@ async function dueTracker(projectId: string, paused: boolean) {
}
beforeEach(async () => {
+ hosted.mockResolvedValue(false);
await testDb.seedProject();
await testDb.db.insert(projects).values({
id: "paused-project",
@@ -56,6 +65,18 @@ it("moves every due tracker on, including one whose check cannot start", async (
expect(skipped?.lastSkipReason).toMatch(/unpause prompts/);
expect((await repo.getTracker("project"))?.nextCheckAt).not.toBe(due);
expect(await repo.listRuns("project")).toMatchObject([
- { trigger: "baseline", status: "queued" },
+ { trigger: "scheduled", status: "queued" },
]);
});
+
+it("records a skipped check for credits on the tracker without starting it", async () => {
+ hosted.mockResolvedValue(true);
+ await dueTracker("project", false);
+
+ await runScheduledAiVisibility();
+
+ expect((await repo.getTracker("project"))?.lastSkipReason).toBe(
+ "INSUFFICIENT_CREDITS",
+ );
+ expect(await repo.listRuns("project")).toEqual([]);
+});
diff --git a/src/server/features/ai-visibility/services/scheduledAiVisibility.ts b/src/server/features/ai-visibility/services/scheduledAiVisibility.ts
index 9ad9e3ed..4d89c62f 100644
--- a/src/server/features/ai-visibility/services/scheduledAiVisibility.ts
+++ b/src/server/features/ai-visibility/services/scheduledAiVisibility.ts
@@ -1,3 +1,4 @@
+import { AppError } from "@/server/lib/errors";
import { pruneAiVisibility } from "./aiVisibilityRetention";
import { AiVisibilityRepository as repo } from "../repositories/AiVisibilityRepository";
import { AiVisibilityError } from "./aiVisibilityErrors";
@@ -50,8 +51,9 @@ export async function runScheduledAiVisibility() {
},
});
if (!claimed) continue;
- const first = !(await repo.getLatestScheduledRun(tracker.projectId));
- await startRun(config, first ? "baseline" : "scheduled", {
+ // Always queued: a baseline collects live only when a user starts it
+ // (onboarding or turning on the schedule) and waits for the answers.
+ await startRun(config, "scheduled", {
organizationId,
userId: "system",
userEmail: "[email protected]",
@@ -60,6 +62,9 @@ export async function runScheduledAiVisibility() {
started++;
answersStarted += answers;
} catch (error) {
+ // startRun records a credits skip on the tracker.
+ if (error instanceof AppError && error.code === "INSUFFICIENT_CREDITS")
+ continue;
if (!(error instanceof AiVisibilityError))
console.error("[ai-visibility] scheduled check failed to start", {
trackerId: tracker.id,
diff --git a/src/server/workflows/AiVisibilityWorkflow.test.ts b/src/server/workflows/AiVisibilityWorkflow.test.ts
index 05b120e7..0260ac45 100644
--- a/src/server/workflows/AiVisibilityWorkflow.test.ts
+++ b/src/server/workflows/AiVisibilityWorkflow.test.ts
@@ -152,12 +152,12 @@ describe("AI visibility workflow", () => {
);
});
- it("fails the run when preparation fails, such as when credits run out", async () => {
- const error = new Error("Not enough credits");
+ it("fails the run when preparation fails", async () => {
+ const error = new Error();
mocks.prepare.mockRejectedValue(error);
await expect(execute()).rejects.toThrow(error);
expect(mocks.post).not.toHaveBeenCalled();
- expect(mocks.markFailed).toHaveBeenCalledExactlyOnceWith("run", error);
+ expect(mocks.markFailed).toHaveBeenCalledExactlyOnceWith("run");
});
it("does not log a rejected poll sleep as a failure, but still marks the run failed", async () => {
@@ -166,6 +166,6 @@ describe("AI visibility workflow", () => {
const consoleError = vi.spyOn(console, "error");
await expect(execute()).rejects.toThrow(error);
expect(consoleError).not.toHaveBeenCalled();
- expect(mocks.markFailed).toHaveBeenCalledExactlyOnceWith("run", error);
+ expect(mocks.markFailed).toHaveBeenCalledExactlyOnceWith("run");
});
});
diff --git a/src/server/workflows/AiVisibilityWorkflow.ts b/src/server/workflows/AiVisibilityWorkflow.ts
index b751ed55..5e7995dc 100644
--- a/src/server/workflows/AiVisibilityWorkflow.ts
+++ b/src/server/workflows/AiVisibilityWorkflow.ts
@@ -79,7 +79,7 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<
const { runId, customer } = payload;
const markFailed = async (error: unknown) => {
await pgStep(step, "mark-failed", SINGLE_ATTEMPT, () =>
- markAiRunFailed(runId, error),
+ markAiRunFailed(runId),
);
throw error;
};
@@ -124,7 +124,7 @@ export class AiVisibilityWorkflow extends WorkflowEntrypoint<
};
try {
plan = await pgStep(step, "prepare", SINGLE_ATTEMPT, () =>
- prepareAiRun(runId, customer),
+ prepareAiRun(runId),
);
// Live runs save each live batch as it returns, so nothing is left
// pending to poll.