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(fanout): complete aggregation, bounded fetches, real error messages (#428)
Gökhan Geyik2fa4c40fbabe
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsxindex d74b8d458..1b4ff6e52 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx@@ -46,6 +46,23 @@ type QueryFanoutTabProps = {const INTENT_INITIAL_LOAD_TIMEOUT_MS = 1500;+/**+ * Server-action failures reach the client with Next's production-masked+ * message ("An error occurred in the Server Components render… A digest+ * property is included…"), which is meaningless to users (#427). Surface the+ * real message only when it survived; otherwise fall back to a friendly one.+ */+function userErrorMessage(err: unknown, fallback: string): string {+ if (+ err instanceof Error &&+ err.message &&+ !/^An error occurred in the Server/i.test(err.message)+ ) {+ return err.message;+ }+ return fallback;+}+export function QueryFanoutTab({ brandId, onTracked }: QueryFanoutTabProps) {const [data, setData] = useState<QueryFanoutData | null>(null);const [loading, setLoading] = useState(true);@@ -93,7 +110,8 @@ export function QueryFanoutTab({ brandId, onTracked }: QueryFanoutTabProps) {}}} catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to load query fan-out');+ console.error('[fanout] load failed', err);+ toast.error(userErrorMessage(err, 'Failed to load query fan-out — please retry.'));setData({ subQueries: [], totalObserved: 0 });} finally {if (!silent) {@@ -141,6 +159,10 @@ export function QueryFanoutTab({ brandId, onTracked }: QueryFanoutTabProps) {setAddingKey(query.toLowerCase());try {const result = await trackFanoutQuery(brandId, query);+ if ('error' in result) {+ toast.error(result.error);+ return;+ }toast.success('Added as a tracked prompt');setData((prev) => {if (!prev) return prev;@@ -161,7 +183,8 @@ export function QueryFanoutTab({ brandId, onTracked }: QueryFanoutTabProps) {await load({ silent: true });await onTracked?.();} catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to track this query');+ console.error('[fanout] track failed', err);+ toast.error(userErrorMessage(err, 'Failed to track this query — please retry.'));} finally {setAddingKey(null);}diff --git a/web/src/lib/actions/fanout.ts b/web/src/lib/actions/fanout.tsindex 9f9394cde..7db38ce06 100644--- a/web/src/lib/actions/fanout.ts+++ b/web/src/lib/actions/fanout.ts@@ -3,6 +3,7 @@import { revalidatePath } from 'next/cache';import { createClient } from '@/lib/supabase/server';import { addPromptToSet } from '@/lib/actions/prompt';+import { PlanLimitError } from '@/lib/guards/plan-guard';import { API_BASE_URL } from '@/config/api';/**@@ -47,6 +48,53 @@ interface RawSearchQueryItem {/** Longest fan-out window a caller may request (days). */const MAX_FANOUT_DAYS = 90;+/**+ * PostgREST silently caps un-paginated selects at 1000 rows, which quietly+ * truncated the aggregation on exactly the brands where fan-out matters most+ * (#427). Page through the window instead, with a hard row ceiling so a+ * pathological brand can't pin the server action.+ */+const FANOUT_PAGE_SIZE = 1000;+const FANOUT_MAX_ROWS = 50_000;++/** How long the intent-classification round-trip may take before we abort (#427). */+const FANOUT_INTENT_FETCH_TIMEOUT_MS = 20_000;++interface FanoutResultRow {+ prompt_id: string | null;+ platform: string | null;+ search_queries: unknown;+}++async function fetchFanoutRows(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+ since: string,+ promptId?: string,+): Promise<FanoutResultRow[]> {+ const rows: FanoutResultRow[] = [];+ for (let from = 0; from < FANOUT_MAX_ROWS; from += FANOUT_PAGE_SIZE) {+ let query = supabase+ .from('prompt_results')+ .select('prompt_id, platform, search_queries')+ .eq('brand_id', brandId)+ .gte('created_at', since)+ // Deterministic order so .range() pages don't shuffle between requests.+ .order('created_at', { ascending: true })+ .order('id', { ascending: true })+ .range(from, from + FANOUT_PAGE_SIZE - 1);+ if (promptId) query = query.eq('prompt_id', promptId);++ const { data, error } = await query;+ if (error) throw new Error(error.message);++ const batch = (data ?? []) as FanoutResultRow[];+ rows.push(...batch);+ if (batch.length < FANOUT_PAGE_SIZE) break;+ }+ return rows;+}+/*** Canonical form of a sub-query for display + grouping: trim, then collapse any* internal whitespace run (double spaces, tabs, newlines) to a single space, so@@ -78,13 +126,7 @@ export async function getQueryFanout(// No server-side "non-empty" filter: comparing a jsonb column to '[]' through// PostgREST is unreliable, and rows with an empty fan-out contribute nothing// to the aggregation below anyway (the item loop skips them).- const { data: rows, error } = await supabase- .from('prompt_results')- .select('prompt_id, platform, search_queries')- .eq('brand_id', brandId)- .gte('created_at', since);-- if (error) throw new Error(error.message);+ const rows = await fetchFanoutRows(supabase, brandId, since);interface Acc {display: string;@@ -188,13 +230,12 @@ export async function getQueryFanout(* set, deriving platforms/models from its most recent active prompt.* `addPromptToSet` enforces the plan's `maxPrompts` limit.*/-export async function trackFanoutQuery(- brandId: string,- query: string,-): Promise<{ promptId: string }> {+export type TrackFanoutResult = { promptId: string } | { error: string };++export async function trackFanoutQuery(brandId: string, query: string): Promise<TrackFanoutResult> {const supabase = await createClient();const text = normalizeQuery(query);- if (!text) throw new Error('Empty query');+ if (!text) return { error: 'Empty query' };const { data: ps, error: psErr } = await supabase.from('prompt_sets')@@ -204,7 +245,7 @@ export async function trackFanoutQuery(.limit(1).maybeSingle();if (psErr || !ps) {- throw new Error('No prompt set exists for this brand. Create one first.');+ return { error: 'No prompt set exists for this brand. Create one first.' };}const { data: defaults } = await supabase@@ -222,7 +263,16 @@ export async function trackFanoutQuery(: ['chatgpt-web'];const models = Array.isArray(defaults?.models) ? (defaults!.models as string[]) : [];- const created = await addPromptToSet({ promptSetId: ps.id as string, text, platforms, models });+ // User-facing failures (plan limit, invalid input) come back as a VALUE:+ // production masks every error thrown from a server action, so a thrown+ // PlanLimitError reached users as the meaningless digest message (#427).+ let created;+ try {+ created = await addPromptToSet({ promptSetId: ps.id as string, text, platforms, models });+ } catch (err) {+ if (err instanceof PlanLimitError) return { error: err.message };+ throw err;+ }revalidatePath('/dashboard/prompts');return { promptId: created.id };@@ -243,6 +293,9 @@ export async function classifyFanoutIntents(queries: string[]): Promise<Record<s} = await supabase.auth.getSession();if (!session) throw new Error('Not authenticated');+ // Bounded: classifying a cold cache can take the aeo-server a while, and a+ // hung upstream must never pin this server action until the platform kills+ // it (#427). The tab degrades gracefully to no intent badges on rejection.const res = await fetch(`${API_BASE_URL}/api/prompts/fanout-intents`, {method: 'POST',headers: {@@ -250,6 +303,7 @@ export async function classifyFanoutIntents(queries: string[]): Promise<Record<sAuthorization: `Bearer ${session.access_token}`,},body: JSON.stringify({ queries }),+ signal: AbortSignal.timeout(FANOUT_INTENT_FETCH_TIMEOUT_MS),});if (!res.ok) {const body = await res.json().catch(() => ({}));@@ -274,14 +328,7 @@ export async function getPromptFanout(const days = Math.min(Math.max(Math.trunc(opts?.days ?? 30) || 30, 1), MAX_FANOUT_DAYS);const since = new Date(Date.now() - days * 86_400_000).toISOString();- const { data: rows, error } = await supabase- .from('prompt_results')- .select('prompt_id, platform, search_queries')- .eq('brand_id', brandId)- .eq('prompt_id', promptId)- .gte('created_at', since);-- if (error) throw new Error(error.message);+ const rows = await fetchFanoutRows(supabase, brandId, since, promptId);interface Acc {display: string;