Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
fix(volumes): analyse a brand's keywords when its setup finishes, not only after checkout (#765)
Gökhan Geyik9736b2d6aa73
diff --git a/server/src/routes/volumes.js b/server/src/routes/volumes.jsindex 2665eecbe..6914fdee9 100644--- a/server/src/routes/volumes.js+++ b/server/src/routes/volumes.js@@ -234,6 +234,86 @@ router.post('/analyze-batch', requireFeature('prompt_volumes'), async (req, res)}});+/**+ * POST /api/volumes/bootstrap+ * The one automatic run a brand gets, at the end of its setup.+ *+ * Tracking starts the moment setup finishes, so Cloro is already scraping+ * while the user watches. Volumes were only ever started from the Stripe+ * success route, which meant a paying org's first brand got them and every+ * brand added afterwards got nothing until someone found the Analyze button.+ *+ * Deliberately outside the quota: the user did not ask for this run, so+ * spending one of a Starter plan's four analyses on it would take an+ * allowance they never offered. What bounds it instead is `analyzed`. A brand+ * with volumes has already had its free run, so the endpoint declines and the+ * quota-bearing /analyze-batch becomes the only way back in.+ */+router.post('/bootstrap', requireFeature('prompt_volumes'), async (req, res) => {+ try {+ const { brandId, locationCode, languageCode } = req.body;++ if (!brandId) {+ return res.status(400).json({ error: 'brandId is required' });+ }++ await assertBrandAccess(brandId, req.user.id);++ // Claim before reading the counts, not after: the read is awaited, and a+ // check that finishes before the claim leaves a gap two calls can both+ // pass through — which for a free run means paying DataForSEO twice.+ if (!claimVolumeAnalysis(brandId)) {+ return res.status(202).json({ started: 0, running: true });+ }++ let total;+ try {+ const progress = await getVolumeProgress(brandId);+ total = progress.total;+ if (progress.analyzed > 0 || total === 0) {+ releaseVolumeAnalysis(brandId);+ return res.json({ started: 0, running: false });+ }+ } catch (err) {+ releaseVolumeAnalysis(brandId);+ throw err;+ }++ analyzeBrandVolumes(brandId, {+ locationCode,+ languageCode,+ onlyMissing: true,+ onProgress: (progress) => trackVolumeProgress(brandId, progress),+ })+ .then((results) => {+ const successCount = results.filter((r) => !r.error).length;+ logger.info(+ { brandId, analyzed: successCount, of: results.length },+ 'volume bootstrap finished',+ );+ })+ .catch((err) => {+ logger.error({ err, brandId }, 'volume bootstrap failed');+ })+ .finally(() => releaseVolumeAnalysis(brandId));++ return res.status(202).json({ started: total, running: true });+ } catch (error) {+ if (error instanceof PlanLimitError) {+ return res.status(error.statusCode).json({+ success: false,+ error: 'quota_exceeded',+ message: error.message,+ });+ }+ logger.error({ err: error }, 'volume bootstrap error');+ return res.status(error.status || 500).json({+ error: 'Failed to start volume analysis',+ details: error.message,+ });+ }+});+/*** GET /api/volumes/status/:brandId* Progress of a running analysis: { running, total, analyzed, done }.diff --git a/server/src/routes/volumes.test.js b/server/src/routes/volumes.test.jsindex 2f41d65bf..81b12d80d 100644--- a/server/src/routes/volumes.test.js+++ b/server/src/routes/volumes.test.js@@ -278,6 +278,121 @@ describe('POST /analyze-batch', () => {});});+/**+ * The free run a brand gets when its setup finishes.+ *+ * Setup already starts tracking, so Cloro scrapes while the user watches. The+ * DataForSEO half was wired to the Stripe success route alone, which meant a+ * paying org's first brand got volumes and every brand added afterwards sat at+ * zero until someone found the Analyze button.+ *+ * What makes it safe to give away is the refusal below: a brand with volumes+ * has had its run, so this cannot be called in a loop for free analyses.+ */+describe('POST /bootstrap', () => {+ const bootstrap = (body) =>+ fetch(`${baseUrl}/bootstrap`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++ it('starts the run for a freshly created brand', async () => {+ const res = await bootstrap({ brandId: 'b1' });++ expect(res.status).toBe(202);+ expect(await res.json()).toMatchObject({ started: 100, running: true });+ expect(analyzeBrandVolumes).toHaveBeenCalledWith(+ 'b1',+ expect.objectContaining({+ onlyMissing: true,+ }),+ );+ });++ it('costs the plan nothing', async () => {+ await bootstrap({ brandId: 'b1' });+ await new Promise((resolve) => setTimeout(resolve, 10));++ // Neither the check nor the ledger row: the user did not ask for this run,+ // so it must not spend one of a Starter plan's four analyses.+ expect(enforceVolumeQuota).not.toHaveBeenCalled();+ expect(insert).not.toHaveBeenCalled();+ });++ it('declines a brand that already has volumes', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 1 });++ const res = await bootstrap({ brandId: 'b1' });++ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ started: 0, running: false });+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();+ });++ it('leaves the brand free to start again after declining', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 1 });+ await bootstrap({ brandId: 'b1' });++ // A declined call that kept the claim would lock the Analyze button out+ // of the brand for the lifetime of the process.+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 0 });+ expect(await (await post({ brandId: 'b1' })).json()).toMatchObject({ running: true });+ });++ it('declines a brand with no prompts at all', async () => {+ getVolumeProgress.mockResolvedValue({ total: 0, analyzed: 0 });++ expect(await (await bootstrap({ brandId: 'b1' })).json()).toMatchObject({ started: 0 });+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();+ });++ it('starts nothing a second time when both calls arrive together', async () => {+ analyzeBrandVolumes.mockReturnValue(deferred().promise);++ const [a, b] = await Promise.all([bootstrap({ brandId: 'b1' }), bootstrap({ brandId: 'b1' })]);++ // Two setups finishing at once, or a retried server action: the claim has+ // to be taken before the counts are read, or both calls read "analyzed: 0"+ // and DataForSEO is paid twice for the same brand.+ expect(await Promise.all([a.json(), b.json()])).toEqual(+ expect.arrayContaining([{ started: 0, running: true }]),+ );+ expect(analyzeBrandVolumes).toHaveBeenCalledTimes(1);+ });++ it('does not start while the Analyze button is already running', async () => {+ analyzeBrandVolumes.mockReturnValue(deferred().promise);+ await post({ brandId: 'b1' });+ analyzeBrandVolumes.mockClear();++ const res = await bootstrap({ brandId: 'b1' });++ expect(res.status).toBe(202);+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();+ });++ it('requires a brand', async () => {+ expect((await bootstrap({})).status).toBe(400);+ });++ it('refuses a brand the caller cannot reach', async () => {+ const denied = new Error('Forbidden');+ denied.status = 403;+ assertBrandAccess.mockRejectedValue(denied);++ expect((await bootstrap({ brandId: 'someone-elses' })).status).toBe(403);+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();+ });++ it('releases the claim when the progress read fails', async () => {+ getVolumeProgress.mockRejectedValueOnce(new Error('db down'));+ expect((await bootstrap({ brandId: 'b1' })).status).toBe(500);++ expect(await (await bootstrap({ brandId: 'b1' })).json()).toMatchObject({ running: true });+ });+});+describe('GET /status/:brandId', () => {/*** Nothing reaches prompt_volumes until the lookup at the very end, so adiff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsxindex 94c43fa25..98d103ef0 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/new/page.tsx@@ -9,6 +9,7 @@ import { createTopics } from '@/lib/actions/topic';import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';import { addCompetitor } from '@/lib/actions/competitor';import { triggerTrackingCheck } from '@/lib/actions/tracking';+import { bootstrapBrandVolumes } from '@/lib/actions/volumes';import { usePlanContext } from '@/components/providers/plan-provider';import { getFaviconUrl } from '@/lib/favicon';import { useBrandStore } from '@/stores/use-brand-store';@@ -699,6 +700,12 @@ export default function NewBrandPage() {// Non-critical — scheduled tracking will still run}+ // Volumes run alongside the scrape rather than waiting for someone to+ // find the Analyze button. Awaited only until the server has taken the+ // work: the run itself outlives this page, but a server action left+ // in flight would be cancelled by the navigation below.+ await bootstrapBrandVolumes(createdBrand.id);+toast.success('Brand setup complete! Tracking is starting.');router.push('/dashboard/insights');} catch (err) {diff --git a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsxindex e0704f67b..69513fb25 100644--- a/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx+++ b/web/src/app/[locale]/(onboarding)/dashboard/onboarding/page.tsx@@ -7,6 +7,7 @@ import { createBrand } from '@/lib/actions/brand';import { createTopics, getTopics } from '@/lib/actions/topic';import { getPromptCapacity, savePromptSet } from '@/lib/actions/prompt';import { triggerTrackingCheck } from '@/lib/actions/tracking';+import { bootstrapBrandVolumes } from '@/lib/actions/volumes';import { addCompetitor, getCompetitors } from '@/lib/actions/competitor';import { getFaviconUrl } from '@/lib/favicon';import { slugify } from '@/lib/slug';@@ -894,6 +895,11 @@ export default function OnboardingPage() {// Non-critical — tracking will run on schedule}+ // Volumes run alongside the scrape rather than waiting for someone to+ // find the Analyze button. The cloud flow returns above and gets this+ // from the Stripe success route once the plan is confirmed.+ await bootstrapBrandVolumes(createdBrand.id);+toast.success('Setup complete! Your first tracking is starting.');// Full page navigation bypasses Next.js router cache, ensuringdiff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.tsindex 1f568a8a9..a104f153b 100644--- a/web/src/lib/actions/volumes.ts+++ b/web/src/lib/actions/volumes.ts@@ -129,6 +129,46 @@ export async function startPromptVolumeAnalysis(};}+/**+ * Start the free run a brand gets once its setup finishes.+ *+ * Setup already kicks off tracking, so Cloro scrapes while the user watches.+ * This does the other half — keyword volumes and competition from DataForSEO —+ * so the Prompts page has its numbers by the time anyone opens it, without+ * anybody pressing Analyze.+ *+ * Never throws and never reports. The brand exists and its tracking has+ * started; a volume run that could not be reached is not a reason to put an+ * error in front of someone who just finished setting up, and the Analyze+ * button is still there. The server declines a brand that already has volumes,+ * so calling this twice costs nothing.+ */+export async function bootstrapBrandVolumes(brandId: string): Promise<void> {+ try {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return;++ const res = await fetch(`${AEO_SERVER_URL}/api/volumes/bootstrap`, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ },+ body: JSON.stringify({ brandId }),+ signal: AbortSignal.timeout(15_000),+ });++ if (!res.ok) {+ console.error('Volume bootstrap request failed', res.status);+ }+ } catch (err) {+ console.error('Volume bootstrap request failed', err);+ }+}+/*** How far the brand's analysis has got. Returns null when the status cannot be* read, which the caller treats as "stop polling" rather than as a failure of