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(competitors): suggest competitors with AI from the Competitors page (#1198)

Sanjeev Kumarb0152827846f
diff --git a/web/messages/en.json b/web/messages/en.json
index bd9f5cd50..a83b34441 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3973,7 +3973,21 @@
"noDataTitle": "No comparison data",
"noDataDescription": "Run a tracking check from the Insights page to generate comparison data for this competitor.",
"loadError": "Failed to load comparison data."
- }
+ },
+ "suggestCompetitors": "Suggest competitors",
+ "suggestCompetitorsDescription": "Discover competitors for {brand} with AI research. Select the ones you want to track.",
+ "suggestCompetitorsLoading": "Researching competitors… This can take a little while.",
+ "suggestCompetitorsError": "Couldn't suggest competitors. Please try again.",
+ "suggestCompetitorsRetry": "Try again",
+ "refreshCompetitorSuggestions": "Refresh suggestions",
+ "noCompetitorSuggestions": "No competitors were suggested. Try refreshing the suggestions.",
+ "noNewCompetitorSuggestions": "All suggested competitors are already on your list.",
+ "selectedCompetitorCount": "{count} selected",
+ "addSelectedCompetitors": "Add {count, plural, one {# competitor} other {# competitors}}",
+ "suggestedCompetitorsAdded": "{count, plural, one {# competitor added successfully.} other {# competitors added successfully.}}",
+ "suggestedCompetitorsAddError": "Failed to add competitors. Please try again.",
+ "suggestedCompetitorsPartialError": "{count, plural, one {# competitor couldn't be added. You can retry the remaining suggestions.} other {# competitors couldn't be added. You can retry the remaining suggestions.}}",
+ "missingCompetitorWebsite": "Add a website to this brand before asking AI to suggest competitors."
},
"citations": {
"title": "Citations",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/_suggest-competitors-dialog.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_suggest-competitors-dialog.tsx
new file mode 100644
index 000000000..a5e765ad2
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/_suggest-competitors-dialog.tsx
@@ -0,0 +1,225 @@
+'use client';
+
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Loader2, Plus, RefreshCw, Sparkles } from 'lucide-react';
+import type { Brand, Competitor } from '@/types';
+import { suggestCompetitors, type SuggestedCompetitor } from '@/lib/ai-brand-setup';
+import {
+ competitorSuggestionKey,
+ filterNewCompetitorSuggestions,
+} from '@/lib/competitor-suggestions';
+import { Button } from '@/components/ui/button';
+import { Checkbox } from '@/components/ui/checkbox';
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from '@/components/ui/dialog';
+
+interface AddSelectedResult {
+ added: number;
+ failed: number;
+}
+
+interface SuggestCompetitorsDialogProps {
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ brand: Brand;
+ existingCompetitors: Competitor[];
+ onAddSelected: (suggestions: SuggestedCompetitor[]) => Promise<AddSelectedResult>;
+}
+
+export function SuggestCompetitorsDialog({
+ open,
+ onOpenChange,
+ brand,
+ existingCompetitors,
+ onAddSelected,
+}: SuggestCompetitorsDialogProps) {
+ const t = useTranslations('competitors');
+ const [suggestions, setSuggestions] = useState<SuggestedCompetitor[]>([]);
+ const [selectedKeys, setSelectedKeys] = useState<string[]>([]);
+ const [loading, setLoading] = useState(false);
+ const [saving, setSaving] = useState(false);
+ const [loadError, setLoadError] = useState(false);
+
+ const website = useMemo(
+ () =>
+ brand.domains.find((domain) => domain.isPrimary)?.domain ?? brand.domains[0]?.domain ?? '',
+ [brand.domains],
+ );
+
+ const loadSuggestions = useCallback(async () => {
+ setLoading(true);
+ setLoadError(false);
+
+ if (!website.trim()) {
+ setSuggestions([]);
+ setSelectedKeys([]);
+ setLoadError(true);
+ toast.error(t('missingCompetitorWebsite'));
+ setLoading(false);
+ return;
+ }
+
+ try {
+ const result = await suggestCompetitors({
+ brandName: brand.name,
+ website,
+ description: brand.description ?? '',
+ region: brand.region ?? '',
+ language: brand.language ?? 'en',
+ });
+ setSuggestions(result.competitors);
+ setSelectedKeys(result.competitors.map(competitorSuggestionKey));
+ } catch (error) {
+ console.error('Failed to suggest competitors:', error);
+ setSuggestions([]);
+ setSelectedKeys([]);
+ setLoadError(true);
+ toast.error(t('suggestCompetitorsError'));
+ } finally {
+ setLoading(false);
+ }
+ }, [brand.description, brand.language, brand.name, brand.region, t, website]);
+
+ useEffect(() => {
+ if (open) void loadSuggestions();
+ }, [open, loadSuggestions]);
+
+ const visibleSuggestions = useMemo(
+ () => filterNewCompetitorSuggestions(suggestions, existingCompetitors),
+ [suggestions, existingCompetitors],
+ );
+ const selectedSuggestions = visibleSuggestions.filter((suggestion) =>
+ selectedKeys.includes(competitorSuggestionKey(suggestion)),
+ );
+
+ function toggleSelected(suggestion: SuggestedCompetitor, checked: boolean) {
+ const key = competitorSuggestionKey(suggestion);
+ setSelectedKeys((current) =>
+ checked ? [...new Set([...current, key])] : current.filter((item) => item !== key),
+ );
+ }
+
+ async function handleAddSelected() {
+ if (selectedSuggestions.length === 0) return;
+ setSaving(true);
+ try {
+ const { added, failed } = await onAddSelected(selectedSuggestions);
+ if (added > 0) toast.success(t('suggestedCompetitorsAdded', { count: added }));
+ if (failed > 0) {
+ toast.error(t('suggestedCompetitorsPartialError', { count: failed }));
+ return;
+ }
+ if (added === 0) {
+ toast.error(t('suggestedCompetitorsAddError'));
+ return;
+ }
+ onOpenChange(false);
+ } catch (error) {
+ console.error('Failed to add suggested competitors:', error);
+ toast.error(t('suggestedCompetitorsAddError'));
+ } finally {
+ setSaving(false);
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-xl">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2">
+ <Sparkles className="h-5 w-5" />
+ {t('suggestCompetitors')}
+ </DialogTitle>
+ <DialogDescription>
+ {t('suggestCompetitorsDescription', { brand: brand.name })}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="min-h-28 py-2">
+ {loading ? (
+ <div className="flex items-center justify-center gap-3 py-10" role="status">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ <p className="text-sm text-muted-foreground">{t('suggestCompetitorsLoading')}</p>
+ </div>
+ ) : loadError ? (
+ <p className="py-8 text-center text-sm text-destructive" role="alert">
+ {t('suggestCompetitorsError')}
+ </p>
+ ) : visibleSuggestions.length === 0 ? (
+ <p className="py-8 text-center text-sm text-muted-foreground">
+ {suggestions.length > 0
+ ? t('noNewCompetitorSuggestions')
+ : t('noCompetitorSuggestions')}
+ </p>
+ ) : (
+ <div className="max-h-[50vh] space-y-2 overflow-y-auto pr-1">
+ {visibleSuggestions.map((suggestion) => {
+ const key = competitorSuggestionKey(suggestion);
+ const checked = selectedKeys.includes(key);
+ return (
+ <label
+ key={key}
+ className="flex cursor-pointer items-start gap-3 rounded-md border p-3 transition-colors hover:bg-muted/50"
+ >
+ <Checkbox
+ checked={checked}
+ disabled={saving}
+ onCheckedChange={(value) => toggleSelected(suggestion, value === true)}
+ aria-label={suggestion.name}
+ className="mt-0.5"
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block break-words text-sm font-medium">
+ {suggestion.name}
+ </span>
+ <span className="block break-all text-xs text-muted-foreground">
+ {suggestion.domain}
+ </span>
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ )}
+ </div>
+
+ <DialogFooter className="gap-2 sm:justify-between">
+ <div className="flex items-center text-xs text-muted-foreground">
+ {t('selectedCompetitorCount', { count: selectedSuggestions.length })}
+ </div>
+ <div className="flex flex-wrap justify-end gap-2">
+ <Button
+ type="button"
+ variant="outline"
+ disabled={loading || saving}
+ onClick={() => void loadSuggestions()}
+ >
+ <RefreshCw className="mr-2 h-4 w-4" />
+ {loadError ? t('suggestCompetitorsRetry') : t('refreshCompetitorSuggestions')}
+ </Button>
+ <Button
+ type="button"
+ disabled={loading || saving || selectedSuggestions.length === 0}
+ onClick={() => void handleAddSelected()}
+ >
+ {saving ? (
+ <Loader2 className="mr-2 h-4 w-4 animate-spin" />
+ ) : (
+ <Plus className="mr-2 h-4 w-4" />
+ )}
+ {t('addSelectedCompetitors', { count: selectedSuggestions.length })}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
index 2e69bfc56..a991e35c2 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/competitors/page.tsx
@@ -6,6 +6,8 @@ import { useTranslations } from 'next-intl';
import { useBrandStore } from '@/stores/use-brand-store';
import { useFeatureGate } from '@/hooks/use-feature-gate';
import { getCompetitors, addCompetitor, deleteCompetitor } from '@/lib/actions/competitor';
+import type { SuggestedCompetitor } from '@/lib/ai-brand-setup';
+import { SuggestCompetitorsDialog } from './_suggest-competitors-dialog';
import {
getCompetitorComparison,
getHeadToHeadComparison,
@@ -46,6 +48,7 @@ import { cn } from '@/lib/utils';
import { AIProviderAvatar, resolveAIProvider } from '@/components/ai-provider-avatar';
import {
Plus,
+ Sparkles,
Trash2,
Loader2,
Users,
@@ -158,7 +161,7 @@ function NoBrandSelected() {
// ─── Empty State ──────────────────────────────────────────────────────────────
-function EmptyState({ onAdd }: { onAdd: () => void }) {
+function EmptyState({ onAdd, onSuggest }: { onAdd: () => void; onSuggest: () => void }) {
const t = useTranslations('competitors');
return (
<Card>
@@ -168,10 +171,16 @@ function EmptyState({ onAdd }: { onAdd: () => void }) {
</div>
<h3 className="text-lg font-semibold">{t('emptyTitle')}</h3>
<p className="text-sm text-muted-foreground mt-1 max-w-sm">{t('emptyDescription')}</p>
- <Button className="mt-6 gap-2" onClick={onAdd}>
- <Plus className="h-4 w-4" />
- {t('addCompetitor')}
- </Button>
+ <div className="mt-6 flex flex-wrap justify-center gap-2">
+ <Button className="gap-2" onClick={onAdd}>
+ <Plus className="h-4 w-4" />
+ {t('addCompetitor')}
+ </Button>
+ <Button variant="outline" className="gap-2" onClick={onSuggest}>
+ <Sparkles className="h-4 w-4" />
+ {t('suggestCompetitors')}
+ </Button>
+ </div>
</CardContent>
</Card>
);
@@ -1204,6 +1213,7 @@ export default function CompetitorsPage() {
const [comparisonData, setComparisonData] = useState<CompetitorComparisonData | null>(null);
const [loading, setLoading] = useState(true);
const [dialogOpen, setDialogOpen] = useState(false);
+ const [suggestDialogOpen, setSuggestDialogOpen] = useState(false);
const [deleting, setDeleting] = useState<string | null>(null);
const [confirmDelete, setConfirmDelete] = useState<Competitor | null>(null);
@@ -1347,6 +1357,36 @@ export default function CompetitorsPage() {
loadData();
}
+ async function handleAddSuggested(
+ suggestions: SuggestedCompetitor[],
+ ): Promise<{ added: number; failed: number }> {
+ if (!brand) return { added: 0, failed: suggestions.length };
+
+ const results = await Promise.allSettled(
+ suggestions.map((suggestion) =>
+ addCompetitor(brand.id, { name: suggestion.name, domain: suggestion.domain }),
+ ),
+ );
+ const added = results.filter((result) => result.status === 'fulfilled').length;
+ const failed = results.length - added;
+
+ if (added > 0) {
+ // Refresh in place rather than toggling the page-wide initial loader:
+ // the suggestion dialog should remain open when some inserts fail.
+ try {
+ const [currentCompetitors, comparison] = await Promise.all([
+ getCompetitors(brand.id),
+ getCompetitorComparison(brand.id, last30Days()),
+ ]);
+ setCompetitors(currentCompetitors);
+ setComparisonData(comparison.brands.length > 1 ? comparison : null);
+ } catch {
+ toast.error(t('loadError'));
+ }
+ }
+ return { added, failed };
+ }
+
async function handleDelete(id: string) {
setDeleting(id);
try {
@@ -1421,19 +1461,28 @@ export default function CompetitorsPage() {
return (
<div className="space-y-6">
{/* Header */}
- <div className="flex items-center justify-between">
+ <div className="flex flex-wrap items-center justify-between gap-3">
<div>
<h1 className="text-2xl font-bold tracking-tight">{t('title')}</h1>
<p className="text-muted-foreground">{t('description')}</p>
</div>
- <Button className="gap-2" onClick={() => setDialogOpen(true)}>
- <Plus className="h-4 w-4" />
- {t('addCompetitor')}
- </Button>
+ <div className="flex flex-wrap gap-2">
+ <Button variant="outline" className="gap-2" onClick={() => setSuggestDialogOpen(true)}>
+ <Sparkles className="h-4 w-4" />
+ {t('suggestCompetitors')}
+ </Button>
+ <Button className="gap-2" onClick={() => setDialogOpen(true)}>
+ <Plus className="h-4 w-4" />
+ {t('addCompetitor')}
+ </Button>
+ </div>
</div>
{competitors.length === 0 ? (
- <EmptyState onAdd={() => setDialogOpen(true)} />
+ <EmptyState
+ onAdd={() => setDialogOpen(true)}
+ onSuggest={() => setSuggestDialogOpen(true)}
+ />
) : (
<>
{/* Competitor List */}
@@ -1533,6 +1582,14 @@ export default function CompetitorsPage() {
<AddCompetitorDialog open={dialogOpen} onOpenChange={setDialogOpen} onAdd={handleAdd} />
+ <SuggestCompetitorsDialog
+ open={suggestDialogOpen}
+ onOpenChange={setSuggestDialogOpen}
+ brand={brand}
+ existingCompetitors={competitors}
+ onAddSelected={handleAddSuggested}
+ />
+
<ConfirmDeleteCompetitorDialog
competitor={confirmDelete}
onOpenChange={(open) => {
diff --git a/web/src/lib/competitor-suggestions.test.ts b/web/src/lib/competitor-suggestions.test.ts
new file mode 100644
index 000000000..bba660c93
--- /dev/null
+++ b/web/src/lib/competitor-suggestions.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it } from 'vitest';
+import {
+ competitorSuggestionKey,
+ filterNewCompetitorSuggestions,
+ normalizeCompetitorDomain,
+ normalizeCompetitorName,
+} from './competitor-suggestions';
+
+describe('normalizeCompetitorName', () => {
+ it('ignores case, whitespace, punctuation, and accents', () => {
+ expect(normalizeCompetitorName(' Café & Co. ')).toBe('cafeandco');
+ expect(normalizeCompetitorName('CAFE-AND-CO')).toBe('cafeandco');
+ });
+});
+
+describe('normalizeCompetitorDomain', () => {
+ it('normalizes protocols, www, paths, and trailing dots', () => {
+ expect(normalizeCompetitorDomain('https://www.Acme.com/pricing/')).toBe('acme.com');
+ expect(normalizeCompetitorDomain('acme.com.')).toBe('acme.com');
+ });
+});
+
+describe('filterNewCompetitorSuggestions', () => {
+ it('removes existing names/domains and retains only unique new suggestions', () => {
+ const suggestions = [
+ { name: 'Existing Inc', domain: 'new-domain.example' },
+ { name: 'New competitor', domain: 'https://www.acme.com/' },
+ { name: 'Unique Co', domain: 'unique.example' },
+ { name: 'Unique Co', domain: 'unique-alt.example' },
+ { name: 'Another Co', domain: 'unique.example' },
+ { name: 'Missing Domain', domain: '' },
+ ];
+
+ expect(
+ filterNewCompetitorSuggestions(suggestions, [
+ { name: 'Existing Inc', domain: 'existing.example' },
+ { name: 'Other name', domain: 'https://acme.com/pricing' },
+ ]),
+ ).toEqual([{ name: 'Unique Co', domain: 'unique.example' }]);
+ });
+
+ it('uses a normalized domain as the stable selection key', () => {
+ expect(competitorSuggestionKey({ name: 'Acme', domain: 'https://www.acme.com/' })).toBe(
+ 'domain:acme.com',
+ );
+ });
+});
diff --git a/web/src/lib/competitor-suggestions.ts b/web/src/lib/competitor-suggestions.ts
new file mode 100644
index 000000000..d579b9c0d
--- /dev/null
+++ b/web/src/lib/competitor-suggestions.ts
@@ -0,0 +1,69 @@
+import type { SuggestedCompetitor } from '@/lib/ai-brand-setup';
+
+export interface ExistingCompetitorIdentity {
+ name: string;
+ domain: string;
+}
+
+export function normalizeCompetitorName(name: string): string {
+ return name
+ .normalize('NFKD')
+ .replace(/[\u0300-\u036f]/g, '')
+ .toLowerCase()
+ .replace(/&/g, 'and')
+ .replace(/[^a-z0-9]/g, '');
+}
+
+/** Normalize a saved domain or URL to its host so equivalent URLs deduplicate. */
+export function normalizeCompetitorDomain(domain: string): string {
+ return domain
+ .trim()
+ .toLowerCase()
+ .replace(/^[a-z][a-z\d+.-]*:\/\//, '')
+ .replace(/^www\./, '')
+ .split(/[/?#]/, 1)[0]
+ .replace(/:\d+$/, '')
+ .replace(/\.$/, '');
+}
+
+export function competitorSuggestionKey(suggestion: SuggestedCompetitor): string {
+ const domain = normalizeCompetitorDomain(suggestion.domain);
+ return domain ? `domain:${domain}` : `name:${normalizeCompetitorName(suggestion.name)}`;
+}
+
+/**
+ * Remove suggestions already tracked by the brand, and duplicate candidates
+ * from the AI response. Name and domain matches are case/URL-insensitive.
+ */
+export function filterNewCompetitorSuggestions(
+ suggestions: SuggestedCompetitor[],
+ existing: ExistingCompetitorIdentity[],
+): SuggestedCompetitor[] {
+ const existingNames = new Set(
+ existing.map((competitor) => normalizeCompetitorName(competitor.name)).filter(Boolean),
+ );
+ const existingDomains = new Set(
+ existing.map((competitor) => normalizeCompetitorDomain(competitor.domain)).filter(Boolean),
+ );
+ const seenNames = new Set<string>();
+ const seenDomains = new Set<string>();
+
+ return suggestions.filter((suggestion) => {
+ const name = normalizeCompetitorName(suggestion.name);
+ const domain = normalizeCompetitorDomain(suggestion.domain);
+ if (!name || !domain) return false;
+
+ if (
+ existingNames.has(name) ||
+ existingDomains.has(domain) ||
+ seenNames.has(name) ||
+ seenDomains.has(domain)
+ ) {
+ return false;
+ }
+
+ seenNames.add(name);
+ seenDomains.add(domain);
+ return true;
+ });
+}