Skip to content

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.

fix(prompts): consolidate the page's first load into one server action (#473)

Gökhan Geyik8a82ec0e191c
diff --git a/supabase/migrations/00025_prompt_visibility_summaries.sql b/supabase/migrations/00025_prompt_visibility_summaries.sql
new file mode 100644
index 000000000..5e0a828eb
--- /dev/null
+++ b/supabase/migrations/00025_prompt_visibility_summaries.sql
@@ -0,0 +1,42 @@
+-- ── Per-prompt visibility summaries (#472 / prompts first-load fix) ──────────
+--
+-- The All Prompts tab's health columns were computed by fetching the brand's
+-- raw prompt_results window into JS: un-paginated, so PostgREST silently
+-- capped it at 1000 rows (wrong numbers on busy brands — same family as
+-- #430/#464/#450) and the transfer cost slowed the page's first load. One
+-- GROUP BY returns at most one row per prompt instead.
+--
+-- SECURITY INVOKER (00014 convention); excludes chatgpt-shopping (#155) to
+-- match every other analytical surface.
+
+CREATE OR REPLACE FUNCTION public.prompt_visibility_summaries(
+ p_brand_id uuid,
+ p_date_from timestamptz DEFAULT NULL
+)
+RETURNS TABLE (
+ prompt_id uuid,
+ avg_visibility double precision,
+ total_mentions bigint,
+ runs bigint,
+ last_run_at timestamptz
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT pr.prompt_id,
+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,
+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,
+ COUNT(*)::bigint AS runs,
+ MAX(pr.created_at) AS last_run_at
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.prompt_id IS NOT NULL
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from analytics
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ GROUP BY pr.prompt_id
+$$;
+
+GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz)
+ TO authenticated;
diff --git a/supabase/schema.sql b/supabase/schema.sql
index 0f5d860c0..3e6226f1d 100644
--- a/supabase/schema.sql
+++ b/supabase/schema.sql
@@ -3091,3 +3091,49 @@ GRANT EXECUTE ON FUNCTION public.tracked_prompt_count(
uuid, text, text[], text, timestamptz, timestamptz, uuid
) TO authenticated;
+-- ─────────────────────────────────────────────────────────────────────────
+-- migrations/00025_prompt_visibility_summaries.sql
+-- ─────────────────────────────────────────────────────────────────────────
+-- ── Per-prompt visibility summaries (#472 / prompts first-load fix) ──────────
+--
+-- The All Prompts tab's health columns were computed by fetching the brand's
+-- raw prompt_results window into JS: un-paginated, so PostgREST silently
+-- capped it at 1000 rows (wrong numbers on busy brands — same family as
+-- #430/#464/#450) and the transfer cost slowed the page's first load. One
+-- GROUP BY returns at most one row per prompt instead.
+--
+-- SECURITY INVOKER (00014 convention); excludes chatgpt-shopping (#155) to
+-- match every other analytical surface.
+
+CREATE OR REPLACE FUNCTION public.prompt_visibility_summaries(
+ p_brand_id uuid,
+ p_date_from timestamptz DEFAULT NULL
+)
+RETURNS TABLE (
+ prompt_id uuid,
+ avg_visibility double precision,
+ total_mentions bigint,
+ runs bigint,
+ last_run_at timestamptz
+)
+LANGUAGE sql
+STABLE
+SECURITY INVOKER
+SET search_path = public
+AS $$
+ SELECT pr.prompt_id,
+ AVG(COALESCE(pr.visibility_score, 0))::double precision AS avg_visibility,
+ COALESCE(SUM(pr.mention_count), 0)::bigint AS total_mentions,
+ COUNT(*)::bigint AS runs,
+ MAX(pr.created_at) AS last_run_at
+ FROM public.prompt_results pr
+ WHERE pr.brand_id = p_brand_id
+ AND pr.prompt_id IS NOT NULL
+ AND pr.platform <> 'chatgpt-shopping' -- #155 — isolate from analytics
+ AND (p_date_from IS NULL OR pr.created_at >= p_date_from)
+ GROUP BY pr.prompt_id
+$$;
+
+GRANT EXECUTE ON FUNCTION public.prompt_visibility_summaries(uuid, timestamptz)
+ TO authenticated;
+
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 730dadec4..c6a400b2b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -46,14 +46,9 @@ import {
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
-import {
- getPromptVolumes,
- analyzePromptVolumesBatch,
- refreshVolumes,
- type VolumeQuota,
-} from '@/lib/actions/volumes';
-import { getPromptSets } from '@/lib/actions/prompt';
-import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';
+import { analyzePromptVolumesBatch, refreshVolumes, type VolumeQuota } from '@/lib/actions/volumes';
+import { getPromptsPageData } from '@/lib/actions/prompt';
+import { type PromptVisibilitySummary } from '@/lib/actions/tracking';
import { aggregatePromptVolumeClusters } from '@/lib/prompt-volume-clusters';
import type { PromptVolume, Prompt } from '@/types';
import { toast } from 'sonner';
@@ -319,17 +314,19 @@ export default function PromptsPage() {
setLoading(true);
try {
- const [volumeResult, promptSets, visSummary] = await Promise.all([
- getPromptVolumes(activeBrandId),
- getPromptSets(activeBrandId),
- getPromptVisibilitySummaries(activeBrandId, { days: 30 }),
- ]);
+ // One consolidated server action: Next.js queues client-fired server
+ // actions sequentially, so the old three separate calls cost their
+ // SUM on a cold load — the main culprit behind the slow first paint.
+ const page = await getPromptsPageData(activeBrandId);
if (isCancelled?.()) return;
- setVolumes(volumeResult.volumes);
- if (volumeResult.quota) setQuota(volumeResult.quota);
- const prompts = promptSets.flatMap((ps) => ps.prompts);
+ setVolumes(page.volumes);
+ if (page.quota) setQuota(page.quota);
+ const prompts = page.promptSets.flatMap((ps) => ps.prompts);
setAllPrompts(prompts);
- setVisibility(visSummary);
+ setVisibility(page.visibility);
+ if (page.volumesDegraded) {
+ toast.warning('Volume data is temporarily unavailable — showing prompts without it.');
+ }
} catch (err) {
if (isCancelled?.()) return;
console.error('Failed to load prompt data:', err);
diff --git a/web/src/lib/actions/prompt-suggestions.ts b/web/src/lib/actions/prompt-suggestions.ts
index c00a3fe60..c1e1c8cec 100644
--- a/web/src/lib/actions/prompt-suggestions.ts
+++ b/web/src/lib/actions/prompt-suggestions.ts
@@ -67,6 +67,9 @@ export async function getPromptSuggestions(
const res = await fetch(`${AEO_SERVER_URL}/api/prompts/suggestions/${brandId}`, {
headers: { Authorization: `Bearer ${session.access_token}` },
cache: 'no-store',
+ // Read-only cache lookup — a hung upstream must not pin the suggestions
+ // card (and the serialized server-action queue behind it) indefinitely.
+ signal: AbortSignal.timeout(15_000),
});
if (!res.ok) {
const body = await res.json().catch(() => ({}));
diff --git a/web/src/lib/actions/prompt.ts b/web/src/lib/actions/prompt.ts
index d34560cb0..105202ce2 100644
--- a/web/src/lib/actions/prompt.ts
+++ b/web/src/lib/actions/prompt.ts
@@ -2,10 +2,12 @@
import { createClient } from '@/lib/supabase/server';
import { revalidatePath } from 'next/cache';
-import type { PromptSet, Prompt, AIPlatform } from '@/types';
+import type { PromptSet, Prompt, AIPlatform, PromptVolume } from '@/types';
import { enforceLimit, getOrgPlan } from '@/lib/guards/plan-guard';
import { ALL_MODELS, ALL_SCRAPERS } from '@/config/prompt-options';
import type { Plan } from '@/config/plans';
+import { getPromptVolumes, type VolumeQuota } from '@/lib/actions/volumes';
+import { getPromptVisibilitySummaries, type PromptVisibilitySummary } from '@/lib/actions/tracking';
function filterByPlan(plan: Plan, platforms: string[], models: string[]) {
const allowedScrapers = plan.limits.allowedScrapers
@@ -399,3 +401,47 @@ export async function deletePromptSet(id: string): Promise<void> {
revalidatePath('/dashboard/brands');
}
+
+export interface PromptsPageData {
+ promptSets: PromptSet[];
+ visibility: Record<string, PromptVisibilitySummary>;
+ volumes: PromptVolume[];
+ quota: VolumeQuota | null;
+ /** True when the volumes upstream failed/timed out — the table still renders. */
+ volumesDegraded: boolean;
+}
+
+/**
+ * One consolidated server action for the Prompts page's first load.
+ *
+ * Next.js runs server actions sequentially — each is its own queued POST — so
+ * the page's old three separate calls (volumes + prompt sets + visibility)
+ * cost roughly their SUM on a cold load, with the suggestions card queued
+ * behind them (the #313 lesson from Insights). This runs them in a real
+ * server-side Promise.all: one round trip, genuinely parallel.
+ *
+ * Volumes come from the aeo-server and are the least reliable dependency, so
+ * their failure degrades to an empty list instead of blanking the prompt
+ * table — the page's core content must never be hostage to the volumes API.
+ */
+export async function getPromptsPageData(brandId: string): Promise<PromptsPageData> {
+ const [promptSets, visibility, volumesResult] = await Promise.all([
+ getPromptSets(brandId),
+ getPromptVisibilitySummaries(brandId, { days: 30 }),
+ getPromptVolumes(brandId).then(
+ (r) => ({ volumes: r.volumes, quota: r.quota ?? null, degraded: false }),
+ (err) => {
+ console.error('[prompts] volumes fetch failed, rendering without them:', err);
+ return { volumes: [] as PromptVolume[], quota: null, degraded: true };
+ },
+ ),
+ ]);
+
+ return {
+ promptSets,
+ visibility,
+ volumes: volumesResult.volumes,
+ quota: volumesResult.quota,
+ volumesDegraded: volumesResult.degraded,
+ };
+}
diff --git a/web/src/lib/actions/tracking.ts b/web/src/lib/actions/tracking.ts
index fa4961e36..4e847789a 100644
--- a/web/src/lib/actions/tracking.ts
+++ b/web/src/lib/actions/tracking.ts
@@ -1009,51 +1009,25 @@ export async function getPromptVisibilitySummaries(
const days = opts?.days ?? 30;
const since = new Date(Date.now() - days * 24 * 60 * 60 * 1000).toISOString();
- // #155 — visibility summary per prompt; exclude chatgpt-shopping to
- // match the aggregate-RPC filters one level up.
- const { data, error } = await supabase
- .from('prompt_results')
- .select('prompt_id, visibility_score, mention_count, created_at')
- .eq('brand_id', brandId)
- .neq('platform', 'chatgpt-shopping')
- .gte('created_at', since);
+ // One GROUP BY in Postgres (migration 00025) instead of pulling the raw
+ // result window into JS: the old un-paginated select silently capped at
+ // 1000 rows (wrong health columns on busy brands — the #430/#464 defect
+ // family) and its transfer cost slowed the Prompts page's first load.
+ // The RPC excludes chatgpt-shopping (#155) like every analytical surface.
+ const { data, error } = await supabase.rpc('prompt_visibility_summaries', {
+ p_brand_id: brandId,
+ p_date_from: since,
+ });
if (error) throw new Error(error.message);
- const acc: Record<
- string,
- { sumVis: number; sumMentions: number; runs: number; lastRunAt: string }
- > = {};
-
- for (const r of (data ?? []) as Record<string, unknown>[]) {
- const pid = r.prompt_id as string;
- if (!pid) continue;
- const vis = (r.visibility_score as number) ?? 0;
- const mentions = (r.mention_count as number) ?? 0;
- const createdAt = r.created_at as string;
- const existing = acc[pid];
- if (existing) {
- existing.sumVis += vis;
- existing.sumMentions += mentions;
- existing.runs += 1;
- if (createdAt > existing.lastRunAt) existing.lastRunAt = createdAt;
- } else {
- acc[pid] = {
- sumVis: vis,
- sumMentions: mentions,
- runs: 1,
- lastRunAt: createdAt,
- };
- }
- }
-
const result: Record<string, PromptVisibilitySummary> = {};
- for (const [pid, v] of Object.entries(acc)) {
- result[pid] = {
- avgVisibility: v.runs > 0 ? v.sumVis / v.runs : 0,
- totalMentions: v.sumMentions,
- runs: v.runs,
- lastRunAt: v.lastRunAt,
+ for (const row of data ?? []) {
+ result[row.prompt_id] = {
+ avgVisibility: row.avg_visibility ?? 0,
+ totalMentions: Number(row.total_mentions ?? 0),
+ runs: Number(row.runs ?? 0),
+ lastRunAt: row.last_run_at,
};
}
return result;
diff --git a/web/src/lib/actions/volumes.ts b/web/src/lib/actions/volumes.ts
index 787a38c75..b08ccf311 100644
--- a/web/src/lib/actions/volumes.ts
+++ b/web/src/lib/actions/volumes.ts
@@ -131,6 +131,9 @@ export async function getPromptVolumes(
headers: {
Authorization: `Bearer ${session.access_token}`,
},
+ // A hung upstream must never pin this action — and with it the whole
+ // Prompts page load — until the platform kills it (#427 lesson).
+ signal: AbortSignal.timeout(15_000),
});
if (!res.ok) {
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index 48c6027bf..fe5c9fd06 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -1204,6 +1204,19 @@ export type Database = {
};
Returns: number;
};
+ prompt_visibility_summaries: {
+ Args: {
+ p_brand_id: string;
+ p_date_from?: string | null;
+ };
+ Returns: {
+ prompt_id: string;
+ avg_visibility: number;
+ total_mentions: number;
+ runs: number;
+ last_run_at: string;
+ }[];
+ };
competitor_aggregates: {
Args: {
p_brand_id: string;