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(prompts): let volume analysis cover a whole brand instead of failing past 50 prompts (#747)
Gökhan Geyik3ca52826c401
diff --git a/server/src/lib/volume-analysis.js b/server/src/lib/volume-analysis.jsindex 327ef0b6e..cd88e2b61 100644--- a/server/src/lib/volume-analysis.js+++ b/server/src/lib/volume-analysis.js@@ -83,9 +83,87 @@ export async function fetchAndSaveVolumes(promptId, keywords, intent, locationCoreturn saved;}+/**+ * PostgREST caps an un-paginated select at 1000 rows, and an `.in()` filter+ * travels in the query string rather than the body — a brand near the+ * 1000-prompt ceiling would truncate silently on the first count and overflow+ * the request line on the second (#714, #740, #741). Both reads below page,+ * and scope through the prompt_sets embed so no list of prompt ids is ever+ * assembled.+ */+const PAGE_SIZE = 1000;++/**+ * Ceiling on what one brand can page in. A backend that kept answering full+ * pages would otherwise spin this loop forever, and the caller is a background+ * run with nobody waiting on it to notice. The largest brand allowed today+ * holds 1000 prompts, so this leaves an order of magnitude of headroom.+ */+const MAX_PAGED_ROWS = 50_000;++async function fetchAllPages(buildQuery) {+ const rows = [];+ for (let from = 0; from < MAX_PAGED_ROWS; from += PAGE_SIZE) {+ const { data, error } = await buildQuery().range(from, from + PAGE_SIZE - 1);+ if (error) throw new Error(error.message);+ if (!data?.length) break;+ rows.push(...data);+ if (data.length < PAGE_SIZE) break;+ }+ return rows;+}++async function fetchPromptSetIds(brandId) {+ const { data, error } = await supabaseAdmin+ .from('prompt_sets')+ .select('id')+ .eq('brand_id', brandId);++ if (error) throw new Error(`Failed to fetch prompt sets: ${error.message}`);+ return (data || []).map((ps) => ps.id);+}++/**+ * Inactive prompts are tracked on no platform, so analysing one spends an LLM+ * call, a DataForSEO call and its share of the wait on a row no surface reads.+ */+function activePromptsQuery(setIds) {+ return supabaseAdmin+ .from('prompts')+ .select('id, text')+ .in('prompt_set_id', setIds)+ .eq('is_active', true)+ .order('id', { ascending: true });+}++/**+ * How much of a brand's active prompt set already carries volumes. This is the+ * pair the Prompts page polls while an analysis runs, so it stays two exact+ * counts — no rows travel, and the 1000-row cap cannot reach it.+ */+export async function getVolumeProgress(brandId) {+ const setIds = await fetchPromptSetIds(brandId);+ if (setIds.length === 0) return { total: 0, analyzed: 0 };++ const [{ count: total }, { count: analyzed }] = await Promise.all([+ supabaseAdmin+ .from('prompts')+ .select('*', { count: 'exact', head: true })+ .in('prompt_set_id', setIds)+ .eq('is_active', true),+ supabaseAdmin+ .from('prompt_volumes')+ .select('prompts!inner(prompt_set_id, is_active)', { count: 'exact', head: true })+ .in('prompts.prompt_set_id', setIds)+ .eq('prompts.is_active', true),+ ]);++ return { total: total || 0, analyzed: analyzed || 0 };+}+export async function analyzeBrandVolumes(brandId,- { promptIds, locationCode, languageCode, force = false, onlyMissing = false } = {},+ { locationCode, languageCode, force = false, onlyMissing = false } = {},) {const { data: brand, error: brandError } = await supabaseAdmin.from('brands')@@ -104,62 +182,37 @@ export async function analyzeBrandVolumes(locationCode ?? (brand.region ? regionToLocationCode(brand.region) : undefined);const resolvedLanguageCode =languageCode ?? (brand.language ? languageToCode(brand.language) : undefined);- const { data: promptSets, error: psError } = await supabaseAdmin- .from('prompt_sets')- .select('id')- .eq('brand_id', brandId);-- if (psError) {- throw new Error(`Failed to fetch prompt sets: ${psError.message}`);- }- if (!promptSets || promptSets.length === 0) {+ const setIds = await fetchPromptSetIds(brandId);+ if (setIds.length === 0) {return [];}- const setIds = promptSets.map((ps) => ps.id);- let promptsQuery = supabaseAdmin.from('prompts').select('id, text');-- if (promptIds?.length) {- promptsQuery = promptsQuery.in('id', promptIds);- } else {- promptsQuery = promptsQuery.in('prompt_set_id', setIds);- }-- const { data: prompts, error: pError } = await promptsQuery;-- if (pError) {- throw new Error(`Failed to fetch prompts: ${pError.message}`);- }-- if (!prompts || prompts.length === 0) {+ const prompts = await fetchAllPages(() => activePromptsQuery(setIds));+ if (prompts.length === 0) {return [];}- const analyzedPromptIds = prompts.map((p) => p.id);const existingMap = {};const existingPromptIds = new Set();if (!force || onlyMissing) {- const { data: existingRows, error: existingError } = await supabaseAdmin- .from('prompt_volumes')- .select('prompt_id, intent, keywords')- .in('prompt_id', analyzedPromptIds);-- if (existingError) {- throw new Error(`Failed to fetch existing volumes: ${existingError.message}`);- }+ const existingRows = await fetchAllPages(() =>+ supabaseAdmin+ .from('prompt_volumes')+ .select('prompt_id, intent, keywords, prompts!inner(prompt_set_id)')+ .in('prompts.prompt_set_id', setIds)+ .order('prompt_id', { ascending: true }),+ );- if (existingRows) {- for (const row of existingRows) {- existingPromptIds.add(row.prompt_id);+ for (const row of existingRows) {+ existingPromptIds.add(row.prompt_id);- if (row.keywords?.length) {- existingMap[row.prompt_id] = {- intent: row.intent,- keywords: row.keywords,- };- }+ if (row.keywords?.length) {+ existingMap[row.prompt_id] = {+ intent: row.intent,+ keywords: row.keywords,+ };}}}diff --git a/server/src/lib/volume-analysis.test.js b/server/src/lib/volume-analysis.test.jsnew file mode 100644index 000000000..b7a320cf0--- /dev/null+++ b/server/src/lib/volume-analysis.test.js@@ -0,0 +1,280 @@+import { describe, expect, it, vi, beforeEach } from 'vitest';++/**+ * A minimal stand-in for the supabase query builder.+ *+ * It records every filter each query was built with, which is half the point:+ * the failures this file guards against were never wrong results, they were+ * queries shaped so that PostgREST truncated them or refused to carry them.+ */+const MAX_ROWS = 1000;++function makeSupabase(db) {+ const queries = [];++ function builder(table) {+ const state = { table, filters: [], range: null, count: null, head: false };+ queries.push(state);++ const resolve = () => {+ let rows = (db[table] || []).filter((row) =>+ state.filters.every((f) => matches(table, row, f, db)),+ );+ if (state.count === 'exact') {+ const count = rows.length;+ return { data: state.head ? null : rows, count, error: null };+ }+ // PostgREST answers an un-paginated select with its first MAX_ROWS and+ // no indication that more exist. Reproducing that here is what makes the+ // pagination test mean anything.+ rows = state.range ? rows.slice(state.range[0], state.range[1] + 1) : rows.slice(0, MAX_ROWS);+ return { data: rows, count: null, error: null };+ };++ const api = {+ select(cols, opts = {}) {+ state.cols = cols;+ state.count = opts.count ?? null;+ state.head = opts.head ?? false;+ return api;+ },+ eq(col, val) {+ state.filters.push(['eq', col, val]);+ return api;+ },+ in(col, vals) {+ state.filters.push(['in', col, vals]);+ return api;+ },+ order() {+ return api;+ },+ range(from, to) {+ state.range = [from, to];+ return api;+ },+ maybeSingle() {+ const { data, error } = resolve();+ return Promise.resolve({ data: data[0] ?? null, error });+ },+ single() {+ const { data, error } = resolve();+ return Promise.resolve({ data: data[0] ?? null, error });+ },+ upsert(row) {+ state.upserted = row;+ return {+ select: () => ({+ single: () =>+ Promise.resolve({+ data: { id: `v-${row.prompt_id}`, ...row },+ error: null,+ }),+ }),+ };+ },+ then(onFulfilled, onRejected) {+ return Promise.resolve(resolve()).then(onFulfilled, onRejected);+ },+ };+ return api;+ }++ return { client: { from: builder }, queries };+}++/** Resolves `prompts.is_active`-style embedded columns against the joined row. */+function matches(table, row, [op, col, val], db) {+ let target = row;+ let column = col;++ if (col.includes('.')) {+ const [embed, embedCol] = col.split('.');+ if (table !== 'prompt_volumes' || embed !== 'prompts') {+ throw new Error(`test fake cannot resolve embed ${table}.${col}`);+ }+ target = db.prompts.find((p) => p.id === row.prompt_id) || {};+ column = embedCol;+ }++ return op === 'eq' ? target[column] === val : val.includes(target[column]);+}++function seed({ activeCount = 0, inactiveCount = 0, withVolumes = [] } = {}) {+ const prompts = [];+ for (let i = 0; i < activeCount; i += 1) {+ prompts.push({ id: `p${i}`, text: `prompt ${i}`, prompt_set_id: 's1', is_active: true });+ }+ for (let i = 0; i < inactiveCount; i += 1) {+ prompts.push({ id: `off${i}`, text: `off ${i}`, prompt_set_id: 's1', is_active: false });+ }+ return {+ brands: [{ id: 'b1', region: 'US', language: 'en' }],+ prompt_sets: [{ id: 's1', brand_id: 'b1' }],+ prompts,+ prompt_volumes: withVolumes.map((id) => ({+ prompt_id: id,+ intent: 'saved intent',+ keywords: ['saved keyword'],+ })),+ };+}++const extractIntentKeywords = vi.fn();+const getSearchVolumes = vi.fn();++async function load(db) {+ const { client, queries } = makeSupabase(db);+ vi.resetModules();+ vi.doMock('../config/supabase.js', () => ({ default: client }));+ vi.doMock('./dataforseo.js', () => ({ getSearchVolumes }));+ vi.doMock('./ai-provider.js', () => ({ resolveModel: () => 'model' }));+ vi.doMock('./intent-extraction.js', () => ({+ AI_VOLUME_MULTIPLIER: 0.15,+ extractIntentKeywords,+ }));+ vi.doMock('./logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn() };+ return { default: logger, logger };+ });+ const mod = await import('./volume-analysis.js');+ return { ...mod, queries };+}++beforeEach(() => {+ vi.clearAllMocks();+ extractIntentKeywords.mockResolvedValue({ intent: 'informational', keywords: ['a', 'b'] });+ getSearchVolumes.mockResolvedValue({+ a: { volume: 10, competitionIndex: 50, competition: 'MEDIUM' },+ });+});++/**+ * The Prompts page used to send its prompts inline and the route refused more+ * than 50 of them, so a 100-prompt brand had a button that could not succeed+ * The brand is now the unit of work, and nothing about its size is a+ * reason to refuse it.+ */+describe('analyzeBrandVolumes', () => {+ it('analyzes a brand far past the old 50-prompt refusal', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 100 }));++ const results = await analyzeBrandVolumes('b1', { onlyMissing: true });++ expect(results).toHaveLength(100);+ expect(results.every((r) => !r.error)).toBe(true);+ });++ // PostgREST returns 1000 rows for an un-paginated select and says nothing+ // about the rest, which is how #714 and #740 each lost data silently. A brand+ // is allowed up to 1000 prompts today, so this sits exactly on the edge.+ it('pages past the 1000-row cap instead of truncating', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 1500 }));++ const results = await analyzeBrandVolumes('b1', { onlyMissing: true });++ expect(results).toHaveLength(1500);+ });++ it('leaves inactive prompts alone', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 3, inactiveCount: 4 }));++ const results = await analyzeBrandVolumes('b1', { onlyMissing: true });++ expect(results).toHaveLength(3);+ expect(results.map((r) => r.promptId).sort()).toEqual(['p0', 'p1', 'p2']);+ });++ it('skips prompts that already have volumes when only filling gaps', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 4, withVolumes: ['p0', 'p2'] }));++ const results = await analyzeBrandVolumes('b1', { onlyMissing: true });++ expect(results.map((r) => r.promptId)).toEqual(['p1', 'p3']);+ });++ it('reuses saved keywords rather than paying for the LLM again', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 2, withVolumes: ['p0', 'p1'] }));++ await analyzeBrandVolumes('b1');++ expect(extractIntentKeywords).not.toHaveBeenCalled();+ expect(getSearchVolumes).toHaveBeenCalledWith(['saved keyword'], expect.anything());+ });++ it('re-generates keywords for every active prompt under force', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 3, withVolumes: ['p0'] }));++ const results = await analyzeBrandVolumes('b1', { force: true });++ expect(results).toHaveLength(3);+ expect(extractIntentKeywords).toHaveBeenCalledTimes(3);+ });++ // One prompt's upstream failure is recorded against that prompt; the rest of+ // the brand still gets analyzed.+ it('records a per-prompt failure without dropping the run', async () => {+ const { analyzeBrandVolumes } = await load(seed({ activeCount: 3 }));+ getSearchVolumes.mockRejectedValueOnce(new Error('DataForSEO API error (429)'));++ const results = await analyzeBrandVolumes('b1', { onlyMissing: true });++ expect(results).toHaveLength(3);+ expect(results.filter((r) => r.error)).toHaveLength(1);+ });++ it('returns nothing for a brand with no prompt sets', async () => {+ const db = seed({ activeCount: 2 });+ db.prompt_sets = [];+ const { analyzeBrandVolumes } = await load(db);++ expect(await analyzeBrandVolumes('b1', { onlyMissing: true })).toEqual([]);+ });++ // An `.in()` filter travels in the query string, so a list of prompt ids is a+ // request-line overflow waiting for a big enough brand — the failure #741 was+ // opened for. Scoping through prompt_sets keeps the filter one id wide.+ it('never filters by a list of prompt ids', async () => {+ const { analyzeBrandVolumes, queries } = await load(seed({ activeCount: 1200 }));++ await analyzeBrandVolumes('b1', { onlyMissing: true });++ const idFilters = queries.flatMap((q) =>+ q.filters.filter(([op, col]) => op === 'in' && col === 'prompt_id'),+ );+ expect(idFilters).toEqual([]);+ });+});++/**+ * The pair the Prompts page polls while a run is in flight. It has to agree+ * with what analyzeBrandVolumes actually does, or the progress readout stalls+ * short of the end or claims to pass it.+ */+describe('getVolumeProgress', () => {+ it('counts active prompts and how many of them carry volumes', async () => {+ const { getVolumeProgress } = await load(+ seed({ activeCount: 5, inactiveCount: 3, withVolumes: ['p0', 'p1'] }),+ );++ expect(await getVolumeProgress('b1')).toEqual({ total: 5, analyzed: 2 });+ });++ // A volume row left behind by a prompt that has since been deactivated must+ // not count towards a total that excludes it — otherwise analyzed > total and+ // the page reports progress past the end.+ it('ignores volumes belonging to deactivated prompts', async () => {+ const db = seed({ activeCount: 2, inactiveCount: 1, withVolumes: ['p0', 'off0'] });+ const { getVolumeProgress } = await load(db);++ expect(await getVolumeProgress('b1')).toEqual({ total: 2, analyzed: 1 });+ });++ it('reports zero for a brand with no prompt sets', async () => {+ const db = seed({ activeCount: 3 });+ db.prompt_sets = [];+ const { getVolumeProgress } = await load(db);++ expect(await getVolumeProgress('b1')).toEqual({ total: 0, analyzed: 0 });+ });+});diff --git a/server/src/routes/volumes.js b/server/src/routes/volumes.jsindex 2a69774ea..1b4ed0a4e 100644--- a/server/src/routes/volumes.js+++ b/server/src/routes/volumes.js@@ -10,10 +10,38 @@ import {import supabaseAdmin from '../config/supabase.js';import { assertBrandAccess, assertPromptAccess } from '../lib/access.js';import { extractIntentKeywords } from '../lib/intent-extraction.js';-import { mapVolumeRow, fetchAndSaveVolumes, analyzeBrandVolumes } from '../lib/volume-analysis.js';+import {+ mapVolumeRow,+ fetchAndSaveVolumes,+ analyzeBrandVolumes,+ getVolumeProgress,+} from '../lib/volume-analysis.js';+import logger from '../lib/logger.js';const router = Router();+/**+ * Brands with a volume analysis in flight in this process. The work outlives+ * the request that starts it, so nothing else would stop a double-click from+ * starting a second pass over the same prompts.+ */+const runningBrands = new Set();++/**+ * Claim the brand, or report that someone already holds it. Claiming and+ * testing are one step on purpose: a check followed by an await leaves a gap+ * two clicks can both pass through.+ */+function claimVolumeAnalysis(brandId) {+ if (runningBrands.has(brandId)) return false;+ runningBrands.add(brandId);+ return true;+}++function releaseVolumeAnalysis(brandId) {+ runningBrands.delete(brandId);+}+/*** POST /api/volumes/analyze* First-time analysis: LLM extracts intent + keywords, then fetches volumes.@@ -110,61 +138,80 @@ router.post('/analyze', requireFeature('prompt_volumes'), async (req, res) => {/*** POST /api/volumes/analyze-batch- * Batch analysis. Uses saved keywords when available, calls LLM only for new prompts.- * Pass force=true to re-generate all keywords via LLM.+ * Body: { brandId, force? }+ *+ * Analysing a brand takes far longer than a request should be held open: each+ * prompt costs an LLM call plus a DataForSEO call and they run in order, which+ * measures at a 6.4s median — roughly eleven minutes for a 100-prompt brand.+ * So this starts the work and returns 202 immediately; the client follows+ * GET /status/:brandId. The previous shape took the prompts inline and refused+ * more than 50 of them, which made the Prompts page offer a button that a+ * brand of that size could never complete.+ *+ * force=true re-generates keywords for every active prompt; the default only+ * fills in prompts that have no volumes yet.*/router.post('/analyze-batch', requireFeature('prompt_volumes'), async (req, res) => {try {const { remaining, orgId } = await enforceVolumeQuota(req.user.id);- const { prompts, locationCode, languageCode, force } = req.body;+ const { brandId, locationCode, languageCode, force } = req.body;- if (!Array.isArray(prompts) || prompts.length === 0) {- return res.status(400).json({ error: 'prompts array is required and must not be empty' });- }-- if (prompts.length > 50) {- return res.status(400).json({ error: 'Maximum 50 prompts per batch' });+ if (!brandId) {+ return res.status(400).json({ error: 'brandId is required' });}- const promptIds = prompts.map((p) => p.promptId);-- await assertPromptAccess(promptIds, req.user.id);+ await assertBrandAccess(brandId, req.user.id);- const { data: brandRow, error: brandError } = await supabaseAdmin- .from('prompts')- .select('prompt_sets!inner(brands!inner(id))')- .in('id', promptIds)- .limit(1)- .maybeSingle();+ // A second click while the first run is still going would analyse every+ // prompt twice and bill the quota twice.+ if (!claimVolumeAnalysis(brandId)) {+ return res.status(202).json({ started: 0, running: true, remaining });+ }- if (brandError) {- throw new Error(`Failed to resolve brand: ${brandError.message}`);+ let started;+ try {+ const { total, analyzed } = await getVolumeProgress(brandId);+ started = force ? total : total - analyzed;+ } catch (err) {+ releaseVolumeAnalysis(brandId);+ throw err;}- const brandId = brandRow?.prompt_sets?.brands?.id;- if (!brandId) {- return res.status(400).json({- error: 'Unable to resolve brand from prompts',- });+ if (started <= 0) {+ releaseVolumeAnalysis(brandId);+ return res.json({ started: 0, running: false, remaining });}- const results = await analyzeBrandVolumes(brandId, {- promptIds,+ analyzeBrandVolumes(brandId, {locationCode,languageCode,force,+ onlyMissing: !force,+ })+ .then(async (results) => {+ // Quota counts runs, not prompts, so this stays one row per click+ // however many prompts the run covered.+ const successCount = results.filter((r) => !r.error).length;+ if (successCount > 0 && orgId) {+ await supabaseAdmin.from('volume_usage').insert({+ organization_id: orgId,+ action: 'analyze-batch',+ prompt_count: successCount,+ });+ }+ logger.info({ brandId, analyzed: successCount, of: results.length }, 'volume run finished');+ })+ .catch((err) => {+ logger.error({ err, brandId }, 'batch volume analysis failed');+ })+ .finally(() => releaseVolumeAnalysis(brandId));++ return res.status(202).json({+ started,+ running: true,+ remaining: remaining === -1 ? -1 : remaining - 1,});- const successCount = results.filter((r) => !r.error).length;- if (successCount > 0 && orgId) {- await supabaseAdmin.from('volume_usage').insert({- organization_id: orgId,- action: 'analyze-batch',- prompt_count: successCount,- });- }-- return res.json({ results, remaining: remaining === -1 ? -1 : remaining - 1 });} catch (error) {if (error instanceof PlanLimitError) {return res.status(error.statusCode).json({@@ -173,7 +220,7 @@ router.post('/analyze-batch', requireFeature('prompt_volumes'), async (req, res)message: error.message,});}- req.log.error({ err: error }, 'batch volume analysis error');+ logger.error({ err: error }, 'batch volume analysis error');return res.status(error.status || 500).json({error: 'Failed to analyze prompt volumes',details: error.message,@@ -181,6 +228,36 @@ router.post('/analyze-batch', requireFeature('prompt_volumes'), async (req, res)}});+/**+ * GET /api/volumes/status/:brandId+ * Progress of a running analysis: { running, total, analyzed }.+ *+ * `running` is per-process, so a server restart mid-run reports false while+ * rows are still being written. The client treats that as "stopped" and shows+ * what actually landed, which is the honest reading — the counts come from the+ * table either way.+ */+router.get('/status/:brandId', requireFeature('prompt_volumes'), async (req, res) => {+ try {+ const { brandId } = req.params;+ await assertBrandAccess(brandId, req.user.id);++ const { total, analyzed } = await getVolumeProgress(brandId);++ return res.json({ running: runningBrands.has(brandId), total, analyzed });+ } 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 status error');+ return res.status(error.status || 500).json({ error: 'Failed to read volume status' });+ }+});+/*** POST /api/volumes/refresh* Refreshes Google volumes for all prompts that already have saved keywords.diff --git a/server/src/routes/volumes.test.js b/server/src/routes/volumes.test.jsnew file mode 100644index 000000000..c784f6a9e--- /dev/null+++ b/server/src/routes/volumes.test.js@@ -0,0 +1,303 @@+import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest';+import express from 'express';++/**+ * Route-level tests for volume analysis.+ *+ * The unit tests around analyzeBrandVolumes cover which prompts get analyzed.+ * What only shows up here is the contract the Prompts page depends on: that a+ * brand of any size is accepted, that the answer comes back before the run+ * does, and that a second click cannot start a second pass.+ */++class PlanLimitError extends Error {+ constructor(message, statusCode = 403) {+ super(message);+ this.name = 'PlanLimitError';+ this.statusCode = statusCode;+ }+}++const enforceVolumeQuota = vi.fn();+const assertBrandAccess = vi.fn();+const getVolumeProgress = vi.fn();+const analyzeBrandVolumes = vi.fn();+const insert = vi.fn();++/** Lets a test hold a run open and decide exactly when it ends. */+function deferred() {+ let resolve;+ let reject;+ const promise = new Promise((res, rej) => {+ resolve = res;+ reject = rej;+ });+ return { promise, resolve, reject };+}++let server;+let baseUrl;++async function startApp() {+ vi.resetModules();+ vi.doMock('../lib/plan-guard.js', () => ({+ PlanLimitError,+ enforceVolumeQuota,+ getVolumeQuotaStatus: vi.fn(),+ requireFeature: () => (req, res, next) => next(),+ }));+ vi.doMock('../lib/access.js', () => ({+ assertBrandAccess,+ assertPromptAccess: vi.fn(),+ }));+ vi.doMock('../lib/volume-analysis.js', () => ({+ getVolumeProgress,+ analyzeBrandVolumes,+ mapVolumeRow: (r) => r,+ fetchAndSaveVolumes: vi.fn(),+ }));+ vi.doMock('../config/supabase.js', () => ({ default: { from: () => ({ insert }) } }));+ vi.doMock('../lib/logger.js', () => {+ const logger = { info: vi.fn(), warn: vi.fn(), error: vi.fn(), fatal: vi.fn() };+ return { default: logger, logger };+ });+ vi.doMock('../lib/ai-provider.js', () => ({ resolveModel: vi.fn() }));+ vi.doMock('../lib/dataforseo-codes.js', () => ({+ regionToLocationCode: vi.fn(),+ languageToCode: vi.fn(),+ }));++ const { default: router } = await import('./volumes.js');+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => {+ req.user = { id: 'u1' };+ req.log = { error: vi.fn(), info: vi.fn() };+ next();+ });+ app.use('/api/volumes', router);++ await new Promise((resolve) => {+ server = app.listen(0, resolve);+ });+ baseUrl = `http://127.0.0.1:${server.address().port}/api/volumes`;+}++const post = (body) =>+ fetch(`${baseUrl}/analyze-batch`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });++beforeEach(async () => {+ vi.clearAllMocks();+ enforceVolumeQuota.mockResolvedValue({ remaining: -1, orgId: 'org1' });+ assertBrandAccess.mockResolvedValue(undefined);+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 0 });+ analyzeBrandVolumes.mockResolvedValue([]);+ insert.mockResolvedValue({ error: null });+ await startApp();+});++afterEach(async () => {+ await new Promise((resolve) => server.close(resolve));+});++describe('POST /analyze-batch', () => {+ // The failure this whole change exists for: the route used to refuse more+ // than 50 prompts, so the page's own "Analyze 100 prompts" button returned+ // 400 every time.+ it('accepts a brand with 100 prompts', async () => {+ const res = await post({ brandId: 'b1' });++ expect(res.status).toBe(202);+ expect(await res.json()).toMatchObject({ started: 100, running: true });+ });++ it('answers before the run finishes, not after', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);++ const res = await post({ brandId: 'b1' });++ // The response is already here while the run is still outstanding — an+ // eleven-minute request would be cut long before this point.+ expect(res.status).toBe(202);+ run.resolve([]);+ });++ it('starts only the prompts that have no volumes yet', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 60 });++ expect(await (await post({ brandId: 'b1' })).json()).toMatchObject({ started: 40 });+ expect(analyzeBrandVolumes).toHaveBeenCalledWith(+ 'b1',+ expect.objectContaining({ onlyMissing: true }),+ );+ });++ it('starts every active prompt under force', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 60 });++ expect(await (await post({ brandId: 'b1', force: true })).json()).toMatchObject({+ started: 100,+ });+ expect(analyzeBrandVolumes).toHaveBeenCalledWith(+ 'b1',+ expect.objectContaining({ force: true, onlyMissing: false }),+ );+ });++ it('does nothing when every active prompt already has volumes', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 100 });++ const res = await post({ brandId: 'b1' });++ expect(res.status).toBe(200);+ expect(await res.json()).toMatchObject({ started: 0, running: false });+ expect(analyzeBrandVolumes).not.toHaveBeenCalled();+ });++ // Two clicks would otherwise analyze every prompt twice and bill the quota+ // twice. The claim is taken before the first await for exactly this reason.+ it('refuses to start a second run while one is in flight', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);++ await post({ brandId: 'b1' });+ const second = await post({ brandId: 'b1' });++ expect(second.status).toBe(202);+ expect(await second.json()).toMatchObject({ started: 0, running: true });+ expect(analyzeBrandVolumes).toHaveBeenCalledTimes(1);++ run.resolve([]);+ });++ // Sequential clicks are the easy case. Two arriving together are the real+ // one: reading "not running" and then awaiting the progress count leaves a+ // gap both requests pass through, and the brand gets analyzed twice.+ it('refuses a second run even when both clicks arrive together', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);+ // The progress read is what yields control between the check and the claim.+ getVolumeProgress.mockImplementation(+ () => new Promise((resolve) => setTimeout(() => resolve({ total: 100, analyzed: 0 }), 5)),+ );++ const [a, b] = await Promise.all([post({ brandId: 'b1' }), post({ brandId: 'b1' })]);+ const bodies = [await a.json(), await b.json()];++ expect(analyzeBrandVolumes).toHaveBeenCalledTimes(1);+ expect(bodies.filter((x) => x.started > 0)).toHaveLength(1);++ run.resolve([]);+ });++ it('holds no claim against a different brand', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);++ await post({ brandId: 'b1' });+ await post({ brandId: 'b2' });++ expect(analyzeBrandVolumes).toHaveBeenCalledTimes(2);+ run.resolve([]);+ });++ it('lets the brand start again once the run has ended', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);+ await post({ brandId: 'b1' });++ run.resolve([]);+ await new Promise((resolve) => setTimeout(resolve, 10));++ analyzeBrandVolumes.mockResolvedValue([]);+ const again = await post({ brandId: 'b1' });+ expect(await again.json()).toMatchObject({ started: 100, running: true });+ expect(analyzeBrandVolumes).toHaveBeenCalledTimes(2);+ });++ // A failed run must not leave the brand permanently claimed — the next click+ // would report "already running" forever with nothing running.+ it('releases the claim when the run fails', async () => {+ analyzeBrandVolumes.mockRejectedValueOnce(new Error('upstream down'));+ await post({ brandId: 'b1' });+ await new Promise((resolve) => setTimeout(resolve, 10));++ analyzeBrandVolumes.mockResolvedValue([]);+ expect(await (await post({ brandId: 'b1' })).json()).toMatchObject({ started: 100 });+ });++ it('releases the claim when the progress read fails', async () => {+ getVolumeProgress.mockRejectedValueOnce(new Error('db blip'));+ expect((await post({ brandId: 'b1' })).status).toBe(500);++ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 0 });+ expect(await (await post({ brandId: 'b1' })).json()).toMatchObject({ started: 100 });+ });++ it('requires a brand', async () => {+ expect((await post({})).status).toBe(400);+ });++ // The page distinguishes this from a generic failure so it can offer the+ // upgrade wording; it has to arrive as a code, not as prose.+ it('reports an exhausted quota as quota_exceeded', async () => {+ enforceVolumeQuota.mockRejectedValueOnce(new PlanLimitError('Monthly limit reached (4/4).'));++ const res = await post({ brandId: 'b1' });++ expect(res.status).toBe(403);+ expect((await res.json()).error).toBe('quota_exceeded');+ });++ it('bills the quota once per run, not once per prompt', async () => {+ analyzeBrandVolumes.mockResolvedValue([+ { promptId: 'p1' },+ { promptId: 'p2' },+ { promptId: 'p3' },+ ]);++ await post({ brandId: 'b1' });+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(insert).toHaveBeenCalledTimes(1);+ expect(insert).toHaveBeenCalledWith(expect.objectContaining({ prompt_count: 3 }));+ });++ it('bills nothing when every prompt in the run failed', async () => {+ analyzeBrandVolumes.mockResolvedValue([{ promptId: 'p1', error: 'boom' }]);++ await post({ brandId: 'b1' });+ await new Promise((resolve) => setTimeout(resolve, 10));++ expect(insert).not.toHaveBeenCalled();+ });+});++describe('GET /status/:brandId', () => {+ it('reports progress and whether a run is in flight', async () => {+ const run = deferred();+ analyzeBrandVolumes.mockReturnValue(run.promise);+ await post({ brandId: 'b1' });++ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 32 });+ const res = await fetch(`${baseUrl}/status/b1`);++ expect(await res.json()).toEqual({ running: true, total: 100, analyzed: 32 });+ run.resolve([]);+ });++ it('reports a brand with no run as stopped', async () => {+ getVolumeProgress.mockResolvedValue({ total: 100, analyzed: 100 });++ expect(await (await fetch(`${baseUrl}/status/b1`)).json()).toEqual({+ running: false,+ total: 100,+ analyzed: 100,+ });+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex 35bd5dc3e..053c2997f 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -68,7 +68,13 @@ import {} from 'lucide-react';import { cn } from '@/lib/utils';import { useBrandStore } from '@/stores/use-brand-store';-import { analyzePromptVolumesBatch, refreshVolumes, type VolumeQuota } from '@/lib/actions/volumes';+import {+ startPromptVolumeAnalysis,+ getVolumeAnalysisStatus,+ refreshVolumes,+ type VolumeQuota,+ type VolumeErrorCode,+} from '@/lib/actions/volumes';import {addPromptToBrand,deletePrompt,@@ -899,6 +905,36 @@ function KpiCard({);}+/**+ * A volume run is polled, not awaited — the server keeps going regardless. At+ * the measured 6.4s per prompt a ten-second tick still shows steady movement,+ * without turning a quarter-hour run into hundreds of round-trips.+ */+const VOLUME_POLL_MS = 10_000;++/**+ * Ceiling on how long the page keeps watching. At the measured 6.4s median per+ * prompt a 1000-prompt brand runs well past this; the run itself is unaffected,+ * the page just stops narrating it and shows what has landed.+ */+const VOLUME_WATCH_MS = 30 * 60_000;++/**+ * Wording for the closed set of failure codes. Server text never reaches a+ * customer: it names batch sizes, upstream APIs and Postgres columns, none of+ * which mean anything to the person reading the toast.+ */+function volumeErrorMessage(code: VolumeErrorCode, fallback: string): string {+ switch (code) {+ case 'quota_exceeded':+ return 'Monthly volume analysis limit reached. Upgrade your plan for more.';+ case 'plan_limit':+ return 'Volume analysis is not part of your current plan.';+ default:+ return fallback;+ }+}+function VolumePill({ value }: { value: number }) {return <span className="tabular-nums text-sm font-semibold">~{formatCompactNumber(value)}</span>;}@@ -912,6 +948,13 @@ export default function PromptsPage() {const [visibility, setVisibility] = useState<Record<string, PromptVisibilitySummary>>({});const [loading, setLoading] = useState(true);const [analyzing, setAnalyzing] = useState(false);+ const [analysisProgress, setAnalysisProgress] = useState<{+ analyzed: number;+ total: number;+ } | null>(null);+ // Bumped whenever a run is superseded or the brand changes, so a poll that is+ // still in flight cannot write progress for a brand no longer on screen.+ const analysisGenRef = useRef(0);const [refreshing, setRefreshing] = useState(false);const [quota, setQuota] = useState<VolumeQuota | null>(null);const [addPromptOpen, setAddPromptOpen] = useState(false);@@ -1068,54 +1111,128 @@ export default function PromptsPage() {};}, [loadData]);- const handleAnalyzeNew = async () => {+ // Switching brands (or leaving) ends the watch. The run itself is on the+ // server and carries on; only this page's narration of it stops.+ useEffect(() => {+ return () => {+ analysisGenRef.current += 1;+ setAnalyzing(false);+ setAnalysisProgress(null);+ };+ }, [activeBrandId]);++ /**+ * Start a run, then follow it to the end.+ *+ * The work outlives the request that starts it: every prompt costs an LLM+ * call plus a DataForSEO call and they run in order, which measures at a 6.4s+ * median — about eleven minutes for a 100-prompt brand. Holding the request+ * open for that would be cut by the platform long before the run finished,+ * and the old shape sent the prompts inline and was refused outright past 50+ * of them. So the server answers as soon as the work is queued and+ * this polls its count; each prompt is saved on its own row as it lands, so+ * whatever finished is kept even if this page goes away.+ */+ const runVolumeAnalysis = async (force: boolean) => {if (!activeBrandId) return;- const promptsWithoutVolume = allPrompts.filter(- (p) => p.isActive && !volumes.find((v) => v.promptId === p.id),- );-- const promptsToAnalyze =- promptsWithoutVolume.length > 0 ? promptsWithoutVolume : allPrompts.filter((p) => p.isActive);-- if (promptsToAnalyze.length === 0) {+ if (!allPrompts.some((p) => p.isActive)) {toast.error('No active prompts to analyze. Add prompts to a brand first.');return;}+ const gen = ++analysisGenRef.current;setAnalyzing(true);+ setAnalysisProgress(null);+try {- const result = await analyzePromptVolumesBatch(- promptsToAnalyze.map((p) => ({ promptId: p.id, promptText: p.text })),- );- if (result.remaining !== undefined && quota) {+ const started = await startPromptVolumeAnalysis(activeBrandId, force);++ if (!started.ok) {+ toast.error(+ volumeErrorMessage(+ started.code,+ 'Volume analysis could not be started. Please try again.',+ ),+ );+ return;+ }++ if (!started.running && started.started === 0) {+ toast.success('Every active prompt already has volume data.');+ return;+ }++ if (started.remaining !== undefined && quota) {setQuota({...quota,- remaining: result.remaining,- used: quota.limit === -1 ? 0 : quota.limit - result.remaining,+ remaining: started.remaining,+ used: quota.limit === -1 ? 0 : quota.limit - started.remaining,});}- toast.success(`Analyzed ${promptsToAnalyze.length} prompts`);++ toast.success(+ started.started > 0+ ? `Analyzing ${started.started} prompt${started.started === 1 ? '' : 's'} — this keeps running in the background.`+ : 'Volume analysis is already running for this brand.',+ );++ // Only a status that comes back saying the run has stopped counts as+ // finished. Giving up on the watch — deadline reached, status unreadable+ // — says nothing about the run, and claiming otherwise would send someone+ // off with a half-filled table believing it was complete.+ let finished = false;+ const deadline = Date.now() + VOLUME_WATCH_MS;++ for (;;) {+ await new Promise((resolve) => setTimeout(resolve, VOLUME_POLL_MS));+ if (analysisGenRef.current !== gen) return;++ const status = await getVolumeAnalysisStatus(activeBrandId);+ if (analysisGenRef.current !== gen) return;++ if (!status) break;+ setAnalysisProgress({ analyzed: status.analyzed, total: status.total });+ if (!status.running) {+ finished = true;+ break;+ }+ if (Date.now() > deadline) break;+ }+await loadData();- } catch (err: unknown) {- const message = err instanceof Error ? err.message : 'Volume analysis failed';- if (message.includes('limit reached')) {- toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');- } else {- console.error('Volume analysis failed:', err);- toast.error('Volume analysis failed');+ if (analysisGenRef.current === gen) {+ toast.success(+ finished+ ? 'Volume analysis finished.'+ : 'Still analyzing in the background — reopen this page later for the rest.',+ );}+ } catch (err) {+ console.error('Volume analysis failed:', err);+ toast.error('Volume analysis could not be started. Please try again.');} finally {- setAnalyzing(false);+ if (analysisGenRef.current === gen) {+ setAnalyzing(false);+ setAnalysisProgress(null);+ }}};+ const handleAnalyzeNew = () => runVolumeAnalysis(false);+const handleRefreshVolumes = async () => {if (!activeBrandId || volumes.length === 0) return;setRefreshing(true);try {const result = await refreshVolumes(activeBrandId);+ if (!result.ok) {+ toast.error(+ volumeErrorMessage(result.code, 'Volumes could not be refreshed. Please try again.'),+ );+ return;+ }if (result.remaining !== undefined && quota) {setQuota({...quota,@@ -1126,56 +1243,14 @@ export default function PromptsPage() {toast.success(`Refreshed volumes for ${result.refreshed} prompts`);await loadData();} catch (err: unknown) {- const message = err instanceof Error ? err.message : 'Volume refresh failed';- if (message.includes('limit reached')) {- toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');- } else {- console.error('Volume refresh failed:', err);- toast.error('Volume refresh failed');- }+ console.error('Volume refresh failed:', err);+ toast.error('Volumes could not be refreshed. Please try again.');} finally {setRefreshing(false);}};- const handleReanalyzeAll = async () => {- if (!activeBrandId) return;-- const activePrompts = allPrompts.filter((p) => p.isActive);- if (activePrompts.length === 0) {- toast.error('No active prompts to analyze.');- return;- }-- setAnalyzing(true);- try {- const result = await analyzePromptVolumesBatch(- activePrompts.map((p) => ({ promptId: p.id, promptText: p.text })),- undefined,- undefined,- true,- );- if (result.remaining !== undefined && quota) {- setQuota({- ...quota,- remaining: result.remaining,- used: quota.limit === -1 ? 0 : quota.limit - result.remaining,- });- }- toast.success(`Re-analyzed ${activePrompts.length} prompts with new keywords`);- await loadData();- } catch (err: unknown) {- const message = err instanceof Error ? err.message : 'Re-analysis failed';- if (message.includes('limit reached')) {- toast.error('Monthly volume analysis limit reached. Upgrade your plan for more.');- } else {- console.error('Re-analysis failed:', err);- toast.error('Re-analysis failed');- }- } finally {- setAnalyzing(false);- }- };+ const handleReanalyzeAll = () => runVolumeAnalysis(true);const totalGoogleVol = volumes.reduce((s, v) => s + v.totalGoogleVolume, 0);const totalAiVol = volumes.reduce((s, v) => s + v.estAiVolume, 0);@@ -1189,6 +1264,12 @@ export default function PromptsPage() {const quotaExhausted = quota !== null && quota.limit !== -1 && quota.remaining <= 0;+ // Reads "Analyzing 32/100..." once the first poll lands, so a run measured in+ // minutes shows movement instead of an indefinite spinner.+ const analyzingLabel = analysisProgress+ ? `Analyzing ${analysisProgress.analyzed}/${analysisProgress.total}...`+ : 'Analyzing...';+// Join prompts with their volume + visibility summaries once, reused by the// All Prompts table.const volumeByPromptId = useMemo(() => {@@ -1404,7 +1485,7 @@ export default function PromptsPage() {{analyzing ? (<><Loader2 className="mr-2 h-4 w-4 animate-spin" />- Analyzing...+ {analyzingLabel}</>) : (<>@@ -1483,7 +1564,7 @@ export default function PromptsPage() {) : (<BarChart3 className="h-4 w-4" />)}- {analyzing ? 'Analyzing...' : 'Re-analyze Keywords'}+ {analyzing ? analyzingLabel : 'Re-analyze Keywords'}</Button></>)}@@ -1501,7 +1582,7 @@ export default function PromptsPage() {) : (<BarChart3 className="h-4 w-4" />)}- {analyzing ? 'Analyzing...' : 'Analyze New Prompts'}+ {analyzing ? analyzingLabel : 'Analyze New Prompts'}</Button>)}</div>@@ -1535,7 +1616,7 @@ export default function PromptsPage() {) : (<BarChart3 className="h-4 w-4" />)}- {analyzing ? 'Analyzing...' : 'Analyze Volumes'}+ {analyzing ? analyzingLabel : 'Analyze Volumes'}</Button>{quotaExhausted && (<p className="text-xs text-red-500">diff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.tsindex b08ccf311..40412c287 100644--- a/web/src/lib/actions/volumes.ts+++ b/web/src/lib/actions/volumes.ts@@ -49,21 +49,55 @@ export async function analyzePromptVolume(}/**- * Analyze multiple prompts in batch.- * Uses saved keywords when available, calls LLM only for new prompts.- * Pass force=true to re-generate all keywords via LLM.+ * Failure codes the page can phrase for itself.+ *+ * The server's own text is diagnostic — DataForSEO status lines, Postgres+ * messages, argument validation — and none of it belongs in front of a+ * customer. Next.js also redacts thrown server-action messages in production,+ * so a caller reading `err.message` gets whatever the platform substituted+ * rather than the reason. A small closed set of codes survives both, and the+ * wording stays in the UI where it can be written for a person.*/-export async function analyzePromptVolumesBatch(- prompts: { promptId: string; promptText: string }[],- locationCode?: number,- languageCode?: string,+export type VolumeErrorCode = 'quota_exceeded' | 'plan_limit' | 'failed';++export type StartVolumeAnalysisResult =+ | { ok: true; started: number; running: boolean; remaining?: number }+ | { ok: false; code: VolumeErrorCode };++export interface VolumeAnalysisStatus {+ running: boolean;+ total: number;+ analyzed: number;+}++async function toErrorCode(res: Response): Promise<VolumeErrorCode> {+ const body: { error?: string } = await res.json().catch(() => ({}));+ if (body.error === 'quota_exceeded') return 'quota_exceeded';+ if (body.error === 'plan_limit') return 'plan_limit';+ console.error('Volume analysis request failed', res.status, body.error);+ return 'failed';+}++/**+ * Start volume analysis for a brand.+ *+ * The run outlives this request — a 100-prompt brand takes about eleven+ * minutes, since every prompt costs an LLM call plus a DataForSEO call and+ * they run in order. The server answers as soon as the work is queued;+ * `getVolumeAnalysisStatus` reports how far it has got.+ *+ * force=true re-generates keywords for every active prompt; the default fills+ * in only the prompts that have no volumes yet.+ */+export async function startPromptVolumeAnalysis(+ brandId: string,force?: boolean,-): Promise<{ results: (PromptVolume & { error?: string })[]; remaining?: number }> {+): Promise<StartVolumeAnalysisResult> {const supabase = await createClient();const {data: { session },} = await supabase.auth.getSession();- if (!session) throw new Error('Not authenticated');+ if (!session) return { ok: false, code: 'failed' };const res = await fetch(`${AEO_SERVER_URL}/api/volumes/analyze-batch`, {method: 'POST',@@ -71,15 +105,48 @@ export async function analyzePromptVolumesBatch('Content-Type': 'application/json',Authorization: `Bearer ${session.access_token}`,},- body: JSON.stringify({ prompts, locationCode, languageCode, force }),+ body: JSON.stringify({ brandId, force }),});- if (!res.ok) {- const body = await res.json().catch(() => ({}));- throw new Error(body.error || `Server error: ${res.status}`);- }+ if (!res.ok) return { ok: false, code: await toErrorCode(res) };- return res.json();+ const body = await res.json();+ return {+ ok: true,+ started: body.started ?? 0,+ running: Boolean(body.running),+ remaining: body.remaining,+ };+}++/**+ * 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+ * the run itself — the run is on the server and keeps going either way.+ */+export async function getVolumeAnalysisStatus(+ brandId: string,+): Promise<VolumeAnalysisStatus | null> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) return null;++ const res = await fetch(`${AEO_SERVER_URL}/api/volumes/status/${brandId}`, {+ method: 'GET',+ headers: { Authorization: `Bearer ${session.access_token}` },+ signal: AbortSignal.timeout(15_000),+ });++ if (!res.ok) return null;++ const body = await res.json();+ return {+ running: Boolean(body.running),+ total: body.total ?? 0,+ analyzed: body.analyzed ?? 0,+ };}/**@@ -90,12 +157,14 @@ export async function refreshVolumes(brandId: string,locationCode?: number,languageCode?: string,-): Promise<{ results: PromptVolume[]; refreshed: number; remaining?: number }> {+): Promise<+ { ok: true; refreshed: number; remaining?: number } | { ok: false; code: VolumeErrorCode }+> {const supabase = await createClient();const {data: { session },} = await supabase.auth.getSession();- if (!session) throw new Error('Not authenticated');+ if (!session) return { ok: false, code: 'failed' };const res = await fetch(`${AEO_SERVER_URL}/api/volumes/refresh`, {method: 'POST',@@ -106,12 +175,10 @@ export async function refreshVolumes(body: JSON.stringify({ brandId, locationCode, languageCode }),});- if (!res.ok) {- const body = await res.json().catch(() => ({}));- throw new Error(body.error || `Server error: ${res.status}`);- }+ if (!res.ok) return { ok: false, code: await toErrorCode(res) };- return res.json();+ const body = await res.json();+ return { ok: true, refreshed: body.refreshed ?? 0, remaining: body.remaining };}/**