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
feat(prompts): show which engines share their searches on the Query Fan-out page (#1057)
Cihanbbb9f6399d7d
diff --git a/web/messages/en.json b/web/messages/en.jsonindex d13f84834..fbe96cb4a 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -2408,6 +2408,24 @@"nonePaused": "No paused prompts match."}},+ "fanout": {+ "engines": "Engines",+ "allEngines": "All engines",+ "share": "{percent} of answers",+ "noneSince": "none since {date}",+ "noneInWindow": "none in this window",+ "notShared": "not shared",+ "silentTitle": "{engine} usually shares the searches behind its answers, but none arrived since {date}.",+ "silentTitleNoDate": "{engine} usually shares the searches behind its answers, but none arrived in this window.",+ "silentBody": "Its answers are still tracked as usual; only the list of searches is missing.",+ "notSharedNote": "{engines} don't come with the searches behind their answers, so they can't appear here.",+ "enginesLegend": "Coloured: shared searches for this prompt in the window. Faded: tracked, but shared none.",+ "engineEmptyTitle": "No {engine} searches in the {range}",+ "engineEmptyBody": "{engine} usually shares the searches behind its answers. Try a longer date range.",+ "emptyTitle": "No fan-out captured yet",+ "emptyBody": "ChatGPT, Copilot and Perplexity share the searches behind some of their answers; Google AI Overviews, AI Mode and Gemini don't share them. Once those engines run for your prompts, the searches will appear here.",+ "coverageTooltip": "Of {total} tracked answers in this window, {withFanout} came with the searches the engine ran. Only ChatGPT, Copilot and Perplexity share them."+ },"bulkDelete": {"progress": "Deleting {done} of {total} prompts…","failed": "{count, plural, one {Failed to delete the prompt.} other {Failed to delete the prompts.}}",diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.test.tsxnew file mode 100644index 000000000..23d47e23c--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.test.tsx@@ -0,0 +1,130 @@+import { act } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { NextIntlClientProvider } from 'next-intl';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import messages from '../../../../../../messages/en.json';+import type { FanoutEngineCoverage } from '@/lib/actions/fanout';+import { FanoutEngineNotices, FanoutEngineStrip, isSilentEngine } from './_fanout-engines';++(+ globalThis as typeof globalThis & {+ IS_REACT_ACT_ENVIRONMENT: boolean;+ }+).IS_REACT_ACT_ENVIRONMENT = true;++const engine = (over: Partial<FanoutEngineCoverage>): FanoutEngineCoverage => ({+ platform: 'copilot-web',+ answers: 100,+ answersWithFanout: 21,+ subQueries: 706,+ lastFanoutAt: null,+ ...over,+});++// What production showed on 2026-10-15: Copilot shares, ChatGPT stopped on+// Sep 30, Google's engines never share.+const engines = [+ engine({}),+ engine({+ platform: 'chatgpt-web',+ answersWithFanout: 0,+ subQueries: 0,+ lastFanoutAt: '2026-09-29T05:12:00Z',+ }),+ engine({ platform: 'google-aio', answersWithFanout: 0, subQueries: 0 }),+ engine({ platform: 'gemini-web', answersWithFanout: 0, subQueries: 0 }),+];++let container: HTMLDivElement;+let root: Root;++function render(node: React.ReactNode) {+ act(() => {+ root.render(+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">+ {node}+ </NextIntlClientProvider>,+ );+ });+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+});++describe('FanoutEngineStrip', () => {+ it("shows each engine's share, when a silent one last shared, and the ones that never share", () => {+ const onSelect = vi.fn();+ render(+ <FanoutEngineStrip+ engines={engines}+ totalSubQueries={706}+ selected={null}+ onSelect={onSelect}+ />,+ );++ const buttons = [...container.querySelectorAll('button')].map((b) => b.textContent);+ expect(buttons).toEqual([+ 'All engines706',+ 'Microsoft Copilot21% of answers · 706',+ 'ChatGPTnone since Sep 29',+ ]);+ // Never-sharing engines are labels, not filters.+ expect(container.textContent).toContain('Google AI Overview · not shared');+ expect(container.textContent).toContain('Google Gemini · not shared');++ act(() => container.querySelectorAll('button')[2].click());+ expect(onSelect).toHaveBeenCalledWith('chatgpt-web');+ });++ it('clears the filter when the picked engine is clicked again', () => {+ const onSelect = vi.fn();+ render(+ <FanoutEngineStrip+ engines={engines}+ totalSubQueries={706}+ selected="copilot-web"+ onSelect={onSelect}+ />,+ );+ act(() => container.querySelectorAll('button')[1].click());+ expect(onSelect).toHaveBeenCalledWith(null);+ });+});++describe('FanoutEngineNotices', () => {+ it('explains a silent engine and names the engines that never share', () => {+ render(<FanoutEngineNotices engines={engines} />);+ expect(container.textContent).toContain(+ 'ChatGPT usually shares the searches behind its answers, but none arrived since Sep 29.',+ );+ expect(container.textContent).toContain(+ "Google AI Overview and Google Gemini don't come with the searches behind their answers",+ );+ });++ it('says nothing once every sharing engine shares again', () => {+ render(<FanoutEngineNotices engines={[engine({})]} />);+ expect(container.textContent).toBe('');+ });+});++describe('isSilentEngine', () => {+ it('is only an engine that shares searches, answered, and shared none', () => {+ expect(isSilentEngine(engines[1])).toBe(true);+ expect(isSilentEngine(engines[0])).toBe(false);+ expect(isSilentEngine(engines[2])).toBe(false);+ // Four answers with none is chance, not an outage.+ expect(+ isSilentEngine(engine({ platform: 'chatgpt-web', answers: 4, answersWithFanout: 0 })),+ ).toBe(false);+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.tsxnew file mode 100644index 000000000..88a94f490--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-engines.tsx@@ -0,0 +1,227 @@+'use client';++import { useFormatter, useTranslations } from 'next-intl';+import { AlertTriangle, Info } from 'lucide-react';+import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';+import { PLATFORM_LABELS } from '@/config/platform-labels';+import {+ API_MODEL_PLATFORMS,+ FANOUT_MIN_SILENT_ANSWERS,+ fanoutSharing,+} from '@/config/fanout-platforms';+import type { FanoutEngineCoverage } from '@/lib/actions/fanout';+import { cn } from '@/lib/utils';++/**+ * The Query Fan-out page's per-engine view: which engines shared the searches+ * behind their answers, which shared none although they usually do, and+ * which never share them. Without it the page read as broken whenever the+ * list held only Copilot: ChatGPT's searches stopped arriving on 2026-09-30,+ * and Google AI Overviews, AI Mode and Gemini never send any.+ */++export function platformLabel(platform: string): string {+ const label = PLATFORM_LABELS[platform] ?? platform;+ // "ChatGPT API" beside the ChatGPT app, never two plain "ChatGPT"s.+ return API_MODEL_PLATFORMS.includes(platform) ? `${label} API` : label;+}++/** A share of answers as a whole percent; a small non-zero one isn't "0%". */+function useShare() {+ const format = useFormatter();+ return (part: number, whole: number) => {+ if (whole === 0) return '–';+ const rate = part / whole;+ if (rate > 0 && rate < 0.01) return '<1%';+ return format.number(rate, { style: 'percent', maximumFractionDigits: 0 });+ };+}++function useShortDate() {+ const format = useFormatter();+ return (iso: string) => format.dateTime(new Date(iso), { month: 'short', day: 'numeric' });+}++/** An engine that shares its searches, answered often enough to tell, and shared none. */+export function isSilentEngine(e: FanoutEngineCoverage): boolean {+ return (+ e.answers >= FANOUT_MIN_SILENT_ANSWERS &&+ e.answersWithFanout === 0 &&+ fanoutSharing(e.platform) === 'shares'+ );+}++/**+ * One chip per engine that answered in the window, after "All engines". A+ * chip filters the lists below; an engine that never shares searches has+ * nothing to filter to, so its chip is a label only.+ */+export function FanoutEngineStrip({+ engines,+ totalSubQueries,+ selected,+ onSelect,+}: {+ engines: FanoutEngineCoverage[];+ totalSubQueries: number;+ selected: string | null;+ onSelect: (platform: string | null) => void;+}) {+ const t = useTranslations('prompts.fanout');+ const format = useFormatter();+ const share = useShare();+ const shortDate = useShortDate();++ const chip =+ 'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs whitespace-nowrap';+ const on = 'border-foreground bg-foreground text-background';++ return (+ <div className="flex flex-wrap items-center gap-1.5" role="group" aria-label={t('engines')}>+ <button+ type="button"+ aria-pressed={selected === null}+ onClick={() => onSelect(null)}+ className={cn(chip, selected === null ? on : 'bg-background hover:bg-muted')}+ >+ {t('allEngines')}+ <span className={selected === null ? 'opacity-70' : 'text-muted-foreground'}>+ {format.number(totalSubQueries)}+ </span>+ </button>+ {engines.map((e) => {+ const label = platformLabel(e.platform);+ const avatar = (+ <AIProviderAvatar+ provider={resolveAIProvider(e.platform, e.platform)}+ className="h-4 w-4"+ />+ );+ if (fanoutSharing(e.platform) === 'not-shared' && e.answersWithFanout === 0) {+ return (+ <span+ key={e.platform}+ className={cn(chip, 'border-dashed bg-muted/50 text-muted-foreground')}+ >+ <span className="opacity-50">{avatar}</span>+ {label} · {t('notShared')}+ </span>+ );+ }+ const silent = isSilentEngine(e);+ const isOn = selected === e.platform;+ return (+ <button+ key={e.platform}+ type="button"+ aria-pressed={isOn}+ onClick={() => onSelect(isOn ? null : e.platform)}+ className={cn(+ chip,+ isOn+ ? on+ : silent+ ? 'border-amber-200 bg-amber-50 text-amber-800 hover:bg-amber-100 dark:border-amber-900/50 dark:bg-amber-950/30 dark:text-amber-300'+ : 'bg-background hover:bg-muted',+ )}+ >+ {avatar}+ {label}+ <span className={isOn ? 'opacity-70' : silent ? '' : 'text-muted-foreground'}>+ {silent+ ? e.lastFanoutAt+ ? t('noneSince', { date: shortDate(e.lastFanoutAt) })+ : t('noneInWindow')+ : `${t('share', { percent: share(e.answersWithFanout, e.answers) })} · ${format.number(e.subQueries)}`}+ </span>+ {silent && <AlertTriangle className="h-3 w-3" aria-hidden="true" />}+ </button>+ );+ })}+ </div>+ );+}++/**+ * Says why an engine is missing: one that usually shares its searches and+ * sent none (generic, so it clears itself once they arrive again), and the+ * engines that never share them.+ */+export function FanoutEngineNotices({ engines }: { engines: FanoutEngineCoverage[] }) {+ const t = useTranslations('prompts.fanout');+ const format = useFormatter();+ const shortDate = useShortDate();++ const silent = engines.filter(isSilentEngine);+ const notShared = engines+ .filter((e) => fanoutSharing(e.platform) === 'not-shared' && e.answersWithFanout === 0)+ .map((e) => platformLabel(e.platform));++ if (silent.length === 0 && notShared.length === 0) return null;+ return (+ <div className="space-y-2">+ {silent.map((e) => (+ <div+ key={e.platform}+ className="flex items-start gap-2 rounded-lg border border-amber-200 bg-amber-50 px-3 py-2 text-xs dark:border-amber-900/50 dark:bg-amber-950/30"+ >+ <AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0 text-amber-600 dark:text-amber-500" />+ <p className="text-amber-900 dark:text-amber-200">+ <span className="font-medium">+ {e.lastFanoutAt+ ? t('silentTitle', {+ engine: platformLabel(e.platform),+ date: shortDate(e.lastFanoutAt),+ })+ : t('silentTitleNoDate', { engine: platformLabel(e.platform) })}+ </span>{' '}+ <span className="text-amber-800/80 dark:text-amber-300/80">{t('silentBody')}</span>+ </p>+ </div>+ ))}+ {notShared.length > 0 && (+ <p className="flex items-start gap-1.5 text-xs text-muted-foreground">+ <Info className="mt-0.5 h-3.5 w-3.5 shrink-0" />+ {t('notSharedNote', { engines: format.list(notShared, { type: 'conjunction' }) })}+ </p>+ )}+ </div>+ );+}++/**+ * Which engines answered a prompt in the window, coloured when they shared+ * searches for it and faded when they didn't. Engines sharing one icon+ * (Google's) show once, coloured if any of them shared.+ */+export function PromptEnginesCell({+ platforms,+ fanoutPlatforms,+}: {+ platforms: string[];+ fanoutPlatforms: string[];+}) {+ const byProvider = new Map<string, { labels: string[]; shared: boolean }>();+ for (const platform of platforms) {+ const provider = resolveAIProvider(platform, platform);+ const entry = byProvider.get(provider) ?? { labels: [], shared: false };+ entry.labels.push(platformLabel(platform));+ entry.shared ||= fanoutPlatforms.includes(platform);+ byProvider.set(provider, entry);+ }+ if (byProvider.size === 0) return <span className="text-xs text-muted-foreground">—</span>;+ return (+ <div className="flex items-center gap-1">+ {[...byProvider.entries()]+ .sort(([, a], [, b]) => Number(b.shared) - Number(a.shared))+ .map(([provider, { labels, shared }]) => (+ <span key={provider} className={cn(!shared && 'opacity-25')} title={labels.join(', ')}>+ <AIProviderAvatar+ provider={provider as ReturnType<typeof resolveAIProvider>}+ className="h-5 w-5"+ />+ </span>+ ))}+ </div>+ );+}diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsxindex 007133242..79b7be7b2 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_fanout-tab.tsx@@ -1,6 +1,7 @@'use client';import { Fragment, useCallback, useEffect, useMemo, useRef, useState } from 'react';+import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { Link } from '@/i18n/navigation';import {@@ -29,6 +30,12 @@ import {} from '@/components/ui/table';import { Check, ChevronRight, Plus, Loader2, Search } from 'lucide-react';import { usePagination, TablePager } from '@/components/table-pager';+import {+ FanoutEngineNotices,+ FanoutEngineStrip,+ PromptEnginesCell,+ platformLabel,+} from './_fanout-engines';type View = 'frequency' | 'by-prompt';@@ -39,6 +46,9 @@ interface PromptGroup {totalRuns: number;/** Of those, how many triggered at least one live search. */runsWithFanout: number;+ /** Platforms that answered it, and those whose answers shared searches. */+ platforms: string[];+ fanoutPlatforms: string[];}type QueryFanoutTabProps = {@@ -85,6 +95,8 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFconst [intents, setIntents] = useState<Record<string, string>>({});const [view, setView] = useState<View>('by-prompt');const [searchText, setSearchText] = useState('');+ // The engine chip picked above the lists; null shows every engine.+ const [engine, setEngine] = useState<string | null>(null);// Mirror of `intents` for the async classification chain (avoids stale// closures), plus a run counter so a reload/brand switch/unmount cancels@@ -94,16 +106,19 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFconst filteredSubQueries = useMemo<FanoutSubQuery[]>(() => {if (!data) return [];- if (!searchText) return data.subQueries;const lower = searchText.toLowerCase();- return data.subQueries.filter((sq) => sq.query.toLowerCase().includes(lower));- }, [data, searchText]);+ return data.subQueries.filter(+ (sq) =>+ (!engine || sq.engines.includes(engine)) &&+ (!searchText || sq.query.toLowerCase().includes(lower)),+ );+ }, [data, searchText, engine]);- // Shared pager for the HighFrequencyView — reset whenever brandId, view, or the search term changes.+ // Shared pager for the HighFrequencyView — reset whenever brandId, view, the engine or the search term changes.const pager = usePagination(filteredSubQueries.length,- // resetKey: changing brand, switching away from/back to frequency view, or typing a search term resets to page 0- `${brandId}::${view}::${searchText}`,+ // resetKey: changing brand, switching away from/back to frequency view, picking an engine or typing a search term resets to page 0+ `${brandId}::${view}::${engine}::${searchText}`,FANOUT_PAGE_SIZE,);@@ -154,7 +169,13 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF} catch (err) {console.error('[fanout] load failed', err);toast.error(userErrorMessage(err, 'Failed to load query fan-out — please retry.'));- setData({ subQueries: [], totalObserved: 0, promptCoverage: [], truncated: false });+ setData({+ subQueries: [],+ totalObserved: 0,+ promptCoverage: [],+ engines: [],+ truncated: false,+ });} finally {if (!silent) {setLoading(false);@@ -174,6 +195,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFuseEffect(() => {setSearchText('');+ setEngine(null);}, [brandId, range]);useEffect(() => {@@ -193,13 +215,22 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFsubQueries: [],totalRuns: c.totalRuns,runsWithFanout: c.runsWithFanout,+ platforms: c.platforms,+ fanoutPlatforms: c.fanoutPlatforms,});}for (const sq of data.subQueries) {for (const p of sq.sourcedPrompts) {// Defensive: a sourced prompt should always have a coverage entry.if (!map.has(p.id)) {- map.set(p.id, { prompt: p, subQueries: [], totalRuns: 0, runsWithFanout: 0 });+ map.set(p.id, {+ prompt: p,+ subQueries: [],+ totalRuns: 0,+ runsWithFanout: 0,+ platforms: [],+ fanoutPlatforms: [],+ });}map.get(p.id)!.subQueries.push(sq);}@@ -216,16 +247,26 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF}, [data]);const filteredByPrompt = useMemo<PromptGroup[]>(() => {- if (!searchText) return byPrompt;const lower = searchText.toLowerCase();- return byPrompt.filter((group) => group.prompt.text.toLowerCase().includes(lower));- }, [byPrompt, searchText]);+ const groups = searchText+ ? byPrompt.filter((group) => group.prompt.text.toLowerCase().includes(lower))+ : byPrompt;+ if (!engine) return groups;+ // With an engine picked, a prompt shows that engine's searches only, and+ // a prompt it shared none for drops out.+ return groups+ .map((group) => ({+ ...group,+ subQueries: group.subQueries.filter((sq) => sq.engines.includes(engine)),+ }))+ .filter((group) => group.subQueries.length > 0);+ }, [byPrompt, searchText, engine]);// The By-prompt list now covers every tracked prompt with a run in the// window, not just those with observed fan-out, so it needs its own pager.const byPromptPager = usePagination(filteredByPrompt.length,- `${brandId}::${view}::${searchText}`,+ `${brandId}::${view}::${engine}::${searchText}`,FANOUT_PAGE_SIZE,);@@ -309,6 +350,17 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF</p></CardHeader><CardContent>+ {!loading && data && data.engines.length > 0 && (+ <div className="mb-4 space-y-2.5">+ <FanoutEngineStrip+ engines={data.engines}+ totalSubQueries={data.totalObserved}+ selected={engine}+ onSelect={setEngine}+ />+ <FanoutEngineNotices engines={data.engines} />+ </div>+ )}{loading ? (<div className="space-y-2">{Array.from({ length: 5 }).map((_, i) => (@@ -323,6 +375,8 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFintents={intents}addingKey={addingKey}pager={pager}+ rangeLabel={rangeLabel}+ engine={engine}onTrack={handleTrack}searchText={searchText}onSearchChange={setSearchText}@@ -334,6 +388,7 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryFaddingKey={addingKey}pager={byPromptPager}rangeLabel={rangeLabel}+ engine={engine}onTrack={handleTrack}searchText={searchText}onSearchChange={setSearchText}@@ -351,14 +406,28 @@ export function QueryFanoutTab({ brandId, range, rangeLabel, onTracked }: QueryF}function EmptyState() {+ const t = useTranslations('prompts.fanout');return (<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="text-sm font-medium">{t('emptyTitle')}</p>+ <p className="max-w-md text-xs text-muted-foreground">{t('emptyBody')}</p>+ </div>+ );+}++/** An engine is picked and shared nothing in the window. */+function EngineEmptyState({ engine, rangeLabel }: { engine: string; rangeLabel: string }) {+ const t = useTranslations('prompts.fanout');+ const label = platformLabel(engine);+ return (+ <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">+ {t('engineEmptyTitle', { engine: label, range: rangeLabel })}+ </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.+ {t('engineEmptyBody', { engine: label })}</p></div>);@@ -379,6 +448,8 @@ function HighFrequencyView({intents,addingKey,pager,+ rangeLabel,+ engine,onTrack,searchText,onSearchChange,@@ -387,6 +458,8 @@ function HighFrequencyView({intents: Record<string, string>;addingKey: string | null;pager: ReturnType<typeof usePagination>;+ rangeLabel: string;+ engine: string | null;onTrack: (query: string) => void;searchText: string;onSearchChange: (text: string) => void;@@ -405,6 +478,8 @@ function HighFrequencyView({// no longer gates on that, so this view has to explain it itself.searchText ? (<NoMatches label="No sub-queries match your search" />+ ) : engine ? (+ <EngineEmptyState engine={engine} rangeLabel={rangeLabel} />) : (<EmptyState />)@@ -487,6 +562,7 @@ function ByPromptView({addingKey,pager,rangeLabel,+ engine,onTrack,searchText,onSearchChange,@@ -496,10 +572,12 @@ function ByPromptView({addingKey: string | null;pager: ReturnType<typeof usePagination>;rangeLabel: string;+ engine: string | null;onTrack: (query: string) => void;searchText: string;onSearchChange: (text: string) => void;}) {+ const t = useTranslations('prompts.fanout');const [expanded, setExpanded] = useState<Set<string>>(new Set());const pageRows = groups.slice(pager.start, pager.end);@@ -522,6 +600,8 @@ function ByPromptView({{groups.length === 0 ? (searchText ? (<NoMatches label="No prompts match your search" />+ ) : engine ? (+ <EngineEmptyState engine={engine} rangeLabel={rangeLabel} />) : (<NoMatches label={`No tracked answers in the ${rangeLabel}`} />)@@ -532,110 +612,124 @@ function ByPromptView({<TableRow><TableHead className="w-[28px]" /><TableHead>Prompt</TableHead>+ <TableHead className="w-[150px]" title={t('enginesLegend')}>+ {t('engines')}+ </TableHead><TableHead className="w-[170px] text-right">Answers with fan-out</TableHead><TableHead className="w-[110px] text-right">Sub-queries</TableHead></TableRow></TableHeader><TableBody>- {pageRows.map(({ prompt, subQueries, totalRuns, runsWithFanout }) => {- // Nothing fanned out — there is no panel to open, so the row- // stays inert rather than expanding into an empty box.- const expandable = subQueries.length > 0;- const isOpen = expandable && expanded.has(prompt.id);- return (- <Fragment key={prompt.id}>- <TableRow- className={cn(expandable && 'cursor-pointer select-none')}- onClick={expandable ? () => toggle(prompt.id) : undefined}- >- <TableCell className="pr-0">- {expandable && (- // The whole row is clickable for the mouse, but a- // <tr> can't carry button semantics without breaking- // the table for screen readers — so the toggle itself- // is the real, focusable control.- <button- type="button"- aria-expanded={isOpen}- aria-label={`${isOpen ? 'Hide' : 'Show'} fan-out for "${prompt.text}"`}- className="flex items-center rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"- onClick={(e) => {- e.stopPropagation();- toggle(prompt.id);- }}- >- <ChevronRight- className={cn(- 'h-4 w-4 text-muted-foreground transition-transform duration-150',- isOpen && 'rotate-90',- )}- />- </button>- )}- </TableCell>- <TableCell className="font-medium">{prompt.text}</TableCell>- <TableCell className="text-right">- <FanoutCoverageCell totalRuns={totalRuns} runsWithFanout={runsWithFanout} />- </TableCell>- <TableCell className="text-right">- <Badge variant="secondary" className="tabular-nums text-[10px]">- {subQueries.length}- </Badge>- </TableCell>- </TableRow>- {isOpen && (- <TableRow key={`${prompt.id}-expanded`} className="hover:bg-transparent">- <TableCell />- <TableCell colSpan={3} className="pb-3 pt-0">- <div className="rounded-md border">- <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-[130px] pl-6">Intent</TableHead>- <TableHead className="w-[64px] text-right">Track</TableHead>- </TableRow>- </TableHeader>- <TableBody>- {subQueries.map((sq) => {- const key = sq.query.toLowerCase();- return (- <TableRow key={key} className="align-middle">- <TableCell className="align-middle font-medium">- {sq.query}- </TableCell>- <TableCell className="align-middle">- <PlatformsCell models={sq.engines} />- </TableCell>- <TableCell className="align-middle text-right tabular-nums">- {sq.timesSearched}- </TableCell>- <TableCell className="align-middle pl-6">- <IntentBadge intent={intents[key]} />- </TableCell>- <TableCell className="align-middle text-right">- <TrackCell- sq={sq}- adding={addingKey === key}- onTrack={onTrack}- />- </TableCell>- </TableRow>- );- })}- </TableBody>- </Table>- </div>+ {pageRows.map(+ ({ prompt, subQueries, totalRuns, runsWithFanout, platforms, fanoutPlatforms }) => {+ // Nothing fanned out — there is no panel to open, so the row+ // stays inert rather than expanding into an empty box.+ const expandable = subQueries.length > 0;+ const isOpen = expandable && expanded.has(prompt.id);+ return (+ <Fragment key={prompt.id}>+ <TableRow+ className={cn(expandable && 'cursor-pointer select-none')}+ onClick={expandable ? () => toggle(prompt.id) : undefined}+ >+ <TableCell className="pr-0">+ {expandable && (+ // The whole row is clickable for the mouse, but a+ // <tr> can't carry button semantics without breaking+ // the table for screen readers — so the toggle itself+ // is the real, focusable control.+ <button+ type="button"+ aria-expanded={isOpen}+ aria-label={`${isOpen ? 'Hide' : 'Show'} fan-out for "${prompt.text}"`}+ className="flex items-center rounded-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ onClick={(e) => {+ e.stopPropagation();+ toggle(prompt.id);+ }}+ >+ <ChevronRight+ className={cn(+ 'h-4 w-4 text-muted-foreground transition-transform duration-150',+ isOpen && 'rotate-90',+ )}+ />+ </button>+ )}+ </TableCell>+ <TableCell className="font-medium">{prompt.text}</TableCell>+ <TableCell>+ <PromptEnginesCell+ platforms={platforms}+ fanoutPlatforms={fanoutPlatforms}+ />+ </TableCell>+ <TableCell className="text-right">+ <FanoutCoverageCell+ totalRuns={totalRuns}+ runsWithFanout={runsWithFanout}+ />+ </TableCell>+ <TableCell className="text-right">+ <Badge variant="secondary" className="tabular-nums text-[10px]">+ {subQueries.length}+ </Badge></TableCell></TableRow>- )}- </Fragment>- );- })}+ {isOpen && (+ <TableRow key={`${prompt.id}-expanded`} className="hover:bg-transparent">+ <TableCell />+ <TableCell colSpan={4} className="pb-3 pt-0">+ <div className="rounded-md border">+ <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-[130px] pl-6">Intent</TableHead>+ <TableHead className="w-[64px] text-right">Track</TableHead>+ </TableRow>+ </TableHeader>+ <TableBody>+ {subQueries.map((sq) => {+ const key = sq.query.toLowerCase();+ return (+ <TableRow key={key} className="align-middle">+ <TableCell className="align-middle font-medium">+ {sq.query}+ </TableCell>+ <TableCell className="align-middle">+ <PlatformsCell models={sq.engines} />+ </TableCell>+ <TableCell className="align-middle text-right tabular-nums">+ {sq.timesSearched}+ </TableCell>+ <TableCell className="align-middle pl-6">+ <IntentBadge intent={intents[key]} />+ </TableCell>+ <TableCell className="align-middle text-right">+ <TrackCell+ sq={sq}+ adding={addingKey === key}+ onTrack={onTrack}+ />+ </TableCell>+ </TableRow>+ );+ })}+ </TableBody>+ </Table>+ </div>+ </TableCell>+ </TableRow>+ )}+ </Fragment>+ );+ },+ )}</TableBody></Table><TablePager@@ -737,6 +831,7 @@ function FanoutCoverageCell({totalRuns: number;runsWithFanout: number;}) {+ const t = useTranslations('prompts.fanout');if (totalRuns === 0) return <span className="text-xs text-muted-foreground">—</span>;const pct = (runsWithFanout / totalRuns) * 100;@@ -748,10 +843,7 @@ function FanoutCoverageCell({return (<spanclassName="text-xs text-muted-foreground tabular-nums"- title={- `Of ${totalRuns} tracked answers in this window, ${runsWithFanout} triggered live searches. ` +- 'Most engines never fan out — Copilot and Perplexity are the main sources.'- }+ title={t('coverageTooltip', { total: totalRuns, withFanout: runsWithFanout })}>{runsWithFanout} / {totalRuns} · {label}</span>diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsxindex d4c70e1e0..8fd7b1f5a 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx@@ -343,6 +343,15 @@ const PROMPT_EXPORT_HINT = 'No prompts yet - add prompts first.';// ─── Helpers ──────────────────────────────────────────────────────────────────const VALID_TABS = ['all', 'fanout', 'insights'] as const;++/**+ * The window a tab opens on. Query Fan-out opens on 7 days: one day of+ * answers holds few searches, and an engine that only some answers search+ * with looks absent in it.+ */+function defaultRangeFor(tab: string): PromptRangePreset {+ return tab === 'fanout' ? '7d' : DEFAULT_PROMPT_RANGE_PRESET;+}type TabId = (typeof VALID_TABS)[number];const PROMPT_VIEWS = ['tracked', 'suggestions'] as const;@@ -1312,7 +1321,7 @@ export default function PromptsPage() {// than silently dropping them back to the default.if (isPromptRangePreset(raw)) return raw;if (raw && isPromptRangePreset(`${raw}d`)) return `${raw}d` as PromptRangePreset;- return DEFAULT_PROMPT_RANGE_PRESET;+ return defaultRangeFor(initialTab);})();const [rangePreset, setRangePreset] = useState<PromptRangePreset>(initialRange);// Which tracked location the health columns describe. Empty = every@@ -1356,7 +1365,7 @@ export default function PromptsPage() {// The default range stays out of the URL so shared links keep their// existing shape unless the user actually picked a different window.const want: Record<string, string | null> = {- range: rangePreset === DEFAULT_PROMPT_RANGE_PRESET ? null : rangePreset,+ range: rangePreset === defaultRangeFor(tab) ? null : rangePreset,from: rangePreset === 'custom' && customFrom ? customFrom : null,to: rangePreset === 'custom' && customTo ? customTo : null,region: regionFilter || null,@@ -1771,7 +1780,16 @@ export default function PromptsPage() {</div></div>- <Tabs value={tab} onValueChange={(v) => setTab(v as TabId)}>+ <Tabs+ value={tab}+ onValueChange={(v) => {+ const next = v as TabId;+ // A window still on this tab's default wasn't picked by the user,+ // so it follows the next tab's own (Query Fan-out opens on 7 days).+ if (rangePreset === defaultRangeFor(tab)) setRangePreset(defaultRangeFor(next));+ setTab(next);+ }}+ ><div className="flex items-center justify-between gap-4 flex-wrap"><TabsList><TabsTrigger value="all">Prompts</TabsTrigger>diff --git a/web/src/config/fanout-platforms.ts b/web/src/config/fanout-platforms.tsnew file mode 100644index 000000000..014da0a85--- /dev/null+++ b/web/src/config/fanout-platforms.ts@@ -0,0 +1,47 @@+/**+ * Which tracked platforms can carry observed query fan-out (#332), as our data+ * provider (Cloro) documents it. The Query Fan-out page uses this to tell+ * "this engine shares its searches, but none arrived" (worth flagging) apart+ * from "this engine never shares them" (nothing to wait for). The server's+ * daily health report keeps the same list (server/src/lib/health/report.js).+ */++/** Platforms whose answers come with the searches the engine ran. */+export const FANOUT_SHARING_PLATFORMS: readonly string[] = [+ 'chatgpt-web',+ 'copilot-web',+ 'perplexity-web',+];++/**+ * Platforms whose answers never come with their searches: those our provider+ * documents no fan-out for, and the API models (`claude`, `gemini`, `chatgpt`,+ * see resolveModelPlatform in the tracking worker), whose searches we don't+ * capture.+ */+export const FANOUT_NOT_SHARED_PLATFORMS: readonly string[] = [+ 'google-aio',+ 'google-aimode',+ 'gemini-web',+ 'claude',+ 'gemini',+ 'chatgpt',+];++/**+ * Answers an engine needs in the window before "it shared none" means+ * something. ChatGPT shared searches on about a quarter of its answers, so+ * four answers with none is ordinary chance on a small brand.+ */+export const FANOUT_MIN_SILENT_ANSWERS = 20;++/** The API-model platforms, whose labels match a scraper's ("ChatGPT"). */+export const API_MODEL_PLATFORMS: readonly string[] = ['claude', 'gemini', 'chatgpt'];++export type FanoutSharing = 'shares' | 'not-shared' | 'unknown';++export function fanoutSharing(platform: string): FanoutSharing {+ if (FANOUT_SHARING_PLATFORMS.includes(platform)) return 'shares';+ if (FANOUT_NOT_SHARED_PLATFORMS.includes(platform)) return 'not-shared';+ return 'unknown';+}diff --git a/web/src/lib/actions/fanout.test.ts b/web/src/lib/actions/fanout.test.tsindex f16e8fcc8..948fbb0a8 100644--- a/web/src/lib/actions/fanout.test.ts+++ b/web/src/lib/actions/fanout.test.ts@@ -13,6 +13,8 @@ interface QueryState {eq: Record<string, unknown>;inFilter?: { column: string; values: string[] };range?: [number, number];+ /** The single-row lookup (lastFanoutAt): `.not(…).limit(1).maybeSingle()`. */+ single?: boolean;}const SET_ID = 'set-1';@@ -30,6 +32,8 @@ let rosterRows: PromptRow[] = [];/** Prompts reachable only by id — e.g. moved out of the brand's sets. */let residualRows: PromptRow[] = [];let promptSetRows: { id: string }[] = [];+/** What the last-fan-out lookup finds, per platform. */+let lastFanoutRows: Record<string, string> = {};/** When set, prompt_results always returns a full page (drives truncation). */let alwaysFullPage = false;let residualError: string | null = null;@@ -45,6 +49,11 @@ function resolveQuery(state: QueryState): {return rows.slice(from, to + 1);};+ if (state.table === 'prompt_results' && state.single) {+ const at = lastFanoutRows[state.eq.platform as string];+ return { data: at ? ({ created_at: at } as never) : null, error: null };+ }+if (state.table === 'prompt_results') {if (alwaysFullPage) {const [from, to] = state.range ?? [0, 0];@@ -79,6 +88,13 @@ function fakeQueryBuilder(table: string) {return builder;},gte: () => builder,+ lt: () => builder,+ not: () => builder,+ limit: () => builder,+ maybeSingle: () => {+ state.single = true;+ return builder;+ },order: () => builder,in: (column: string, values: string[]) => {state.inFilter = { column, values };@@ -113,6 +129,7 @@ const q = (query: string) => ({ query, source_platform: 'copilot' });beforeEach(() => {calls = [];+ lastFanoutRows = {};alwaysFullPage = false;residualError = null;promptSetRows = [{ id: SET_ID }];@@ -154,6 +171,8 @@ describe('getQueryFanout — prompt coverage', () => {text: 'How do I track brand mentions?',totalRuns: 4,runsWithFanout: 0,+ platforms: ['copilot'],+ fanoutPlatforms: [],});});@@ -296,3 +315,77 @@ describe('getQueryFanout — window truncation', () => {await expect(getQueryFanout('brand-1')).resolves.toMatchObject({ truncated: true });});});++describe('getQueryFanout — engines', () => {+ it("counts each engine's answers, answers with fan-out and distinct sub-queries", async () => {+ resultRows = [+ answer('p-loud', [{ query: 'aeo tools', source_platform: 'copilot-web' }], 'copilot-web'),+ answer('p-loud', [], 'copilot-web'),+ answer('p-loud', [], 'chatgpt-web'),+ answer('p-loud', [], 'google-aio'),+ ];+ const { getQueryFanout } = await import('./fanout');++ const { engines, promptCoverage } = await getQueryFanout('brand-1');++ expect(engines).toEqual([+ {+ platform: 'copilot-web',+ answers: 2,+ answersWithFanout: 1,+ subQueries: 1,+ lastFanoutAt: null,+ },+ {+ platform: 'chatgpt-web',+ answers: 1,+ answersWithFanout: 0,+ subQueries: 0,+ lastFanoutAt: null,+ },+ {+ platform: 'google-aio',+ answers: 1,+ answersWithFanout: 0,+ subQueries: 0,+ lastFanoutAt: null,+ },+ ]);+ expect(promptCoverage.find((p) => p.id === 'p-loud')).toMatchObject({+ platforms: ['chatgpt-web', 'copilot-web', 'google-aio'],+ fanoutPlatforms: ['copilot-web'],+ });+ });++ it('says when an engine that shares its searches last did, and only for such an engine', async () => {+ resultRows = [+ ...Array.from({ length: 20 }, () => answer('p-loud', [], 'chatgpt-web')),+ ...Array.from({ length: 20 }, () => answer('p-loud', [], 'gemini-web')),+ ];+ lastFanoutRows = {+ 'chatgpt-web': '2026-09-29T05:12:00Z',+ 'gemini-web': '2026-09-01T00:00:00Z',+ };+ const { getQueryFanout } = await import('./fanout');++ const { engines } = await getQueryFanout('brand-1');++ expect(engines.find((e) => e.platform === 'chatgpt-web')?.lastFanoutAt).toBe(+ '2026-09-29T05:12:00Z',+ );+ // Gemini never shares searches, so there is nothing to look back for.+ expect(engines.find((e) => e.platform === 'gemini-web')?.lastFanoutAt).toBeNull();+ expect(calls.filter((c) => c.single).map((c) => c.eq.platform)).toEqual(['chatgpt-web']);+ });++ it('does not look back for an engine with too few answers to tell', async () => {+ resultRows = Array.from({ length: 4 }, () => answer('p-loud', [], 'chatgpt-web'));+ lastFanoutRows = { 'chatgpt-web': '2026-09-29T05:12:00Z' };+ const { getQueryFanout } = await import('./fanout');++ const { engines } = await getQueryFanout('brand-1');++ expect(engines[0]).toMatchObject({ platform: 'chatgpt-web', answers: 4, lastFanoutAt: null });+ expect(calls.filter((c) => c.single)).toHaveLength(0);+ });+});diff --git a/web/src/lib/actions/fanout.ts b/web/src/lib/actions/fanout.tsindex d7b1762d5..4c5fe941a 100644--- a/web/src/lib/actions/fanout.ts+++ b/web/src/lib/actions/fanout.ts@@ -4,6 +4,7 @@ import { revalidatePath } from 'next/cache';import { createClient } from '@/lib/supabase/server';import { addPromptToSet } from '@/lib/actions/prompt';import { API_BASE_URL } from '@/config/api';+import { FANOUT_MIN_SILENT_ANSWERS, FANOUT_SHARING_PLATFORMS } from '@/config/fanout-platforms';/*** Query Fan-out (#333) — read + promote actions over the OBSERVED sub-queries@@ -39,6 +40,28 @@ export interface FanoutPromptCoverage {totalRuns: number;/** Of those, how many contained at least one observed sub-query. */runsWithFanout: number;+ /** Platforms that answered this prompt in the window. */+ platforms: string[];+ /** Of those, the ones whose answers carried fan-out. */+ fanoutPlatforms: string[];+}++/** One platform's fan-out over the window, for the page's engine strip. */+export interface FanoutEngineCoverage {+ /** Platform slug, as in `prompt_results.platform`. */+ platform: string;+ /** Tracked answers from this platform in the window. */+ answers: number;+ /** Of those, how many carried observed fan-out. */+ answersWithFanout: number;+ /** Distinct sub-queries this platform surfaced in the window. */+ subQueries: number;+ /**+ * For a platform that shares its searches (FANOUT_SHARING_PLATFORMS) but+ * had none in the window: when its last one arrived, up to MAX_FANOUT_DAYS+ * back. Null otherwise, or when none arrived in that time either.+ */+ lastFanoutAt: string | null;}export interface QueryFanoutData {@@ -55,6 +78,12 @@ export interface QueryFanoutData {* ranks by sub-query count). Only a stable baseline sort is applied here.*/promptCoverage: FanoutPromptCoverage[];+ /**+ * Per-platform fan-out over the same window, every platform that answered+ * included (those that never share searches too). Ordered by the answers+ * that carried fan-out. Empty for the single-prompt variant.+ */+ engines: FanoutEngineCoverage[];/*** True when the window held more answers than `FANOUT_MAX_ROWS` and the read* stopped early. Rows come back oldest-first, so it's the MOST RECENT answers@@ -242,18 +271,37 @@ export async function getQueryFanout(interface CoverageAcc {totalRuns: number;runsWithFanout: number;+ platforms: Set<string>;+ fanoutPlatforms: Set<string>;}const coverageByPrompt = new Map<string, CoverageAcc>();+ // The same per answer, by the platform that answered.+ const byEngine = new Map<string, { answers: number; answersWithFanout: number }>();for (const row of rows) {let coverage: CoverageAcc | undefined;if (row.prompt_id) {coverage = coverageByPrompt.get(row.prompt_id);if (!coverage) {- coverage = { totalRuns: 0, runsWithFanout: 0 };+ coverage = {+ totalRuns: 0,+ runsWithFanout: 0,+ platforms: new Set(),+ fanoutPlatforms: new Set(),+ };coverageByPrompt.set(row.prompt_id, coverage);}coverage.totalRuns += 1;+ if (row.platform) coverage.platforms.add(row.platform);+ }+ let engine: { answers: number; answersWithFanout: number } | undefined;+ if (row.platform) {+ engine = byEngine.get(row.platform);+ if (!engine) {+ engine = { answers: 0, answersWithFanout: 0 };+ byEngine.set(row.platform, engine);+ }+ engine.answers += 1;}const items = Array.isArray(row.search_queries)@@ -287,14 +335,24 @@ export async function getQueryFanout(}// `seenInRow` is only written to past the validity guard above, so a// non-empty set means this answer contributed at least one real sub-query.- if (coverage && seenInRow.size > 0) coverage.runsWithFanout += 1;+ if (seenInRow.size > 0) {+ if (coverage) {+ coverage.runsWithFanout += 1;+ if (row.platform) coverage.fanoutPlatforms.add(row.platform);+ }+ if (engine) engine.answersWithFanout += 1;+ }}if (byQuery.size === 0 && coverageByPrompt.size === 0) {- return { subQueries: [], totalObserved: 0, promptCoverage: [], truncated };+ return { subQueries: [], totalObserved: 0, promptCoverage: [], engines: [], truncated };}- const roster = await fetchBrandPromptRoster(supabase, brandId);+ // Independent reads: the last-fan-out lookups overlap the roster's.+ const [engines, roster] = await Promise.all([+ engineCoverage(supabase, brandId, since, byEngine, byQuery),+ fetchBrandPromptRoster(supabase, brandId),+ ]);// Prompt text for every prompt with a run in the window — a superset of the// fan-out-sourced prompts, since coverage reports the zero rows too. Paused@@ -353,11 +411,75 @@ export async function getQueryFanout(text: promptTextById.get(id) ?? '',totalRuns: acc.totalRuns,runsWithFanout: acc.runsWithFanout,+ platforms: [...acc.platforms].sort(),+ fanoutPlatforms: [...acc.fanoutPlatforms].sort(),})).filter((p) => p.text).sort((a, b) => a.text.localeCompare(b.text));- return { subQueries, totalObserved: subQueries.length, promptCoverage, truncated };+ return { subQueries, totalObserved: subQueries.length, promptCoverage, engines, truncated };+}++/**+ * The engine strip's numbers. For a platform that shares its searches but+ * had none in the window, also when its last ones arrived: ChatGPT's stopped+ * on 2026-09-30, and "none since Sep 30" says far more than "0%".+ */+async function engineCoverage(+ supabase: Awaited<ReturnType<typeof createClient>>,+ brandId: string,+ since: string,+ byEngine: Map<string, { answers: number; answersWithFanout: number }>,+ byQuery: Map<string, { engines: Set<string> }>,+): Promise<FanoutEngineCoverage[]> {+ const subQueriesByEngine = new Map<string, number>();+ for (const acc of byQuery.values()) {+ for (const engine of acc.engines) {+ subQueriesByEngine.set(engine, (subQueriesByEngine.get(engine) ?? 0) + 1);+ }+ }++ const earliest = new Date(Date.now() - MAX_FANOUT_DAYS * 86_400_000).toISOString();+ const silent = [...byEngine.entries()]+ .filter(+ ([platform, e]) =>+ e.answers >= FANOUT_MIN_SILENT_ANSWERS &&+ e.answersWithFanout === 0 &&+ FANOUT_SHARING_PLATFORMS.includes(platform),+ )+ .map(([platform]) => platform);+ const lastFanoutAt = new Map<string, string | null>();+ await Promise.all(+ silent.map(async (platform) => {+ // `search_queries->0` exists only on a non-empty array, which PostgREST+ // can test; comparing the jsonb to '[]' it can't do reliably.+ const { data, error } = await supabase+ .from('prompt_results')+ .select('created_at')+ .eq('brand_id', brandId)+ .eq('platform', platform)+ .gte('created_at', earliest)+ .lt('created_at', since)+ .not('search_queries->0', 'is', null)+ .order('created_at', { ascending: false })+ .limit(1)+ .maybeSingle();+ // The date is a nicety on top of the counts; never fail the page for it.+ lastFanoutAt.set(platform, error ? null : ((data?.created_at as string | undefined) ?? null));+ }),+ );++ return [...byEngine.entries()]+ .map(([platform, e]) => ({+ platform,+ answers: e.answers,+ answersWithFanout: e.answersWithFanout,+ subQueries: subQueriesByEngine.get(platform) ?? 0,+ lastFanoutAt: lastFanoutAt.get(platform) ?? null,+ }))+ .sort(+ (a, b) => b.answersWithFanout - a.answersWithFanout || a.platform.localeCompare(b.platform),+ );}/**@@ -497,7 +619,7 @@ export async function getPromptFanout(// `promptCoverage` stays empty here: this variant answers for a single prompt// and has no prompt roster to report coverage over.if (byQuery.size === 0) {- return { subQueries: [], totalObserved: 0, promptCoverage: [], truncated };+ return { subQueries: [], totalObserved: 0, promptCoverage: [], engines: [], truncated };}const subQueries: FanoutSubQuery[] = [...byQuery.entries()]@@ -511,5 +633,11 @@ export async function getPromptFanout(})).sort((a, b) => b.timesSearched - a.timesSearched || a.query.localeCompare(b.query));- return { subQueries, totalObserved: subQueries.length, promptCoverage: [], truncated };+ return {+ subQueries,+ totalObserved: subQueries.length,+ promptCoverage: [],+ engines: [],+ truncated,+ };}