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.

feat(prompts): Query Fan-out tab — observed sub-queries with times-searched + one-click track (#342)

Gökhan Geyik03e9fe899e07
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx
new file mode 100644
index 000000000..60092fd90
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx
@@ -0,0 +1,189 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { toast } from 'sonner';
+import { Link } from '@/i18n/navigation';
+import { getQueryFanout, trackFanoutQuery, type QueryFanoutData } from '@/lib/actions/fanout';
+import { PLATFORM_LABELS } from '@/config/platform-labels';
+import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { Check, Plus, Loader2, Search } from 'lucide-react';
+
+function platformLabel(slug: string): string {
+ return PLATFORM_LABELS[slug] ?? slug;
+}
+
+export function QueryFanoutTab({ brandId }: { brandId: string }) {
+ const [data, setData] = useState<QueryFanoutData | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [addingKey, setAddingKey] = useState<string | null>(null);
+
+ const load = useCallback(async () => {
+ setLoading(true);
+ try {
+ const result = await getQueryFanout(brandId, { days: 30 });
+ setData(result);
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to load query fan-out');
+ setData({ subQueries: [], totalObserved: 0 });
+ } finally {
+ setLoading(false);
+ }
+ }, [brandId]);
+
+ useEffect(() => {
+ load();
+ }, [load]);
+
+ async function handleTrack(query: string) {
+ setAddingKey(query.toLowerCase());
+ try {
+ await trackFanoutQuery(brandId, query);
+ toast.success('Added as a tracked prompt');
+ await load();
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to track this query');
+ } finally {
+ setAddingKey(null);
+ }
+ }
+
+ return (
+ <Card>
+ <CardHeader className="pb-3">
+ <CardTitle className="text-sm font-medium">Query fan-out</CardTitle>
+ <p className="text-xs text-muted-foreground">
+ The sub-queries answer engines actually ran while building your answers (last 30 days) —
+ observed, never predicted. Sorted by how often they were searched. Track any of them with
+ the <span className="font-medium">+</span> to measure its own visibility.
+ </p>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <div className="space-y-2">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <Skeleton key={i} className="h-11 w-full" />
+ ))}
+ </div>
+ ) : !data || data.subQueries.length === 0 ? (
+ <div className="flex flex-col items-center gap-2 py-12 text-center">
+ <Search className="h-8 w-8 text-muted-foreground/50" />
+ <p className="text-sm font-medium">No fan-out captured yet</p>
+ <p className="max-w-md text-xs text-muted-foreground">
+ Fan-out is emitted mostly by <span className="font-medium">Copilot</span> and{' '}
+ <span className="font-medium">Perplexity</span>, and only for some queries. Once those
+ platforms run for your prompts, the observed sub-queries will appear here.
+ </p>
+ </div>
+ ) : (
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Sub-query</TableHead>
+ <TableHead className="w-[160px]">Engine</TableHead>
+ <TableHead className="w-[120px] text-right">Times searched</TableHead>
+ <TableHead className="w-[240px]">Sourced prompts</TableHead>
+ <TableHead className="w-[64px] text-right">Track</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {data.subQueries.map((sq) => {
+ const key = sq.query.toLowerCase();
+ const adding = addingKey === key;
+ return (
+ <TableRow key={key}>
+ <TableCell className="font-medium">{sq.query}</TableCell>
+ <TableCell>
+ <div className="flex flex-wrap gap-1">
+ {sq.engines.map((e) => (
+ <Badge key={e} variant="secondary" className="text-[10px]">
+ {platformLabel(e)}
+ </Badge>
+ ))}
+ </div>
+ </TableCell>
+ <TableCell className="text-right tabular-nums">{sq.timesSearched}</TableCell>
+ <TableCell>
+ <SourcedPrompts prompts={sq.sourcedPrompts} />
+ </TableCell>
+ <TableCell className="text-right">
+ {sq.tracked ? (
+ <Badge
+ variant="outline"
+ className="gap-1 text-[10px] text-emerald-600 dark:text-emerald-400"
+ render={
+ sq.trackedPromptId ? (
+ <Link href={`/dashboard/prompts/${sq.trackedPromptId}`} />
+ ) : undefined
+ }
+ >
+ <Check className="h-3 w-3" />
+ Tracked
+ </Badge>
+ ) : (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-7 w-7"
+ disabled={adding}
+ onClick={() => handleTrack(sq.query)}
+ aria-label={`Track "${sq.query}" as a prompt`}
+ >
+ {adding ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="h-4 w-4" />
+ )}
+ </Button>
+ )}
+ </TableCell>
+ </TableRow>
+ );
+ })}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ );
+}
+
+function SourcedPrompts({ prompts }: { prompts: { id: string; text: string }[] }) {
+ if (prompts.length === 0) {
+ return <span className="text-xs text-muted-foreground">—</span>;
+ }
+ const shown = prompts.slice(0, 2);
+ const rest = prompts.slice(2);
+ return (
+ <div className="flex flex-wrap items-center gap-1">
+ {shown.map((p) => (
+ <Link
+ key={p.id}
+ href={`/dashboard/prompts/${p.id}`}
+ title={p.text}
+ className="max-w-[160px] truncate rounded bg-muted px-1.5 py-0.5 text-[11px] text-muted-foreground hover:text-foreground"
+ >
+ {p.text}
+ </Link>
+ ))}
+ {rest.length > 0 && (
+ <span
+ className="text-[11px] text-muted-foreground"
+ title={rest.map((p) => p.text).join('\n')}
+ >
+ +{rest.length}
+ </span>
+ )}
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index ea0d48008..09e4befeb 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -12,6 +12,7 @@ const PlatformVolumeChart = dynamic(() => import('./_charts').then((m) => m.Plat
loading: () => <Skeleton className="h-64 w-full" />,
});
import { SuggestionsCard } from './_suggestions-card';
+import { QueryFanoutTab } from './_fanout-tab';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Button, buttonVariants } from '@/components/ui/button';
@@ -218,7 +219,7 @@ const PROMPT_EXPORT_HINT = 'No prompts yet - add prompts first.';
// ─── Helpers ──────────────────────────────────────────────────────────────────
-const VALID_TABS = ['all', 'insights'] as const;
+const VALID_TABS = ['all', 'fanout', 'insights'] as const;
type TabId = (typeof VALID_TABS)[number];
function formatRelative(iso?: string): string {
@@ -560,6 +561,7 @@ export default function PromptsPage() {
<div className="flex items-center justify-between gap-4 flex-wrap">
<TabsList>
<TabsTrigger value="all">All Prompts</TabsTrigger>
+ <TabsTrigger value="fanout">Query Fan-out</TabsTrigger>
<TabsTrigger value="insights">Insights</TabsTrigger>
</TabsList>
<div className="flex items-center gap-2">
@@ -636,6 +638,11 @@ export default function PromptsPage() {
/>
</TabsContent>
+ {/* ─── Query Fan-out tab ───────────────────────────────────────── */}
+ <TabsContent value="fanout" className="mt-4">
+ {activeBrandId && <QueryFanoutTab brandId={activeBrandId} />}
+ </TabsContent>
+
{/* ─── Insights tab ────────────────────────────────────────────── */}
<TabsContent value="insights" className="mt-4">
{/* Action toolbar */}
diff --git a/web/src/lib/actions/fanout.ts b/web/src/lib/actions/fanout.ts
new file mode 100644
index 000000000..2dbafc224
--- /dev/null
+++ b/web/src/lib/actions/fanout.ts
@@ -0,0 +1,228 @@
+'use server';
+
+import { revalidatePath } from 'next/cache';
+import { createClient } from '@/lib/supabase/server';
+import { addPromptToSet } from '@/lib/actions/prompt';
+
+/**
+ * Query Fan-out (#333) — read + promote actions over the OBSERVED sub-queries
+ * answer engines actually ran, captured in `prompt_results.search_queries`
+ * (#332) as `[{ query, engine?, source_platform }]`. Read-only aggregation;
+ * we never synthesize sub-queries.
+ */
+
+export interface FanoutSourcePrompt {
+ id: string;
+ text: string;
+}
+
+export interface FanoutSubQuery {
+ /** The observed sub-query, in its canonical (trimmed) form. */
+ query: string;
+ /** Source-platform slugs that surfaced it (UI maps to labels). */
+ engines: string[];
+ /** Distinct tracked answers whose fan-out contained this sub-query. */
+ timesSearched: number;
+ /** The user's tracked prompts whose answers ran this sub-query. */
+ sourcedPrompts: FanoutSourcePrompt[];
+ /** True when this exact sub-query is already tracked as a prompt. */
+ tracked: boolean;
+ /** The tracked prompt's id when `tracked` (for linking), else null. */
+ trackedPromptId: string | null;
+}
+
+export interface QueryFanoutData {
+ subQueries: FanoutSubQuery[];
+ /** Total distinct observed sub-queries in the window. */
+ totalObserved: number;
+}
+
+interface RawSearchQueryItem {
+ query?: unknown;
+ engine?: unknown;
+ source_platform?: unknown;
+}
+
+/** Longest fan-out window a caller may request (days). */
+const MAX_FANOUT_DAYS = 90;
+
+/**
+ * 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
+ * "best laptops" and "best laptops" group as one row.
+ */
+function normalizeQuery(raw: string): string {
+ return raw.replace(/\s+/g, ' ').trim();
+}
+
+/**
+ * Aggregate the brand's observed query fan-out over a rolling window.
+ *
+ * `timesSearched` counts DISTINCT answers (prompt_results rows) whose
+ * `search_queries` contains the sub-query — an observed demand signal that
+ * replaces Google Ads volume for these long-tail, natural-language queries.
+ * Grouping is by the normalized, lower-cased query string (see normalizeQuery)
+ * so whitespace/case variants collapse into one row.
+ */
+export async function getQueryFanout(
+ brandId: string,
+ opts?: { days?: number },
+): Promise<QueryFanoutData> {
+ const supabase = await createClient();
+ // Clamp the window to a sane range so a crafted call can't force an
+ // unbounded prompt_results scan + in-memory aggregation.
+ 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();
+
+ // 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);
+
+ interface Acc {
+ display: string;
+ engines: Set<string>;
+ promptIds: Set<string>;
+ answerCount: number;
+ }
+ const byQuery = new Map<string, Acc>();
+
+ for (const row of rows ?? []) {
+ const items = Array.isArray(row.search_queries)
+ ? (row.search_queries as RawSearchQueryItem[])
+ : [];
+ // Dedup within a single answer so one answer counts once per sub-query,
+ // even if the engine listed it twice.
+ const seenInRow = new Set<string>();
+ for (const item of items) {
+ const q = typeof item?.query === 'string' ? normalizeQuery(item.query) : '';
+ if (!q) continue;
+ const key = q.toLowerCase();
+
+ let acc = byQuery.get(key);
+ if (!acc) {
+ acc = { display: q, engines: new Set(), promptIds: new Set(), answerCount: 0 };
+ byQuery.set(key, acc);
+ }
+
+ const sp =
+ typeof item?.source_platform === 'string' && item.source_platform
+ ? item.source_platform
+ : (row.platform as string | null);
+ if (sp) acc.engines.add(sp);
+ if (row.prompt_id) acc.promptIds.add(row.prompt_id as string);
+
+ if (!seenInRow.has(key)) {
+ acc.answerCount += 1;
+ seenInRow.add(key);
+ }
+ }
+ }
+
+ if (byQuery.size === 0) return { subQueries: [], totalObserved: 0 };
+
+ // Resolve the sourced prompts' text (the prompts whose answers produced the
+ // fan-out) so the UI can link back to them.
+ const allPromptIds = [...new Set([...byQuery.values()].flatMap((a) => [...a.promptIds]))];
+ const promptTextById = new Map<string, string>();
+ if (allPromptIds.length > 0) {
+ const { data: promptRows } = await supabase
+ .from('prompts')
+ .select('id, text')
+ .in('id', allPromptIds);
+ for (const p of promptRows ?? []) {
+ promptTextById.set(p.id as string, p.text as string);
+ }
+ }
+
+ // Which sub-queries are already tracked as prompts for THIS brand? Compare
+ // against the brand's active prompt texts so the row shows Tracked ✓ vs +.
+ const { data: brandSets } = await supabase
+ .from('prompt_sets')
+ .select('id')
+ .eq('brand_id', brandId);
+ const setIds = (brandSets ?? []).map((s) => s.id as string);
+ const trackedByText = new Map<string, string>();
+ if (setIds.length > 0) {
+ const { data: existing } = await supabase
+ .from('prompts')
+ .select('id, text')
+ .in('prompt_set_id', setIds)
+ .eq('is_active', true);
+ for (const p of existing ?? []) {
+ trackedByText.set(normalizeQuery(p.text as string).toLowerCase(), p.id as string);
+ }
+ }
+
+ const subQueries: FanoutSubQuery[] = [...byQuery.entries()]
+ .map(([key, acc]) => {
+ const trackedPromptId = trackedByText.get(key) ?? null;
+ const sourcedPrompts = [...acc.promptIds]
+ .map((id) => ({ id, text: promptTextById.get(id) ?? '' }))
+ .filter((p) => p.text)
+ .sort((a, b) => a.text.localeCompare(b.text));
+ return {
+ query: acc.display,
+ engines: [...acc.engines].sort(),
+ timesSearched: acc.answerCount,
+ sourcedPrompts,
+ tracked: trackedPromptId !== null,
+ trackedPromptId,
+ };
+ })
+ .sort((a, b) => b.timesSearched - a.timesSearched || a.query.localeCompare(b.query));
+
+ return { subQueries, totalObserved: subQueries.length };
+}
+
+/**
+ * Promote an observed sub-query into a tracked prompt for the brand. Mirrors
+ * the Insights "accept suggestion" flow: add to the brand's earliest prompt
+ * 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 }> {
+ const supabase = await createClient();
+ const text = normalizeQuery(query);
+ if (!text) throw new Error('Empty query');
+
+ const { data: ps, error: psErr } = await supabase
+ .from('prompt_sets')
+ .select('id')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending: true })
+ .limit(1)
+ .maybeSingle();
+ if (psErr || !ps) {
+ throw new Error('No prompt set exists for this brand. Create one first.');
+ }
+
+ const { data: defaults } = await supabase
+ .from('prompts')
+ .select('platforms, models')
+ .eq('prompt_set_id', ps.id)
+ .eq('is_active', true)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ const platforms =
+ Array.isArray(defaults?.platforms) && defaults!.platforms.length > 0
+ ? (defaults!.platforms as string[])
+ : ['chatgpt-web'];
+ const models = Array.isArray(defaults?.models) ? (defaults!.models as string[]) : [];
+
+ const created = await addPromptToSet({ promptSetId: ps.id as string, text, platforms, models });
+
+ revalidatePath('/dashboard/prompts');
+ return { promptId: created.id };
+}
diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.ts
index c57441b55..4b1bcc962 100644
--- a/web/src/types/supabase.ts
+++ b/web/src/types/supabase.ts
@@ -664,6 +664,7 @@ export type Database = {
prompt_id: string;
region: string | null;
response: string;
+ search_queries: Json;
sentiment: string;
shopping_cards: Json;
visibility_score: number;
@@ -682,6 +683,7 @@ export type Database = {
prompt_id: string;
region?: string | null;
response?: string;
+ search_queries?: Json;
sentiment?: string;
shopping_cards?: Json;
visibility_score?: number;
@@ -700,6 +702,7 @@ export type Database = {
prompt_id?: string;
region?: string | null;
response?: string;
+ search_queries?: Json;
sentiment?: string;
shopping_cards?: Json;
visibility_score?: number;