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): give suggestions their own tab and show what feeds them (#727)

Gökhan Geyikb864595ee55a
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index 63adaf214..4f77d35d0 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -71,6 +71,28 @@ function notConfigured(res, provider) {
.json({ error: `${PROVIDERS[provider].label} integration is not configured.` });
}
+/**
+ * GET /api/integrations/config
+ *
+ * Which integrations this deployment has credentials for. Env only — no
+ * Composio round trip — so a surface can decide what to offer without paying
+ * ~450ms per provider to ask whether a flow even exists.
+ *
+ * Declared before the `:provider` routes below, which would otherwise claim
+ * this path. DataForSEO is included although it is not a Composio provider
+ * and has no connect flow: it is our own key, enriching Search Console
+ * candidates with competition and volume data, and a surface saying "enabled"
+ * should be able to check rather than assume. Booleans only, never the
+ * credentials themselves.
+ */
+router.get('/config', async (_req, res) => {
+ return res.json({
+ googleSearchConsole: isComposioConfigured(GSC),
+ googleAnalytics: isComposioConfigured(GA),
+ dataForSeo: Boolean(process.env.DATAFORSEO_LOGIN && process.env.DATAFORSEO_PASSWORD),
+ });
+});
+
// ─── Shared connect / status / disconnect ────────────────────────────────────
// Identical for every OAuth provider; only the auth config differs, which
// lives in the PROVIDERS map.
diff --git a/web/public/dataforseo.svg b/web/public/dataforseo.svg
new file mode 100644
index 000000000..8dcd163ca
--- /dev/null
+++ b/web/public/dataforseo.svg
@@ -0,0 +1,75 @@
+<?xml version="1.0" encoding="UTF-8" standalone="no"?>
+<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
+<svg xmlns="http://www.w3.org/2000/svg" version="1.1" viewBox="0.00 0.00 192.00 192.00" width="128" height="128">
+<g stroke-width="2.00" fill="none" stroke-linecap="butt">
+<path stroke="#8e7f4f" vector-effect="non-scaling-stroke" d="
+ M 192.00 96.08
+ L 157.06 96.11"
+/>
+<path stroke="#8e7f4f" vector-effect="non-scaling-stroke" d="
+ M 34.70 96.12
+ L 0.00 96.11"
+/>
+<path stroke="#8e7f4f" vector-effect="non-scaling-stroke" d="
+ M 134.51 96.14
+ L 57.23 96.13"
+/>
+</g>
+<path fill="#202d9e" d="
+ M 105.16 0.00
+ Q 138.26 3.67 161.60 25.65
+ Q 189.32 51.75 192.00 90.91
+ L 192.00 96.08
+ L 157.06 96.11
+ Q 156.64 73.59 142.89 57.37
+ C 120.54 31.02 81.11 27.63 55.07 50.99
+ C 42.22 62.51 34.91 78.64 34.70 96.12
+ L 0.00 96.11
+ L 0.00 87.01
+ C 5.09 40.49 40.08 5.12 86.66 0.00
+ L 105.16 0.00
+ Z"
+/>
+<path fill="#202d9e" d="
+ M 134.51 96.14
+ L 57.23 96.13
+ A 38.63 38.56 61.4 0 1 63.38 75.12
+ A 38.64 38.61 -73.3 0 1 96.26 57.39
+ A 38.64 38.63 75.8 0 1 129.67 77.32
+ A 38.72 38.68 -59.4 0 1 134.51 96.14
+ Z"
+/>
+<path fill="#fbd000" d="
+ M 192.00 96.08
+ L 192.00 100.72
+ Q 189.90 133.19 169.27 158.01
+ A 0.43 0.43 0.0 0 1 168.63 158.03
+ L 145.20 133.42
+ A 0.43 0.43 0.0 0 1 145.16 132.87
+ Q 157.02 116.45 157.06 96.11
+ L 192.00 96.08
+ Z"
+/>
+<path fill="#fbd000" d="
+ M 34.70 96.12
+ C 34.44 141.71 81.26 170.70 122.33 151.79
+ A 1.15 1.15 0.0 0 1 123.65 152.04
+ L 147.01 176.58
+ A 0.54 0.53 -37.7 0 1 146.90 177.40
+ Q 125.99 190.37 101.09 192.00
+ L 90.64 192.00
+ C 42.25 188.68 5.19 152.65 0.00 104.51
+ L 0.00 96.11
+ L 34.70 96.12
+ Z"
+/>
+<path fill="#fbd000" d="
+ M 134.51 96.14
+ A 38.65 38.64 -22.7 0 1 123.51 123.02
+ A 38.64 38.62 -62.2 0 1 88.28 133.92
+ A 38.67 38.65 -8.0 0 1 61.53 113.74
+ A 38.61 38.52 31.3 0 1 57.23 96.13
+ L 134.51 96.14
+ Z"
+/>
+</svg>
\ No newline at end of file
diff --git a/web/public/google-analytics.svg b/web/public/google-analytics.svg
new file mode 100644
index 000000000..ee6b97012
--- /dev/null
+++ b/web/public/google-analytics.svg
@@ -0,0 +1,12 @@
+<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_300_10492)">
+<path d="M88.4666 15.1692V111.169C88.4666 121.911 95.8848 127.896 103.739 127.896C111.012 127.896 119.012 122.805 119.012 111.169V15.8965C119.012 6.04921 111.739 -0.103516 103.739 -0.103516C95.7393 -0.103516 88.4666 6.68193 88.4666 15.1692Z" fill="#F9AB00"/>
+<path d="M48.4661 63.8958V111.168C48.4661 121.91 55.8843 127.896 63.7389 127.896C71.0116 127.896 79.0117 122.805 79.0117 111.168V64.623C79.0117 54.7758 71.7389 48.623 63.7389 48.623C55.7388 48.623 48.4661 55.4085 48.4661 63.8958Z" fill="#E37400"/>
+<path d="M23.7389 127.895C32.1738 127.895 39.0117 121.057 39.0117 112.622C39.0117 104.187 32.1738 97.3496 23.7389 97.3496C15.3039 97.3496 8.46606 104.187 8.46606 112.622C8.46606 121.057 15.3039 127.895 23.7389 127.895Z" fill="#E37400"/>
+</g>
+<defs>
+<clipPath id="clip0_300_10492">
+<rect width="128" height="128" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/public/google-search-console.svg b/web/public/google-search-console.svg
new file mode 100644
index 000000000..1dba7fe84
--- /dev/null
+++ b/web/public/google-search-console.svg
@@ -0,0 +1,20 @@
+<svg width="128" height="128" viewBox="0 0 128 128" fill="none" xmlns="http://www.w3.org/2000/svg">
+<g clip-path="url(#clip0_300_10544)">
+<mask id="mask0_300_10544" style="mask-type:luminance" maskUnits="userSpaceOnUse" x="0" y="-1" width="129" height="129">
+<path d="M0.265625 -0.103516H128.266V127.896H0.265625V-0.103516Z" fill="white"/>
+</mask>
+<g mask="url(#mask0_300_10544)">
+<path d="M35.7248 97.5832L20.6208 112.69C20.0612 113.248 19.3035 113.561 18.5136 113.561C17.7237 113.561 16.966 113.248 16.4064 112.69L15.472 111.756C14.9154 111.197 14.603 110.439 14.603 109.65C14.603 108.861 14.9154 108.104 15.472 107.545L30.576 92.4376C31.1357 91.8791 31.8941 91.5654 32.6848 91.5654C33.4754 91.5654 34.2338 91.8791 34.7936 92.4376L35.7248 93.3688C36.002 93.6452 36.2219 93.9736 36.372 94.3352C36.522 94.6968 36.5993 95.0845 36.5993 95.476C36.5993 95.8675 36.522 96.2551 36.372 96.6167C36.2219 96.9783 36.002 97.3067 35.7248 97.5832Z" fill="#FBBC04"/>
+<path d="M76.2656 103.896H95.6C98.139 103.896 100.653 103.397 102.999 102.425C105.345 101.454 107.476 100.029 109.271 98.2339C111.067 96.4384 112.49 94.3068 113.461 91.9609C114.433 89.6149 114.932 87.1007 114.931 84.5617V32.5617C114.932 30.0229 114.432 27.509 113.461 25.1634C112.489 22.8179 111.065 20.6867 109.27 18.8915C107.475 17.0964 105.344 15.6724 102.998 14.7011C100.653 13.7298 98.1388 13.23 95.6 13.2305C93.061 13.2296 90.5467 13.729 88.2008 14.7002C85.8549 15.6713 83.7233 17.0952 81.9278 18.8904C80.1323 20.6856 78.7081 22.8169 77.7366 25.1627C76.765 27.5085 76.2652 30.0227 76.2656 32.5617V103.896Z" fill="#4285F4"/>
+<path d="M44.2656 103.896C46.8048 103.897 49.3194 103.397 51.6655 102.426C54.0116 101.455 56.1434 100.031 57.9389 98.235C59.7344 96.4395 61.1586 94.3078 62.1299 91.9616C63.1013 89.6155 63.6008 87.1009 63.5999 84.5617C63.6004 82.0227 63.1005 79.5085 62.129 77.1627C61.1575 74.8169 59.7333 72.6856 57.9378 70.8904C56.1423 69.0952 54.0107 67.6713 51.6648 66.7002C49.3188 65.729 46.8045 65.2296 44.2656 65.2305C41.7266 65.2296 39.2123 65.729 36.8663 66.7002C34.5204 67.6713 32.3888 69.0952 30.5933 70.8904C28.7978 72.6856 27.3736 74.8169 26.4021 77.1627C25.4306 79.5085 24.9307 82.0227 24.9312 84.5617C24.9303 87.1009 25.4298 89.6155 26.4012 91.9616C27.3725 94.3078 28.7967 96.4395 30.5922 98.235C32.3877 100.031 34.5195 101.455 36.8656 102.426C39.2117 103.397 41.7263 103.897 44.2656 103.896Z" fill="#FBBC04"/>
+<path d="M89.7697 103.896H70.9313C68.3923 103.897 65.8781 103.397 63.5323 102.426C61.1866 101.454 59.0552 100.03 57.26 98.2343C55.4648 96.4388 54.041 94.3072 53.0698 91.9613C52.0987 89.6154 51.5993 87.1011 51.6001 84.5621V59.2309C51.5993 56.6919 52.0987 54.1776 53.0698 51.8317C54.041 49.4857 55.4648 47.3541 57.26 45.5587C59.0552 43.7632 61.1866 42.339 63.5323 41.3674C65.8781 40.3959 68.3923 39.8961 70.9313 39.8965C73.4706 39.8956 75.9851 40.3952 78.3313 41.3665C80.6774 42.3379 82.8091 43.762 84.6047 45.5575C86.4002 47.3531 87.8243 49.4848 88.7957 51.8309C89.767 54.1771 90.2665 56.6916 90.2657 59.2309V103.404C90.2657 103.534 90.2138 103.66 90.1214 103.752C90.0289 103.845 89.9036 103.896 89.7729 103.896H89.7697Z" fill="#34A853"/>
+<path d="M90.2656 103.405V59.2318C90.2653 55.0346 88.8991 50.9514 86.3735 47.5991C83.8479 44.2468 80.2999 41.8074 76.2656 40.6494V103.897H89.7696C89.8346 103.898 89.899 103.885 89.9592 103.861C90.0194 103.836 90.0741 103.8 90.1202 103.754C90.1663 103.708 90.2028 103.654 90.2278 103.594C90.2528 103.534 90.2656 103.47 90.2656 103.405Z" fill="#1967D2"/>
+<path d="M63.6001 84.9378C63.6007 81.1019 62.4599 77.3527 60.323 74.1672C58.186 70.9817 55.1496 68.5041 51.6001 67.0498V84.9378C51.6001 90.4418 53.9041 95.4114 57.6001 98.9314C59.4979 97.1285 61.0087 94.9579 62.0402 92.5521C63.0718 90.1462 63.6025 87.5555 63.6001 84.9378Z" fill="#EA4335"/>
+</g>
+</g>
+<defs>
+<clipPath id="clip0_300_10544">
+<rect width="128" height="128" fill="white"/>
+</clipPath>
+</defs>
+</svg>
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
index 93c9d06a2..045a93347 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/insights/page.tsx
@@ -669,7 +669,7 @@ function NoDataForPeriod({ datePreset, onReset }: { datePreset: DatePreset; onRe
* card expands + scrolls itself for this hash; the prompt-suggestions card
* lives on the Prompts page's default All Prompts tab and does the same. */
const TOPIC_OPPORTUNITIES_HREF = '/dashboard/topics#topic-opportunities';
-const PROMPT_OPPORTUNITIES_HREF = '/dashboard/prompts#prompt-opportunities';
+const PROMPT_OPPORTUNITIES_HREF = '/dashboard/prompts?tab=suggestions';
function RecommendationCard({
title,
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx
new file mode 100644
index 000000000..1d582060e
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_data-sources-panel.tsx
@@ -0,0 +1,226 @@
+'use client';
+
+import { useCallback, useEffect, useState } from 'react';
+import { Link } from '@/i18n/navigation';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { BarChart3, Check, ExternalLink, Lock, Radar, Search, Sparkles, X } from 'lucide-react';
+import { getSuggestionSourceStates } from '@/lib/actions/integrations';
+
+/**
+ * What feeds this brand's suggestions, and what could (#659).
+ *
+ * Suggestions are measurably better when mined from the brand's own data —
+ * real Search Console demand and real Analytics behaviour instead of modelled
+ * guesses — but the connect flow lives in Settings, where nobody stumbles onto
+ * it from here. This is the same flow, surfaced where the benefit is visible.
+ *
+ * A source only counts as connected when the org is linked AND this brand is
+ * mapped to a property. Connected-but-unmapped silently produces nothing, so
+ * it gets its own wording rather than a tick.
+ */
+
+type SourceState = 'not_configured' | 'not_connected' | 'connected_unmapped' | 'feeding';
+
+interface Source {
+ key: string;
+ name: string;
+ blurb: string;
+ /** Official mark under web/public. Falls back to `icon` when absent. */
+ logo: string;
+ icon: typeof Search;
+ iconClass: string;
+ state: SourceState;
+ /**
+ * False for sources the customer does not connect themselves. DataForSEO is
+ * our own key — it powers keyword and competition data for everyone on the
+ * plan, so it has a state to report but nothing to click.
+ */
+ connectable: boolean;
+}
+
+const SETTINGS_HREF = '/dashboard/settings?tab=integrations';
+
+/** Remembered across visits: a dismissed panel should stay dismissed. */
+const DISMISSED_KEY = 'aeo:suggestion-sources-dismissed';
+
+/**
+ * The provider's own mark, falling back to a generic icon.
+ *
+ * Rendered as an <img> against web/public rather than inlined, matching how
+ * platform logos already work here — and the fallback means a deployment
+ * missing the asset shows a sensible icon instead of a broken image.
+ */
+function SourceMark({ source }: { source: Source }) {
+ const [failed, setFailed] = useState(false);
+ const Icon = source.icon;
+
+ if (failed) return <Icon className={`h-4 w-4 shrink-0 ${source.iconClass}`} />;
+ return (
+ // eslint-disable-next-line @next/next/no-img-element
+ <img
+ src={source.logo}
+ alt=""
+ aria-hidden="true"
+ className="h-4 w-4 shrink-0 object-contain"
+ onError={() => setFailed(true)}
+ />
+ );
+}
+
+export function DataSourcesPanel({ brandId }: { brandId: string }) {
+ const [sources, setSources] = useState<Source[] | null>(null);
+ // Read during the initial render rather than from an effect: setting it in
+ // an effect dismisses on a second pass, so a previously hidden panel flashes
+ // into view before disappearing again.
+ const [dismissed, setDismissed] = useState(() => {
+ if (typeof window === 'undefined') return false;
+ try {
+ return localStorage.getItem(DISMISSED_KEY) === '1';
+ } catch {
+ return false;
+ }
+ });
+
+ useEffect(() => {
+ let cancelled = false;
+
+ getSuggestionSourceStates(brandId)
+ .then((states) => {
+ if (cancelled) return;
+ const stateOf = (s: { configured: boolean; connected: boolean; mapped: boolean }) =>
+ !s.configured
+ ? ('not_configured' as const)
+ : !s.connected
+ ? ('not_connected' as const)
+ : s.mapped
+ ? ('feeding' as const)
+ : ('connected_unmapped' as const);
+ const gsc = stateOf(states.gsc);
+ const ga = stateOf(states.ga);
+ const dataForSeo = states.dataForSeo.configured;
+ setSources([
+ {
+ key: 'gsc',
+ name: 'Google Search Console',
+ blurb: 'See query and impression data to find high-opportunity prompts.',
+ logo: '/google-search-console.svg',
+ icon: Search,
+ iconClass: 'text-blue-500',
+ state: gsc,
+ connectable: true,
+ },
+ {
+ key: 'ga',
+ name: 'Google Analytics (GA4)',
+ blurb: 'Understand user intent and behaviour to uncover relevant prompts.',
+ logo: '/google-analytics.svg',
+ icon: BarChart3,
+ iconClass: 'text-amber-500',
+ state: ga,
+ connectable: true,
+ },
+ {
+ key: 'dataforseo',
+ name: 'DataForSEO',
+ blurb: 'Uncover keyword and SERP data to find content gaps.',
+ logo: '/dataforseo.svg',
+ icon: Radar,
+ iconClass: 'text-violet-500',
+ state: dataForSeo ? 'feeding' : 'not_configured',
+ connectable: false,
+ },
+ ]);
+ })
+ .catch(() => {
+ // Best effort: a status failure must never delay or break the
+ // suggestions themselves, so the panel simply stays hidden.
+ if (!cancelled) setSources([]);
+ });
+
+ return () => {
+ cancelled = true;
+ };
+ }, [brandId]);
+
+ const dismiss = useCallback(() => {
+ setDismissed(true);
+ try {
+ localStorage.setItem(DISMISSED_KEY, '1');
+ } catch {
+ // Preference just won't persist.
+ }
+ }, []);
+
+ if (dismissed || sources === null) return null;
+
+ // A source the deployment has no credentials for is dropped rather than
+ // shown as unavailable: on a self-host without them there is no flow to
+ // complete, and offering one would be a dead end.
+ const visible = sources.filter((s) => s.state !== 'not_configured');
+ if (visible.length === 0) return null;
+
+ // The panel stays put once everything is connected. It is the standing
+ // answer to "what is behind these suggestions", not a prompt to act, and a
+ // reader who connected a source last month should still be able to see that
+ // it is the one doing the work. Dismissing it is the way to hide it.
+
+ return (
+ <div className="relative rounded-lg border bg-muted/20 p-4">
+ <button
+ type="button"
+ onClick={dismiss}
+ aria-label="Hide data sources"
+ className="absolute right-3 top-3 rounded-sm text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
+ >
+ <X className="h-4 w-4" />
+ </button>
+
+ <div className="grid gap-4 lg:grid-cols-[minmax(0,17rem)_1fr]">
+ <div className="flex gap-3 pr-6">
+ <span className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-primary/10">
+ <Sparkles className="h-4 w-4 text-primary" />
+ </span>
+ <div className="space-y-2">
+ <p className="text-sm font-medium leading-snug">Enable smarter prompt suggestions</p>
+ <p className="text-xs text-muted-foreground leading-relaxed">
+ Connect your data sources to surface the most valuable prompt opportunities.
+ </p>
+ <Link href={SETTINGS_HREF} className={buttonVariants({ size: 'sm' })}>
+ Connect data sources
+ </Link>
+ <p className="flex items-center gap-1.5 pt-1 text-[11px] text-muted-foreground">
+ <Lock className="h-3 w-3" />
+ Your data is secure and never shared.
+ </p>
+ </div>
+ </div>
+
+ <div className="grid gap-3 sm:grid-cols-2 xl:grid-cols-3">
+ {visible.map((source) => (
+ <div key={source.key} className="flex flex-col gap-2 rounded-lg border bg-card p-3">
+ <div className="flex items-center gap-2">
+ <SourceMark source={source} />
+ <span className="text-sm font-medium">{source.name}</span>
+ </div>
+ <p className="flex-1 text-xs text-muted-foreground leading-relaxed">{source.blurb}</p>
+ {source.state === 'feeding' ? (
+ <span className="flex items-center gap-1.5 text-xs font-medium text-green-600 dark:text-green-400">
+ <Check className="h-3.5 w-3.5" />
+ {source.connectable ? 'Connected' : 'Enabled'}
+ </span>
+ ) : !source.connectable ? null : (
+ <Link
+ href={SETTINGS_HREF}
+ className={`${buttonVariants({ variant: 'outline', size: 'sm' })} gap-1.5`}
+ >
+ {source.state === 'connected_unmapped' ? 'Map property' : 'Connect'}
+ <ExternalLink className="h-3 w-3" />
+ </Link>
+ )}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
index c21b86426..99448ba9d 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/_suggestions-card.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useEffect, useState, useCallback, useTransition, useRef } from 'react';
+import { useEffect, useState, useCallback, useMemo, useTransition, useRef } from 'react';
import { createPortal } from 'react-dom';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
@@ -13,14 +13,23 @@ import {
Loader2,
TrendingUp,
Tag,
- Info,
- ChevronDown,
- ChevronRight,
AlertTriangle,
SearchCheck,
+ Shield,
+ Radar,
+ Search as SearchIcon,
+ Trash2,
BarChart3,
- Sparkle,
} from 'lucide-react';
+import { Filter } from 'lucide-react';
+import { Input } from '@/components/ui/input';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
import { toast } from 'sonner';
import {
getPromptSuggestions,
@@ -122,14 +131,79 @@ function HoverTip({ content, children }: { content: string; children: React.Reac
);
}
+/**
+ * Where a suggestion came from, as badges (#659).
+ *
+ * Every suggestion is phrased by our own generation step, so `Ansvisor Agents`
+ * is always present; a data source badge joins it when the suggestion was
+ * mined from the brand's own Search Console or Analytics rather than from the
+ * model alone. Two badges is the honest reading — the data and the phrasing
+ * come from different places.
+ */
+function SourceBadges({ suggestion }: { suggestion: PromptSuggestion }) {
+ const gsc = gscSourceData(suggestion);
+ const ga = gaSourceData(suggestion);
+
+ return (
+ <div className="flex flex-wrap items-center gap-1.5">
+ {gsc && (
+ <HoverTip
+ content={`From your Google Search Console data — the query "${gsc.query}" got ${gsc.impressions.toLocaleString()} impressions in the last 28 days.`}
+ >
+ <Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
+ <SearchCheck className="h-3.5 w-3.5 text-blue-500" />
+ Google Search Console
+ </Badge>
+ </HoverTip>
+ )}
+ {/* Only when the row actually carries DataForSEO's contribution: the
+ competition index it returned for that query. A badge on a row it
+ never touched would be decoration claiming to be provenance. */}
+ {gsc?.competitionIndex != null && (
+ <HoverTip
+ content={`DataForSEO scored advertiser competition for this query at ${gsc.competitionIndex}/100.`}
+ >
+ <Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
+ <Radar className="h-3.5 w-3.5 text-violet-500" />
+ DataForSEO
+ </Badge>
+ </HoverTip>
+ )}
+ {ga && (
+ <HoverTip
+ content={`From your Google Analytics — derived from ${ga.pageTitle ? `"${ga.pageTitle}" (${ga.landingPage})` : ga.landingPage}, read from the page itself rather than from its URL or product name.`}
+ >
+ <Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
+ <BarChart3 className="h-3.5 w-3.5 text-amber-500" />
+ Google Analytics (GA4)
+ </Badge>
+ </HoverTip>
+ )}
+ <HoverTip content="Phrased by Ansvisor from your brand, the prompts you already track, and the competitors cited in your AI answers.">
+ <Badge variant="outline" className="gap-1.5 bg-card text-xs font-normal">
+ <Shield className="h-3.5 w-3.5 text-muted-foreground" />
+ Ansvisor Agents
+ </Badge>
+ </HoverTip>
+ </div>
+ );
+}
+
+/** Which data source a row carries, for the source filter. */
+type SourceFilter = 'all' | 'gsc' | 'ga' | 'agents';
+
+const SOURCE_FILTER_LABELS: Record<SourceFilter, string> = {
+ all: 'All sources',
+ gsc: 'Google Search Console',
+ ga: 'Google Analytics (GA4)',
+ agents: 'Ansvisor Agents only',
+};
+
interface Props {
brandId: string;
onAccepted?: () => void;
}
-/** localStorage key remembering whether the card is expanded across visits. */
-const EXPANDED_KEY = 'aeo:prompt-suggestions-expanded';
-
export function SuggestionsCard({ brandId, onAccepted }: Props) {
const [suggestions, setSuggestions] = useState<PromptSuggestion[]>([]);
const [loading, setLoading] = useState(false);
@@ -137,39 +211,11 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
const [error, setError] = useState<string | null>(null);
const [refreshing, setRefreshing] = useState(false);
const [pendingId, setPendingId] = useState<string | null>(null);
- // Collapsed by default so the card is a one-line strip and the prompt table
- // stays above the fold; the user's last choice is remembered. Starts false
- // on both server and client (no hydration mismatch), then the effect below
- // restores the stored preference.
- const [expanded, setExpanded] = useState(false);
+ const [sourceFilter, setSourceFilter] = useState<SourceFilter>('all');
+ const [search, setSearch] = useState('');
+ const [clearing, setClearing] = useState(false);
const [, startTransition] = useTransition();
- useEffect(() => {
- try {
- if (localStorage.getItem(EXPANDED_KEY) === '1') setExpanded(true);
- } catch {
- // Storage unavailable (private mode) — stay collapsed.
- }
- if (window.location.hash === '#prompt-opportunities') {
- // Deep links mean "show me the suggestions" — expand (without touching
- // the stored preference) and scroll the card into view.
- setExpanded(true);
- document.getElementById('prompt-opportunities')?.scrollIntoView();
- }
- }, []);
-
- const toggleExpanded = () => {
- setExpanded((prev) => {
- const next = !prev;
- try {
- localStorage.setItem(EXPANDED_KEY, next ? '1' : '0');
- } catch {
- // Preference just won't persist.
- }
- return next;
- });
- };
-
const load = useCallback(async () => {
setLoading(true);
setError(null);
@@ -186,24 +232,21 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
}
}, [brandId]);
- // Fetch ONLY once the card is actually expanded — never on page load. The
- // collapsed strip must not fire a server action: when this card moved to
- // the All Prompts tab its mount-time call became the FIRST action in
- // Next's serialized queue and every hiccup in it stalled the prompt
- // table's own data fetch behind it (the "table spins forever" bug). While
- // collapsed the card costs zero requests, exactly like before the move.
useEffect(() => {
setLoaded(false);
setSuggestions([]);
setError(null);
}, [brandId]);
+ // Fetching on mount is safe here because this component only mounts when
+ // the Suggestions tab is open — the tab click is the user asking for it.
+ // It must not move back above a tab boundary: as an always-mounted card its
+ // request became the first entry in Next's serialised server-action queue,
+ // and every hiccup in it stalled the prompt table's own fetch behind it.
useEffect(() => {
- if (expanded && !loaded && !loading) {
- load();
- }
+ if (!loaded && !loading) load();
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [expanded, loaded, brandId]);
+ }, [loaded, brandId]);
const handleRefresh = async () => {
setRefreshing(true);
@@ -220,6 +263,45 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
}
};
+ const visible = useMemo(() => {
+ const q = search.trim().toLowerCase();
+ return suggestions.filter((s) => {
+ if (sourceFilter === 'gsc' && !gscSourceData(s)) return false;
+ if (sourceFilter === 'ga' && !gaSourceData(s)) return false;
+ if (sourceFilter === 'agents' && (gscSourceData(s) || gaSourceData(s))) return false;
+ if (!q) return true;
+ return (
+ s.suggestedText.toLowerCase().includes(q) ||
+ (s.topicName ?? '').toLowerCase().includes(q) ||
+ (s.reason ?? '').toLowerCase().includes(q)
+ );
+ });
+ }, [suggestions, sourceFilter, search]);
+
+ /**
+ * Dismiss everything on screen. Kept to what is actually listed rather than
+ * "every suggestion for this brand": dismissing a Search Console or
+ * Analytics row keeps that query or page out of the pool for 30 days, so
+ * clearing a filtered view must not silently suppress rows the user never
+ * looked at.
+ */
+ const handleClearAll = () => {
+ const doomed = visible;
+ if (doomed.length === 0) return;
+ setClearing(true);
+ const ids = new Set(doomed.map((d) => d.id));
+ setSuggestions((prev) => prev.filter((x) => !ids.has(x.id)));
+ Promise.allSettled(doomed.map((d) => dismissSuggestion(d.id)))
+ .then((results) => {
+ const failed = results.filter((r) => r.status === 'rejected').length;
+ if (failed > 0) {
+ toast.error(`${failed} suggestion${failed === 1 ? '' : 's'} could not be dismissed`);
+ load();
+ }
+ })
+ .finally(() => setClearing(false));
+ };
+
const handleAccept = (s: PromptSuggestion) => {
setPendingId(s.id);
startTransition(async () => {
@@ -254,219 +336,248 @@ export function SuggestionsCard({ brandId, onAccepted }: Props) {
return (
<Card id="prompt-opportunities">
- <CardHeader className={expanded ? 'pb-3' : 'py-4'}>
- <div className="flex items-center justify-between gap-4 flex-wrap">
- <button
- type="button"
- onClick={toggleExpanded}
- aria-expanded={expanded}
- className="flex items-center gap-2 text-left"
- >
- {expanded ? (
- <ChevronDown className="h-4 w-4 text-muted-foreground shrink-0" />
- ) : (
- <ChevronRight className="h-4 w-4 text-muted-foreground shrink-0" />
- )}
- <Sparkles className="h-4 w-4 text-primary" />
- <CardTitle className="text-sm font-medium">Prompt Suggestions</CardTitle>
- <Info
- className="h-3.5 w-3.5 text-muted-foreground cursor-help"
- aria-label="AI-generated prompt ideas based on your brand, existing tracked prompts, and competitors cited in AI answers."
- >
- <title>
- AI-generated prompt ideas based on your brand, existing tracked prompts, and
- competitors cited in AI answers.
- </title>
- </Info>
- {loading ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
- ) : loaded && suggestions.length > 0 ? (
- <Badge variant="secondary" className="text-xs tabular-nums">
- {suggestions.length}
- </Badge>
- ) : loaded ? (
- !expanded && (
- <span className="text-xs text-muted-foreground">no new ideas — expand</span>
- )
- ) : (
- !expanded && (
- <span className="text-xs text-muted-foreground">expand for AI prompt ideas</span>
- )
- )}
- </button>
- {expanded && (
- <Button
- onClick={handleRefresh}
- disabled={refreshing}
- size="sm"
- variant="outline"
- className="gap-2"
- >
- {refreshing ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ <CardHeader className="pb-3">
+ <div className="flex flex-wrap items-start justify-between gap-3">
+ <div className="space-y-0.5">
+ <div className="flex items-center gap-2">
+ <CardTitle className="text-base font-semibold">Prompt Suggestions</CardTitle>
+ {loading ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin text-muted-foreground" />
) : (
- <RefreshCw className="h-3.5 w-3.5" />
+ loaded &&
+ suggestions.length > 0 && (
+ <Badge variant="secondary" className="text-xs tabular-nums">
+ {suggestions.length}
+ </Badge>
+ )
)}
- {refreshing ? 'Generating…' : 'Refresh'}
- </Button>
- )}
- </div>
- </CardHeader>
- {expanded && (
- <CardContent>
- {loading ? (
- <div className="flex items-center justify-center py-10">
- <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
</div>
- ) : error ? (
- <div className="flex flex-col items-center justify-center py-10 text-center">
- <AlertTriangle className="h-8 w-8 text-destructive/60 mb-2" />
- <p className="text-sm font-medium mb-1">Couldn&apos;t load suggestions</p>
- <p className="text-xs text-muted-foreground mb-3 max-w-sm">{error}</p>
+ <p className="text-xs text-muted-foreground">
+ AI-driven suggestions based on your data and industry trends.
+ </p>
+ </div>
+
+ {loaded && suggestions.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2">
+ <Select
+ value={sourceFilter}
+ onValueChange={(v) => setSourceFilter((v as SourceFilter) ?? 'all')}
+ >
+ <SelectTrigger className="h-8 w-44 text-xs">
+ <Filter className="h-3.5 w-3.5 text-muted-foreground" />
+ <SelectValue placeholder="All sources">
+ {(value) => SOURCE_FILTER_LABELS[(value as SourceFilter) ?? 'all']}
+ </SelectValue>
+ </SelectTrigger>
+ <SelectContent>
+ {(Object.keys(SOURCE_FILTER_LABELS) as SourceFilter[]).map((key) => (
+ <SelectItem key={key} value={key}>
+ {SOURCE_FILTER_LABELS[key]}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <div className="relative w-52">
+ <SearchIcon className="absolute left-2.5 top-2.5 h-3.5 w-3.5 text-muted-foreground" />
+ <Input
+ placeholder="Search prompts…"
+ value={search}
+ onChange={(e) => setSearch(e.target.value)}
+ className="h-8 pl-8 text-xs"
+ />
+ </div>
+
<Button
- onClick={load}
- disabled={loading}
+ onClick={handleRefresh}
+ disabled={refreshing}
size="sm"
variant="outline"
className="gap-2"
>
- <RefreshCw className="h-3.5 w-3.5" />
- Retry
- </Button>
- </div>
- ) : suggestions.length === 0 ? (
- <div className="flex flex-col items-center justify-center py-10 text-center">
- <Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
- <p className="text-sm font-medium mb-1">No suggestions right now</p>
- <p className="text-xs text-muted-foreground mb-3 max-w-sm">
- Click refresh to generate new prompt ideas tailored to your brand and competitor
- activity.
- </p>
- <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
{refreshing ? (
<Loader2 className="h-3.5 w-3.5 animate-spin" />
) : (
- <Sparkles className="h-3.5 w-3.5" />
+ <RefreshCw className="h-3.5 w-3.5" />
)}
- Generate Suggestions
+ {refreshing ? 'Generating…' : 'New'}
+ </Button>
+
+ <Button
+ onClick={handleClearAll}
+ disabled={clearing || visible.length === 0}
+ size="sm"
+ variant="outline"
+ className="gap-2 text-muted-foreground"
+ title="Dismiss every suggestion listed below"
+ >
+ {clearing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Trash2 className="h-3.5 w-3.5" />
+ )}
+ Clear All
</Button>
</div>
- ) : (
- <ul className="space-y-2">
- {suggestions.map((s) => {
- const busy = pendingId === s.id;
- // Narrow the evidence payload to the shape its source promises,
- // so a row whose `source` and payload disagree renders as a
- // plain suggestion instead of reading fields that are not there.
- const gsc = gscSourceData(s);
- const ga = gaSourceData(s);
- return (
- <li
- key={s.id}
- className="group flex items-start gap-3 rounded-lg border bg-muted/20 p-3 transition-colors hover:bg-muted/40"
- >
- <div className="flex-1 min-w-0 space-y-1.5">
- <p className="text-sm font-medium leading-snug">{s.suggestedText}</p>
- <div className="flex flex-wrap items-center gap-1.5">
- {s.topicName && (
- <Badge variant="outline" className="gap-1 text-xs">
- <Tag className="h-3 w-3" />
- {s.topicName}
- </Badge>
- )}
- {/* GSC rows carry real impressions — showing the modeled
- estimate next to measured data reads as a contradiction. */}
- {s.estVolume != null && s.estVolume > 0 && !gsc && !ga && (
- <Badge variant="outline" className="gap-1 text-xs tabular-nums">
- <TrendingUp className="h-3 w-3" />~{s.estVolume.toLocaleString()}/mo
- </Badge>
- )}
- {gsc && (
- <>
- <HoverTip
- content={`From your Google Search Console data \u2014 the query "${gsc.query}" got ${gsc.impressions.toLocaleString()} impressions in the last 28 days.`}
+ )}
+ </div>
+ </CardHeader>
+ <CardContent>
+ {loading ? (
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ ) : error ? (
+ <div className="flex flex-col items-center justify-center py-10 text-center">
+ <AlertTriangle className="h-8 w-8 text-destructive/60 mb-2" />
+ <p className="text-sm font-medium mb-1">Couldn&apos;t load suggestions</p>
+ <p className="text-xs text-muted-foreground mb-3 max-w-sm">{error}</p>
+ <Button onClick={load} disabled={loading} size="sm" variant="outline" className="gap-2">
+ <RefreshCw className="h-3.5 w-3.5" />
+ Retry
+ </Button>
+ </div>
+ ) : suggestions.length === 0 ? (
+ <div className="flex flex-col items-center justify-center py-10 text-center">
+ <Sparkles className="h-8 w-8 text-muted-foreground/40 mb-2" />
+ <p className="text-sm font-medium mb-1">No suggestions right now</p>
+ <p className="text-xs text-muted-foreground mb-3 max-w-sm">
+ Click refresh to generate new prompt ideas tailored to your brand and competitor
+ activity.
+ </p>
+ <Button onClick={handleRefresh} disabled={refreshing} size="sm" className="gap-2">
+ {refreshing ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Sparkles className="h-3.5 w-3.5" />
+ )}
+ Generate Suggestions
+ </Button>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {/* Column headings, so the source column reads as a column rather
+ than as loose badges beside the text. */}
+ <div className="hidden gap-3 px-3 text-xs text-muted-foreground sm:grid sm:grid-cols-[2.25rem_1fr_18rem_5rem]">
+ <span />
+ <span>Prompt</span>
+ <span>Source</span>
+ <span />
+ </div>
+
+ {visible.length === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ No suggestions match this filter.
+ </p>
+ ) : (
+ <ul className="space-y-2">
+ {visible.map((s, index) => {
+ const busy = pendingId === s.id;
+ const gsc = gscSourceData(s);
+ const ga = gaSourceData(s);
+ return (
+ <li
+ key={s.id}
+ className="grid items-start gap-3 rounded-lg border bg-card p-3 transition-colors hover:bg-muted/30 sm:grid-cols-[2.25rem_1fr_18rem_5rem]"
+ >
+ <span className="flex h-7 w-7 items-center justify-center rounded-md bg-muted text-xs font-medium tabular-nums text-muted-foreground">
+ {index + 1}
+ </span>
+
+ <div className="min-w-0 space-y-1.5">
+ <p className="text-sm font-medium leading-snug">{s.suggestedText}</p>
+ <div className="flex flex-wrap items-center gap-1.5">
+ {s.topicName && (
+ <Badge variant="outline" className="gap-1 text-xs font-normal">
+ <Tag className="h-3 w-3" />
+ {s.topicName}
+ </Badge>
+ )}
+ {/* Measured rows carry real figures — showing the
+ modelled estimate beside measured data reads as a
+ contradiction. */}
+ {gsc ? (
+ <Badge
+ variant="outline"
+ className="gap-1 text-xs font-normal tabular-nums"
>
+ <TrendingUp className="h-3 w-3" />
+ {gsc.impressions.toLocaleString()} impr/mo
+ </Badge>
+ ) : ga ? (
+ <HoverTip content={gaEvidence(ga).tooltip}>
<Badge
variant="outline"
- className="gap-1 text-xs border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400"
+ className="gap-1 text-xs font-normal tabular-nums"
>
- <SearchCheck className="h-3 w-3" />
- Search Console · {gsc.impressions.toLocaleString()} impr/mo
+ <TrendingUp className="h-3 w-3" />
+ {gaEvidence(ga).label}
</Badge>
</HoverTip>
- {gsc.badge && (
- <HoverTip content={GSC_BADGES[gsc.badge].tooltip}>
- <Badge variant="outline" className="text-xs">
- {GSC_BADGES[gsc.badge].label}
- </Badge>
- </HoverTip>
- )}
- </>
- )}
- {ga && (
- <>
- <HoverTip
- content={`From your Google Analytics — derived from ${ga.pageTitle ? `"${ga.pageTitle}" (${ga.landingPage})` : ga.landingPage}, read from the page itself rather than from its URL or product name.`}
- >
+ ) : (
+ s.estVolume != null &&
+ s.estVolume > 0 && (
<Badge
variant="outline"
- className="gap-1 text-xs border-amber-500/30 bg-amber-500/10 text-amber-600 dark:text-amber-400"
+ className="gap-1 text-xs font-normal tabular-nums"
>
- {ga.kind === 'ai_momentum' ? (
- <Sparkle className="h-3 w-3" />
- ) : (
- <BarChart3 className="h-3 w-3" />
- )}
- Analytics · {ga.landingPage}
+ <TrendingUp className="h-3 w-3" />~{s.estVolume.toLocaleString()}/mo
</Badge>
- </HoverTip>
- <HoverTip content={gaEvidence(ga).tooltip}>
- <Badge variant="outline" className="text-xs tabular-nums">
- {gaEvidence(ga).label}
+ )
+ )}
+ {gsc?.badge && (
+ <HoverTip content={GSC_BADGES[gsc.badge].tooltip}>
+ <Badge variant="outline" className="text-xs font-normal">
+ {GSC_BADGES[gsc.badge].label}
</Badge>
</HoverTip>
- </>
+ )}
+ </div>
+ {s.reason && (
+ <p className="text-xs leading-relaxed text-muted-foreground">
+ {s.reason}
+ </p>
)}
</div>
- {s.reason && (
- <p className="text-xs text-muted-foreground leading-relaxed">{s.reason}</p>
- )}
- </div>
- <div className="flex items-center gap-1 shrink-0">
- <Button
- size="icon"
- variant="outline"
- className="h-8 w-8"
- onClick={() => handleAccept(s)}
- disabled={busy}
- title="Add to tracked prompts"
- aria-label="Add to tracked prompts"
- >
- {busy ? (
- <Loader2 className="h-3.5 w-3.5 animate-spin" />
- ) : (
- <Plus className="h-3.5 w-3.5" />
- )}
- </Button>
- <Button
- size="icon"
- variant="ghost"
- className="h-8 w-8 text-muted-foreground"
- onClick={() => handleDismiss(s)}
- disabled={busy}
- title="Dismiss suggestion"
- aria-label="Dismiss suggestion"
- >
- <X className="h-3.5 w-3.5" />
- </Button>
- </div>
- </li>
- );
- })}
- </ul>
- )}
- </CardContent>
- )}
+
+ <SourceBadges suggestion={s} />
+
+ <div className="flex items-center justify-end gap-1">
+ <Button
+ size="icon"
+ variant="outline"
+ className="h-8 w-8"
+ onClick={() => handleAccept(s)}
+ disabled={busy}
+ title="Add to tracked prompts"
+ aria-label="Add to tracked prompts"
+ >
+ {busy ? (
+ <Loader2 className="h-3.5 w-3.5 animate-spin" />
+ ) : (
+ <Plus className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="h-8 w-8 text-muted-foreground"
+ onClick={() => handleDismiss(s)}
+ disabled={busy}
+ title="Dismiss suggestion"
+ aria-label="Dismiss suggestion"
+ >
+ <X className="h-3.5 w-3.5" />
+ </Button>
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ </div>
+ )}
+ </CardContent>
</Card>
);
}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
index 09c9fe4aa..35bd5dc3e 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/prompts/page.tsx
@@ -63,6 +63,8 @@ import {
ChevronDown,
Trash2,
X,
+ ListChecks,
+ Sparkles,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { useBrandStore } from '@/stores/use-brand-store';
@@ -89,6 +91,7 @@ import {
type PromptRangePreset,
} from '@/config/prompt-options';
import { DateRangeFilter } from '@/components/filters/date-range-filter';
+import { DataSourcesPanel } from './_data-sources-panel';
import { PLANS } from '@/config/plans';
import { getTopics } from '@/lib/actions/topic';
import { type PromptVisibilitySummary } from '@/lib/actions/tracking';
@@ -259,6 +262,9 @@ const PROMPT_EXPORT_HINT = 'No prompts yet - add prompts first.';
const VALID_TABS = ['all', 'fanout', 'insights'] as const;
type TabId = (typeof VALID_TABS)[number];
+const PROMPT_VIEWS = ['tracked', 'suggestions'] as const;
+type PromptsView = (typeof PROMPT_VIEWS)[number];
+
function formatRelative(iso?: string): string {
if (!iso) return '—';
const diffMs = Date.now() - new Date(iso).getTime();
@@ -920,10 +926,25 @@ export default function PromptsPage() {
const initialTab: TabId = (() => {
const raw = searchParams.get('tab');
- return (VALID_TABS as readonly string[]).includes(raw ?? '') ? (raw as TabId) : 'all';
+ if ((VALID_TABS as readonly string[]).includes(raw ?? '')) return raw as TabId;
+ return 'all';
})();
const [tab, setTab] = useState<TabId>(initialTab);
+ // The Prompts tab holds two views of the same roster: what is tracked, and
+ // what could be. A sub-tab rather than a fourth top-level tab, because the
+ // date range, the Add prompt action and the export all belong to both.
+ const initialView: PromptsView = (() => {
+ const raw = searchParams.get('view');
+ if ((PROMPT_VIEWS as readonly string[]).includes(raw ?? '')) return raw as PromptsView;
+ // Links written before the split point at the suggestions card's anchor.
+ if (typeof window !== 'undefined' && window.location.hash === '#prompt-opportunities') {
+ return 'suggestions';
+ }
+ return 'tracked';
+ })();
+ const [view, setView] = useState<PromptsView>(initialView);
+
const initialRange: PromptRangePreset = (() => {
const raw = searchParams.get('range');
// Older links carry a bare day count (`range=7`); keep them working rather
@@ -961,10 +982,12 @@ 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 wantRange = rangePreset === DEFAULT_PROMPT_RANGE_PRESET ? null : rangePreset;
+ const wantView = view === 'tracked' ? null : view;
const wantFrom = rangePreset === 'custom' && customFrom ? customFrom : null;
const wantTo = rangePreset === 'custom' && customTo ? customTo : null;
if (
currentTab === tab &&
+ searchParams.get('view') === wantView &&
currentRange === wantRange &&
searchParams.get('from') === wantFrom &&
searchParams.get('to') === wantTo
@@ -973,6 +996,8 @@ export default function PromptsPage() {
}
const params = new URLSearchParams(Array.from(searchParams.entries()));
params.set('tab', tab);
+ if (wantView) params.set('view', wantView);
+ else params.delete('view');
if (wantRange) params.set('range', wantRange);
else params.delete('range');
if (wantFrom) params.set('from', wantFrom);
@@ -982,7 +1007,7 @@ export default function PromptsPage() {
// Keep the hash: deep links like #prompt-opportunities arrive without a
// tab param, and this sync must not strip their anchor from the URL.
window.history.replaceState(null, '', `?${params.toString()}${window.location.hash}`);
- }, [tab, rangePreset, customFrom, customTo, searchParams]);
+ }, [tab, view, rangePreset, customFrom, customTo, searchParams]);
// Deep link from the Insights Recommendations row (#459): the target card
// only exists once the Insights tab's volume data has rendered, so a bare
@@ -1248,7 +1273,7 @@ export default function PromptsPage() {
<Tabs value={tab} onValueChange={(v) => setTab(v as TabId)}>
<div className="flex items-center justify-between gap-4 flex-wrap">
<TabsList>
- <TabsTrigger value="all">All Prompts</TabsTrigger>
+ <TabsTrigger value="all">Prompts</TabsTrigger>
<TabsTrigger value="fanout">Query Fan-out</TabsTrigger>
<TabsTrigger value="insights">Insights</TabsTrigger>
</TabsList>
@@ -1291,10 +1316,11 @@ export default function PromptsPage() {
</div>
{/* Filter bar — same shape and position as Visibility and Citations
- (#713). Hidden on Insights: that tab shows keyword volume
- estimates, which carry no date dimension, so a range there would be
- a control that changes nothing. It sits outside the tab panels
- because the range governs both All Prompts and Query Fan-out. */}
+ (#713). It sits outside the tab panels because the range governs
+ both All Prompts and Query Fan-out.
+ Hidden on Insights: that tab shows keyword volume estimates, which
+ carry no date dimension, so a range there would be a control that
+ changes nothing. */}
{tab !== 'insights' && (
<div className="mt-4 flex flex-wrap items-end gap-3">
<DateRangeFilter
@@ -1311,54 +1337,96 @@ export default function PromptsPage() {
{/* ─── All Prompts tab ─────────────────────────────────────────── */}
<TabsContent value="all" className="mt-4 space-y-4">
- {activeBrandId && <SuggestionsCard brandId={activeBrandId} onAccepted={loadData} />}
-
- {!loading && unanalyzedCount > 0 && (
- <div className="flex flex-col gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3 sm:flex-row sm:items-center sm:justify-between dark:border-amber-900/50 dark:bg-amber-950/30">
- <div className="flex items-start gap-2.5">
- <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />
- <div className="text-sm">
- <p className="font-medium text-amber-900 dark:text-amber-200">
- {unanalyzedCount} prompt{unanalyzedCount === 1 ? '' : 's'} haven&apos;t been
- analyzed yet
- </p>
- <p className="text-amber-800/80 dark:text-amber-300/80">
- {quotaExhausted
- ? 'Their Volume & Competition stay empty until analyzed — but your monthly volume analysis limit is reached. Upgrade your plan to analyze more.'
- : 'Run volume analysis to fill in their Volume & Competition.'}
- </p>
- </div>
- </div>
- <Button
- size="sm"
- className="shrink-0"
- onClick={handleAnalyzeNew}
- disabled={analyzing || quotaExhausted}
- >
- {analyzing ? (
- <>
- <Loader2 className="mr-2 h-4 w-4 animate-spin" />
- Analyzing...
- </>
- ) : (
- <>
- <BarChart3 className="mr-2 h-4 w-4" />
- Analyze {unanalyzedCount} prompt{unanalyzedCount === 1 ? '' : 's'}
- </>
+ {/* Tracked vs suggested: two views of the same roster. A segmented
+ control rather than a second Tabs, so it reads as a filter on
+ this panel and not as another level of page navigation. */}
+ <div
+ className="inline-flex rounded-lg border p-1"
+ role="tablist"
+ aria-label="Prompt view"
+ >
+ {(
+ [
+ { id: 'tracked' as const, label: 'Tracked Prompts', Icon: ListChecks },
+ { id: 'suggestions' as const, label: 'Prompt Suggestions', Icon: Sparkles },
+ ] satisfies { id: PromptsView; label: string; Icon: typeof ListChecks }[]
+ ).map(({ id, label, Icon }) => (
+ <button
+ key={id}
+ type="button"
+ role="tab"
+ aria-selected={view === id}
+ onClick={() => setView(id)}
+ className={cn(
+ 'flex items-center gap-2 rounded-md px-3 py-1.5 text-sm font-medium transition-colors',
+ view === id
+ ? 'bg-muted text-foreground'
+ : 'text-muted-foreground hover:text-foreground',
)}
- </Button>
- </div>
+ >
+ <Icon className="h-4 w-4" />
+ {label}
+ </button>
+ ))}
+ </div>
+
+ {view === 'suggestions' ? (
+ activeBrandId && (
+ <>
+ <DataSourcesPanel brandId={activeBrandId} />
+ <SuggestionsCard brandId={activeBrandId} onAccepted={loadData} />
+ </>
+ )
+ ) : (
+ <>
+ {!loading && unanalyzedCount > 0 && (
+ <div className="flex flex-col gap-3 rounded-lg border border-amber-200 bg-amber-50 p-3 sm:flex-row sm:items-center sm:justify-between dark:border-amber-900/50 dark:bg-amber-950/30">
+ <div className="flex items-start gap-2.5">
+ <AlertCircle className="mt-0.5 h-4 w-4 shrink-0 text-amber-600 dark:text-amber-500" />
+ <div className="text-sm">
+ <p className="font-medium text-amber-900 dark:text-amber-200">
+ {unanalyzedCount} prompt{unanalyzedCount === 1 ? '' : 's'} haven&apos;t been
+ analyzed yet
+ </p>
+ <p className="text-amber-800/80 dark:text-amber-300/80">
+ {quotaExhausted
+ ? 'Their Volume & Competition stay empty until analyzed — but your monthly volume analysis limit is reached. Upgrade your plan to analyze more.'
+ : 'Run volume analysis to fill in their Volume & Competition.'}
+ </p>
+ </div>
+ </div>
+ <Button
+ size="sm"
+ className="shrink-0"
+ onClick={handleAnalyzeNew}
+ disabled={analyzing || quotaExhausted}
+ >
+ {analyzing ? (
+ <>
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ Analyzing...
+ </>
+ ) : (
+ <>
+ <BarChart3 className="mr-2 h-4 w-4" />
+ Analyze {unanalyzedCount} prompt{unanalyzedCount === 1 ? '' : 's'}
+ </>
+ )}
+ </Button>
+ </div>
+ )}
+ <AllPromptsTab
+ loading={loading}
+ prompts={allPrompts}
+ activeBrandId={activeBrandId}
+ volumeByPromptId={volumeByPromptId}
+ visibility={visibility}
+ rangeLabel={rangeLabel}
+ onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}
+ onEditPrompt={canManage ? setEditingPrompt : undefined}
+ />
+ </>
)}
- <AllPromptsTab
- loading={loading}
- prompts={allPrompts}
- activeBrandId={activeBrandId}
- volumeByPromptId={volumeByPromptId}
- visibility={visibility}
- rangeLabel={rangeLabel}
- onAddPrompt={canManage ? () => setAddPromptOpen(true) : undefined}
- onEditPrompt={canManage ? setEditingPrompt : undefined}
- />
</TabsContent>
{/* ─── Query Fan-out tab ───────────────────────────────────────── */}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index 1545c6f63..40161afe1 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -38,6 +38,66 @@ export async function getIntegrationStatus(
return body as IntegrationStatusResult;
}
+/**
+ * Everything the suggestion-sources panel needs, in two round trips (#659).
+ *
+ * Deliberately does NOT call `getIntegrationStatus`. That resolves the live
+ * state against Composio and re-syncs our row, which costs ~450ms per
+ * provider — measured — and made the panel appear well after the suggestions
+ * it sits above. This reads the row Composio's own status check maintains,
+ * plus the brand's property mapping, in a single query.
+ *
+ * The trade-off is that a connection revoked on Google's side still reads as
+ * connected here until Settings runs its authoritative check and rewrites the
+ * row. For a panel that describes what feeds suggestions, a stale "connected"
+ * for a few minutes is a better failure than a second of blank space on every
+ * visit.
+ */
+export interface SuggestionSourceStates {
+ gsc: { configured: boolean; connected: boolean; mapped: boolean };
+ ga: { configured: boolean; connected: boolean; mapped: boolean };
+ dataForSeo: { configured: boolean };
+}
+
+export async function getSuggestionSourceStates(brandId: string): Promise<SuggestionSourceStates> {
+ const supabase = await createClient();
+
+ interface ConfigBody {
+ googleSearchConsole?: boolean;
+ googleAnalytics?: boolean;
+ dataForSeo?: boolean;
+ }
+
+ const [configRes, brandRes, connRes] = await Promise.all([
+ fetch(`${API_BASE_URL}/api/integrations/config`, {
+ headers: await authHeaders(),
+ cache: 'no-store',
+ })
+ .then((r) => (r.ok ? (r.json() as Promise<ConfigBody>) : ({} as ConfigBody)))
+ .catch(() => ({}) as ConfigBody),
+ supabase.from('brands').select('gsc_property, ga_property_id').eq('id', brandId).maybeSingle(),
+ supabase.from('integration_connections').select('provider, status'),
+ ]);
+
+ const connected = new Set(
+ (connRes.data ?? []).filter((r) => r.status === 'connected').map((r) => r.provider),
+ );
+
+ return {
+ gsc: {
+ configured: Boolean(configRes.googleSearchConsole),
+ connected: connected.has('google-search-console'),
+ mapped: Boolean(brandRes.data?.gsc_property),
+ },
+ ga: {
+ configured: Boolean(configRes.googleAnalytics),
+ connected: connected.has('google-analytics'),
+ mapped: Boolean(brandRes.data?.ga_property_id),
+ },
+ dataForSeo: { configured: Boolean(configRes.dataForSeo) },
+ };
+}
+
export async function connectIntegration(
provider: IntegrationProvider,
callbackUrl: string,