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(traffic): show the page's data sources in a strip and collapse the snippet box (#1153)

Cihan265787507acd
diff --git a/web/messages/en.json b/web/messages/en.json
index 789a0b76f..619ffe6af 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -3072,7 +3072,31 @@
"snippetTitle": "Add this snippet to your website",
"snippetDescription": "Paste this before the closing <code>{tag}</code> tag to track AI-referred visits.",
"copySnippet": "Copy tracking script",
- "exportError": "Failed to export CSV"
+ "exportError": "Failed to export CSV",
+ "sources": {
+ "label": "Data sources",
+ "snippet": "Tracking snippet",
+ "snippetActive": "Active · last visit {when}",
+ "snippetNotDetected": "Not detected",
+ "code": "Code",
+ "install": "Install",
+ "ga": "Google Analytics",
+ "gsc": "Google Search Console",
+ "bots": "AI bots",
+ "property": "{host} ({source})",
+ "synced": "{property} · synced {when}",
+ "syncingGa": "Syncing · first data in ~15 min",
+ "syncingGsc": "Syncing · first data in up to 48 h",
+ "notConnectedGa": "Not connected · see which AI visits convert",
+ "notConnectedGsc": "Not connected · see if AI is taking Google clicks",
+ "unmapped": "Connected · choose a property for this brand",
+ "notConfigured": "Not set up on this server",
+ "botsSoon": "Cloudflare / Vercel · coming soon",
+ "connect": "Connect",
+ "connecting": "Connecting…",
+ "manage": "Manage",
+ "connectNotAllowed": "Only admins and managers can connect a source."
+ }
},
"prompts": {
"positions": {
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx
new file mode 100644
index 000000000..a595190e1
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_snippet-code.tsx
@@ -0,0 +1,106 @@
+'use client';
+
+import { useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { Check, Code, Copy } from 'lucide-react';
+import { Card, CardContent } from '@/components/ui/card';
+import { Button } from '@/components/ui/button';
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
+import { getPublicApiBaseUrl } from '@/config/api';
+
+/** The tracking snippet tag for a brand, or null without a code or an API URL. */
+function snippetTag(trackingCode?: string): string | null {
+ const apiUrl = getPublicApiBaseUrl();
+ if (!trackingCode || !apiUrl) return null;
+ return `<script src="${apiUrl}/t.js" data-t="${trackingCode}" defer></script>`;
+}
+
+/** Where the tag goes, the tag, and a copy button. */
+function SnippetCode({ snippet }: { snippet: string }) {
+ const t = useTranslations('traffic');
+ const [copied, setCopied] = useState(false);
+
+ const handleCopy = () => {
+ navigator.clipboard.writeText(snippet);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <div className="flex items-start gap-3">
+ <div className="min-w-0 flex-1">
+ <p className="text-xs text-muted-foreground">
+ {t.rich('snippetDescription', {
+ tag: '</head>',
+ code: (chunks) => <code className="text-[11px]">{chunks}</code>,
+ })}
+ </p>
+ <pre className="mt-2 overflow-x-auto rounded-md bg-muted/50 px-3 py-2 font-mono text-[11px]">
+ {snippet}
+ </pre>
+ </div>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-8 w-8 shrink-0"
+ onClick={handleCopy}
+ aria-label={t('copySnippet')}
+ >
+ {copied ? (
+ <Check className="h-3.5 w-3.5 text-green-500" />
+ ) : (
+ <Copy className="h-3.5 w-3.5" />
+ )}
+ </Button>
+ </div>
+ );
+}
+
+/**
+ * The snippet's code, open on the page: only while the snippet hasn't sent a
+ * visit in the last week (AT-001). Once it has, the code sits behind the
+ * sources strip's Code button instead of staying at the top for good.
+ */
+export function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
+ const t = useTranslations('traffic');
+ const snippet = snippetTag(trackingCode);
+ if (!snippet) return null;
+
+ return (
+ <Card className="border-blue-500/20 bg-blue-500/5">
+ <CardContent className="flex items-start gap-3 px-4 py-3">
+ <Code className="mt-0.5 h-4 w-4 shrink-0 text-blue-500" />
+ <div className="min-w-0 flex-1">
+ <p className="mb-0.5 text-sm font-medium">{t('snippetTitle')}</p>
+ <SnippetCode snippet={snippet} />
+ </div>
+ </CardContent>
+ </Card>
+ );
+}
+
+/** The snippet's code in a dialog, from the sources strip's Code or Install button. */
+export function SnippetDialog({
+ trackingCode,
+ open,
+ onOpenChange,
+}: {
+ trackingCode?: string;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+}) {
+ const t = useTranslations('traffic');
+ const snippet = snippetTag(trackingCode);
+ if (!snippet) return null;
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="sm:max-w-2xl">
+ <DialogHeader>
+ <DialogTitle>{t('snippetTitle')}</DialogTitle>
+ </DialogHeader>
+ <SnippetCode snippet={snippet} />
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx
new file mode 100644
index 000000000..cca38c0de
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.test.tsx
@@ -0,0 +1,174 @@
+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 { SourceState } from '@/lib/actions/integrations';
+import type { TrafficSources } from '@/lib/actions/traffic';
+
+/**
+ * AT-001: the data sources strip says what feeds the page, what's missing,
+ * and connects a missing Google source without leaving it.
+ */
+
+const connect = vi.fn();
+vi.mock('@/hooks/use-integration-connect', () => ({
+ useIntegrationConnect: () => ({ connecting: false, connect }),
+}));
+vi.mock('@/i18n/navigation', () => ({
+ Link: ({ href, ...props }: { href: string }) => <a href={href} {...props} />,
+}));
+
+const { SourcesStrip } = await import('./_sources-strip');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+const hoursAgo = (h: number) => new Date(Date.now() - h * 3_600_000).toISOString();
+const source = (over: Partial<SourceState> = {}): SourceState => ({
+ configured: true,
+ connected: true,
+ mapped: true,
+ firstDataAt: hoursAgo(500),
+ lastDataAt: hoursAgo(2),
+ property: null,
+ ...over,
+});
+
+let container: HTMLDivElement;
+let root: Root;
+const onShowCode = vi.fn();
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+function render(sources: TrafficSources | null, { canConnect = true } = {}) {
+ act(() => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
+ <SourcesStrip
+ sources={sources}
+ domain="acme-coffee.example.com"
+ hasTrackingCode
+ canConnect={canConnect}
+ onShowCode={onShowCode}
+ onConnected={() => {}}
+ />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+/** Each card's title, sub-line and button, in order. */
+const cards = () =>
+ [...container.querySelectorAll('section > div')].map((card) => ({
+ title: card.querySelector('p')?.textContent,
+ line: card.querySelectorAll('p')[1]?.textContent,
+ button: card.querySelector('a, button')?.textContent ?? null,
+ }));
+
+describe('SourcesStrip', () => {
+ it('shows each connected source with its property and last sync', () => {
+ render({
+ snippetLastVisitAt: hoursAgo(1),
+ ga: source({ property: '123456789' }),
+ gsc: source({ property: 'sc-domain:acme-coffee.example.com', lastDataAt: hoursAgo(5) }),
+ });
+ expect(cards()).toEqual([
+ { title: 'Tracking snippet', line: 'Active · last visit 1h ago', button: 'Code' },
+ {
+ title: 'Google Analytics',
+ line: 'acme-coffee.example.com (GA4) · synced 2h ago',
+ button: 'Manage',
+ },
+ {
+ title: 'Google Search Console',
+ line: 'acme-coffee.example.com (GSC) · synced 5h ago',
+ button: 'Manage',
+ },
+ { title: 'AI bots', line: 'Cloudflare / Vercel · coming soon', button: null },
+ ]);
+ expect(container.querySelector('a')!.getAttribute('href')).toBe(
+ '/dashboard/settings?tab=integrations',
+ );
+ });
+
+ it('names a URL-prefix Search Console property by its host', () => {
+ render({
+ snippetLastVisitAt: hoursAgo(1),
+ ga: source(),
+ gsc: source({ property: 'https://blog.acme-coffee.example.com/' }),
+ });
+ expect(cards()[2].line).toBe('blog.acme-coffee.example.com (GSC) · synced 2h ago');
+ });
+
+ it('says how long the first sync takes, and what a missing source unlocks', () => {
+ render({
+ snippetLastVisitAt: null,
+ ga: source({ lastDataAt: null }),
+ gsc: source({ connected: false, mapped: false }),
+ });
+ expect(cards().slice(0, 3)).toEqual([
+ { title: 'Tracking snippet', line: 'Not detected', button: 'Install' },
+ { title: 'Google Analytics', line: 'Syncing · first data in ~15 min', button: 'Manage' },
+ {
+ title: 'Google Search Console',
+ line: 'Not connected · see if AI is taking Google clicks',
+ button: 'Connect',
+ },
+ ]);
+ });
+
+ it('connects from the strip, and opens the snippet code from its button', () => {
+ render({
+ snippetLastVisitAt: hoursAgo(1),
+ ga: source({ connected: false, mapped: false }),
+ gsc: source(),
+ });
+ const button = (name: string) =>
+ [...container.querySelectorAll('button')].find((b) => b.textContent === name)!;
+ act(() => button('Connect').click());
+ expect(connect).toHaveBeenCalledTimes(1);
+ act(() => button('Code').click());
+ expect(onShowCode).toHaveBeenCalledTimes(1);
+ });
+
+ it("keeps Connect off for members who can't connect", () => {
+ render(
+ { snippetLastVisitAt: null, ga: source({ connected: false }), gsc: source() },
+ { canConnect: false },
+ );
+ const connectButton = [...container.querySelectorAll('button')].find(
+ (b) => b.textContent === 'Connect',
+ )!;
+ expect(connectButton.disabled).toBe(true);
+ expect(connectButton.parentElement!.getAttribute('title')).toBe(
+ 'Only admins and managers can connect a source.',
+ );
+ });
+
+ it('asks for a property, or says the server has no Google keys', () => {
+ render({
+ snippetLastVisitAt: null,
+ ga: source({ mapped: false, lastDataAt: null }),
+ gsc: source({ configured: false, connected: false, mapped: false, lastDataAt: null }),
+ });
+ expect(cards().slice(1, 3)).toEqual([
+ {
+ title: 'Google Analytics',
+ line: 'Connected · choose a property for this brand',
+ button: 'Manage',
+ },
+ { title: 'Google Search Console', line: 'Not set up on this server', button: null },
+ ]);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx
new file mode 100644
index 000000000..3ef197665
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/_sources-strip.tsx
@@ -0,0 +1,221 @@
+'use client';
+
+import type { ReactNode } from 'react';
+import { useTranslations } from 'next-intl';
+import { Code, Loader2 } from 'lucide-react';
+import { Link } from '@/i18n/navigation';
+import { Button } from '@/components/ui/button';
+import { buttonVariants } from '@/components/ui/button-variants';
+import { Skeleton } from '@/components/ui/skeleton';
+import { cn } from '@/lib/utils';
+import { formatRelative } from '@/lib/format-relative';
+import { useIntegrationConnect } from '@/hooks/use-integration-connect';
+import type { IntegrationProvider, SourceState } from '@/lib/actions/integrations';
+import type { TrafficSources } from '@/lib/actions/traffic';
+import { googleSourceStatus, gscPropertyHost, snippetDetected } from '@/lib/traffic-sources';
+
+type Tone = 'on' | 'sync' | 'off';
+
+const DOT: Record<Tone, string> = {
+ on: 'bg-emerald-500',
+ sync: 'bg-amber-500',
+ off: 'bg-muted-foreground/30',
+};
+
+const SETTINGS_INTEGRATIONS = '/dashboard/settings?tab=integrations';
+
+/** One source: a status dot by the title, a sub-line, and its button. */
+function SourceCard({
+ tone,
+ title,
+ line,
+ action,
+}: {
+ tone: Tone;
+ title: string;
+ line: string;
+ action?: ReactNode;
+}) {
+ return (
+ <div className="flex min-w-0 items-start gap-2.5 bg-card px-4 py-3">
+ <span className={cn('mt-1.5 h-2 w-2 shrink-0 rounded-full', DOT[tone])} aria-hidden />
+ <div className="min-w-0 flex-1">
+ <p className="truncate text-[13px] font-semibold" title={title}>
+ {title}
+ </p>
+ <p className="line-clamp-2 text-xs text-muted-foreground">{line}</p>
+ </div>
+ {action && <div className="shrink-0 self-center">{action}</div>}
+ </div>
+ );
+}
+
+/**
+ * Google Analytics or Google Search Console: connected with its property and
+ * last sync, syncing with how long the first data takes, or a Connect that
+ * runs the Settings OAuth flow in a popup, here. Connections stay org-wide.
+ */
+function GoogleSource({
+ provider,
+ state,
+ domain,
+ canConnect,
+ onConnected,
+}: {
+ provider: IntegrationProvider;
+ state: SourceState;
+ domain: string | undefined;
+ canConnect: boolean;
+ onConnected: () => void;
+}) {
+ const t = useTranslations('traffic.sources');
+ const tCommon = useTranslations('common');
+ const isGa = provider === 'google-analytics';
+ const title = isGa ? t('ga') : t('gsc');
+ const { connecting, connect } = useIntegrationConnect(provider, {
+ label: title,
+ callbackUrl: () => window.location.href,
+ onStatus: (status) => {
+ if (status === 'connected') onConnected();
+ },
+ });
+
+ const manage = (
+ <Link
+ href={SETTINGS_INTEGRATIONS}
+ className={cn(buttonVariants({ variant: 'outline', size: 'sm' }), 'h-7 text-xs')}
+ >
+ {t('manage')}
+ </Link>
+ );
+
+ const status = googleSourceStatus(state);
+ if (status === 'connected' || status === 'syncing') {
+ const host =
+ (!isGa && state.property ? gscPropertyHost(state.property) : domain) ?? state.property;
+ return (
+ <SourceCard
+ tone={status === 'connected' ? 'on' : 'sync'}
+ title={title}
+ line={
+ status === 'connected'
+ ? t('synced', {
+ property: t('property', { host: host ?? '', source: isGa ? 'GA4' : 'GSC' }),
+ when: formatRelative(state.lastDataAt, tCommon),
+ })
+ : isGa
+ ? t('syncingGa')
+ : t('syncingGsc')
+ }
+ action={manage}
+ />
+ );
+ }
+ if (status === 'unmapped') {
+ return <SourceCard tone="off" title={title} line={t('unmapped')} action={manage} />;
+ }
+ if (status === 'not_configured') {
+ return <SourceCard tone="off" title={title} line={t('notConfigured')} />;
+ }
+ return (
+ <SourceCard
+ tone="off"
+ title={title}
+ line={isGa ? t('notConnectedGa') : t('notConnectedGsc')}
+ action={
+ // A span carries the tooltip: a disabled button gets no hover.
+ <span title={canConnect ? undefined : t('connectNotAllowed')}>
+ <Button
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ disabled={!canConnect || connecting}
+ onClick={() => void connect()}
+ >
+ {connecting && <Loader2 className="h-3 w-3 animate-spin" />}
+ {connecting ? t('connecting') : t('connect')}
+ </Button>
+ </span>
+ }
+ />
+ );
+}
+
+/**
+ * The data sources strip (AT-001): what feeds the page — the tracking
+ * snippet, Google Analytics, Google Search Console and AI bots — and what's
+ * missing, with a way to connect it without leaving the page (fixes F8).
+ * The snippet's code moves behind its Code button once it sends visits
+ * (F3). AI bots come with phase 3 (AT-010), so that card says so for now.
+ */
+export function SourcesStrip({
+ sources,
+ domain,
+ hasTrackingCode,
+ canConnect,
+ onShowCode,
+ onConnected,
+}: {
+ /** Null while loading. */
+ sources: TrafficSources | null;
+ /** The brand's primary domain, for the GA4 property line. */
+ domain: string | undefined;
+ hasTrackingCode: boolean;
+ canConnect: boolean;
+ onShowCode: () => void;
+ onConnected: () => void;
+}) {
+ const t = useTranslations('traffic.sources');
+ const tCommon = useTranslations('common');
+
+ if (!sources) {
+ return <Skeleton className="h-[62px] w-full rounded-xl" />;
+ }
+
+ const detected = snippetDetected(sources.snippetLastVisitAt);
+ return (
+ <section
+ aria-label={t('label')}
+ // The 1px gaps over the border colour draw the lines between cards, in
+ // one row of four on a wide screen and two by two below it.
+ className="grid gap-px overflow-hidden rounded-xl border bg-border sm:grid-cols-2 min-[75rem]:grid-cols-4"
+ >
+ <SourceCard
+ tone={detected ? 'on' : 'off'}
+ title={t('snippet')}
+ line={
+ detected
+ ? t('snippetActive', { when: formatRelative(sources.snippetLastVisitAt, tCommon) })
+ : t('snippetNotDetected')
+ }
+ action={
+ hasTrackingCode ? (
+ <Button
+ variant={detected ? 'outline' : 'default'}
+ size="sm"
+ className="h-7 gap-1.5 text-xs"
+ onClick={onShowCode}
+ >
+ <Code className="h-3 w-3" />
+ {detected ? t('code') : t('install')}
+ </Button>
+ ) : undefined
+ }
+ />
+ <GoogleSource
+ provider="google-analytics"
+ state={sources.ga}
+ domain={domain}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ />
+ <GoogleSource
+ provider="google-search-console"
+ state={sources.gsc}
+ domain={domain}
+ canConnect={canConnect}
+ onConnected={onConnected}
+ />
+ <SourceCard tone="off" title={t('bots')} line={t('botsSoon')} />
+ </section>
+ );
+}
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
index 3f2cb2065..a93c66d4b 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/traffic/page.tsx
@@ -5,7 +5,6 @@ import { getPlatformFilterItems } from './_charts';
import { getPlatformName } from '@/lib/traffic-platforms';
import dynamic from 'next/dynamic';
import { Skeleton } from '@/components/ui/skeleton';
-import { getPublicApiBaseUrl } from '@/config/api';
const ReferralTrendChart = dynamic(() => import('./_charts').then((m) => m.ReferralTrendChart), {
ssr: false,
loading: () => <Skeleton className="h-64 w-full" />,
@@ -22,9 +21,11 @@ import { useTranslations } from 'next-intl';
import { useBrandStore } from '@/stores/use-brand-store';
import type { Brand } from '@/types';
import {
+ getTrafficSources,
getTrafficSummary,
getTrafficTrend,
getTrafficLogs,
+ type TrafficSources,
type TrafficSummary,
type TrafficTrendPoint,
type TrafficLog,
@@ -36,6 +37,10 @@ import {
type DateRangePreset,
} from '@/components/filters/date-range-filter';
import { PageOpportunitiesCard } from './_opportunities-card';
+import { SourcesStrip } from './_sources-strip';
+import { SnippetBanner, SnippetDialog } from './_snippet-code';
+import { snippetDetected } from '@/lib/traffic-sources';
+import { useUserRole } from '@/hooks/use-user-role';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import {
@@ -52,9 +57,6 @@ import {
TrendingDown,
Users,
LayoutList,
- Code,
- Copy,
- Check,
Search,
X,
Loader2,
@@ -156,56 +158,6 @@ function DeltaBadge({ current, previous }: { current: number; previous: number }
);
}
-function SnippetBanner({ trackingCode }: { trackingCode?: string }) {
- const t = useTranslations('traffic');
- const [copied, setCopied] = useState(false);
- const apiUrl = getPublicApiBaseUrl();
- const snippet = `<script src="${apiUrl}/t.js" data-t="${trackingCode || 'YOUR_TRACKING_CODE'}" defer></script>`;
-
- if (!trackingCode || !apiUrl) return null;
-
- const handleCopy = () => {
- navigator.clipboard.writeText(snippet);
- setCopied(true);
- setTimeout(() => setCopied(false), 2000);
- };
-
- return (
- <Card className="border-blue-500/20 bg-blue-500/5">
- <CardContent className="py-3 px-4 flex items-start gap-3">
- <Code className="h-4 w-4 mt-0.5 shrink-0 text-blue-500" />
- <div className="flex-1 min-w-0">
- <p className="text-sm font-medium">{t('snippetTitle')}</p>
- <p className="text-xs text-muted-foreground mt-0.5">
- {t.rich('snippetDescription', {
- tag: '</head>',
- code: (chunks) => <code className="text-[11px]">{chunks}</code>,
- })}
- </p>
- <div className="mt-2 relative">
- <pre className="text-[11px] bg-muted/50 rounded-md px-3 py-2 overflow-x-auto font-mono">
- {snippet}
- </pre>
- </div>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="shrink-0 h-8 w-8"
- onClick={handleCopy}
- aria-label={t('copySnippet')}
- >
- {copied ? (
- <Check className="h-3.5 w-3.5 text-green-500" />
- ) : (
- <Copy className="h-3.5 w-3.5" />
- )}
- </Button>
- </CardContent>
- </Card>
- );
-}
-
// ─── Filter Bar ───────────────────────────────────────────────────────────────
interface TrafficFilters {
@@ -476,6 +428,26 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
const [isLoadingSummary, setIsLoadingSummary] = useState(true);
const [isLoadingLogs, setIsLoadingLogs] = useState(false);
const [isExporting, setIsExporting] = useState(false);
+ // What feeds the page (AT-001); null while it loads.
+ const [sources, setSources] = useState<TrafficSources | null>(null);
+ // A failed read hides the strip and leaves the snippet code open, as before it.
+ const [sourcesFailed, setSourcesFailed] = useState(false);
+ const [codeOpen, setCodeOpen] = useState(false);
+ const { canManage } = useUserRole();
+
+ const loadSources = useCallback(async () => {
+ try {
+ setSources(await getTrafficSources(brand.id));
+ setSourcesFailed(false);
+ } catch (err) {
+ console.error('Failed to load traffic sources:', err);
+ setSourcesFailed(true);
+ }
+ }, [brand.id]);
+
+ useEffect(() => {
+ void loadSources();
+ }, [loadSources]);
const [filters, setFilters] = useState<TrafficFilters>({ platform: '', search: '' });
const [searchInput, setSearchInput] = useState(filters.search);
@@ -669,8 +641,21 @@ function TrafficPageContent({ brand }: { brand: Brand }) {
</div>
</div>
- {/* Snippet Banner */}
- <SnippetBanner trackingCode={brand.trackingCode} />
+ {!sourcesFailed && (
+ <SourcesStrip
+ sources={sources}
+ domain={primaryDomain}
+ hasTrackingCode={Boolean(brand.trackingCode)}
+ canConnect={canManage}
+ onShowCode={() => setCodeOpen(true)}
+ onConnected={() => void loadSources()}
+ />
+ )}
+ {/* The code stays open only while the snippet sends nothing (F3). */}
+ {(sourcesFailed || (sources && !snippetDetected(sources.snippetLastVisitAt))) && (
+ <SnippetBanner trackingCode={brand.trackingCode} />
+ )}
+ <SnippetDialog trackingCode={brand.trackingCode} open={codeOpen} onOpenChange={setCodeOpen} />
{trulyEmpty ? (
<Card>
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index 25468dba2..785b66ce6 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -27,7 +27,6 @@ import { BarChart3, Loader2, Search, Unplug } from 'lucide-react';
import { useTranslations } from 'next-intl';
import {
getIntegrationStatus,
- connectIntegration,
disconnectIntegration,
getGscProperties,
getGscBrandMappings,
@@ -39,6 +38,7 @@ import {
type IntegrationStatus,
} from '@/lib/actions/integrations';
import { matchProperty } from '@/lib/property-match';
+import { useIntegrationConnect } from '@/hooks/use-integration-connect';
/**
* Settings → Integrations (#577, Google Analytics added in #658).
@@ -102,9 +102,12 @@ function IntegrationCard({
}) {
const t = useTranslations('settings');
const [status, setStatus] = useState<IntegrationStatus | null>(null);
- const [connecting, setConnecting] = useState(false);
const [disconnecting, setDisconnecting] = useState(false);
- const pollGen = useRef(0);
+ const { connecting, connect: handleConnect } = useIntegrationConnect(provider, {
+ label,
+ callbackUrl: () => `${window.location.origin}/dashboard/settings?tab=integrations`,
+ onStatus: setStatus,
+ });
const load = useCallback(async () => {
try {
@@ -119,64 +122,8 @@ function IntegrationCard({
useEffect(() => {
load();
- // Stop any in-flight poll when the card unmounts.
- const gen = pollGen.current;
- return () => {
- if (pollGen.current === gen) pollGen.current++;
- };
}, [load]);
- const handleConnect = async () => {
- setConnecting(true);
- const gen = ++pollGen.current;
- try {
- const callbackUrl = `${window.location.origin}/dashboard/settings?tab=integrations`;
- const { redirectUrl } = await connectIntegration(provider, callbackUrl);
-
- const popup = window.open(redirectUrl, `${provider}-oauth`, 'width=560,height=720');
- if (!popup) {
- // Popup blocked — same-tab fallback; status resolves on return.
- window.location.href = redirectUrl;
- return;
- }
-
- // Poll until Composio reports the account ACTIVE (or ~2 min pass).
- const deadline = Date.now() + 120_000;
- while (Date.now() < deadline && pollGen.current === gen) {
- await new Promise((r) => setTimeout(r, 3000));
- if (pollGen.current !== gen) return;
- try {
- const result = await getIntegrationStatus(provider);
- if (result.status === 'connected') {
- setStatus('connected');
- toast.success(`${label} connected`);
- popup.close();
- return;
- }
- } catch {
- // transient — keep polling until the deadline
- }
- if (popup.closed) {
- // User closed the window — one final check, then give up quietly.
- const result = await getIntegrationStatus(provider).catch(() => null);
- if (pollGen.current !== gen) return;
- setStatus(result?.status ?? 'not_connected');
- if (result?.status === 'connected') {
- toast.success(`${label} connected`);
- }
- return;
- }
- }
- if (pollGen.current === gen) {
- toast.error('Connection timed out — try again.');
- }
- } catch (err) {
- toast.error(err instanceof Error ? err.message : 'Failed to start connection');
- } finally {
- if (pollGen.current === gen) setConnecting(false);
- }
- };
-
const handleDisconnect = async () => {
setDisconnecting(true);
try {
diff --git a/web/src/hooks/use-integration-connect.test.tsx b/web/src/hooks/use-integration-connect.test.tsx
new file mode 100644
index 000000000..f7b91b329
--- /dev/null
+++ b/web/src/hooks/use-integration-connect.test.tsx
@@ -0,0 +1,108 @@
+import { act, useEffect } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+/**
+ * The OAuth popup flow shared by Settings › Integrations and AI Traffic's
+ * sources strip: open the popup, poll until the account is connected, and
+ * stop once the caller is gone.
+ */
+
+const actions = vi.hoisted(() => ({
+ connectIntegration: vi.fn(),
+ getIntegrationStatus: vi.fn(),
+}));
+vi.mock('@/lib/actions/integrations', () => actions);
+vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));
+
+const { useIntegrationConnect } = await import('./use-integration-connect');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+const harness: { connect?: () => Promise<void> } = {};
+const connect = () => harness.connect!();
+const onStatus = vi.fn();
+const popup = { closed: false, close: vi.fn() };
+
+function Harness() {
+ const { connect: start } = useIntegrationConnect('google-analytics', {
+ label: 'Google Analytics',
+ callbackUrl: () => 'https://app.example/dashboard/traffic',
+ onStatus,
+ });
+ useEffect(() => {
+ harness.connect = start;
+ });
+ return null;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ vi.clearAllMocks();
+ popup.closed = false;
+ actions.connectIntegration.mockResolvedValue({ redirectUrl: 'https://oauth.example/start' });
+ vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);
+ container = document.createElement('div');
+ root = createRoot(container);
+ act(() => root.render(<Harness />));
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ vi.useRealTimers();
+});
+
+describe('useIntegrationConnect', () => {
+ it('opens the popup at the OAuth URL and reports the account once connected', async () => {
+ actions.getIntegrationStatus
+ .mockResolvedValueOnce({ status: 'not_connected' })
+ .mockResolvedValueOnce({ status: 'connected' });
+ let done!: Promise<void>;
+ act(() => {
+ done = connect();
+ });
+ await act(async () => void (await vi.advanceTimersByTimeAsync(6000)));
+ await done;
+
+ expect(actions.connectIntegration).toHaveBeenCalledWith(
+ 'google-analytics',
+ 'https://app.example/dashboard/traffic',
+ );
+ expect(window.open).toHaveBeenCalledWith(
+ 'https://oauth.example/start',
+ 'google-analytics-oauth',
+ 'width=560,height=720',
+ );
+ expect(onStatus).toHaveBeenCalledWith('connected');
+ expect(popup.close).toHaveBeenCalled();
+ });
+
+ it('reports the final status when the user closes the popup', async () => {
+ actions.getIntegrationStatus.mockResolvedValue({ status: 'not_connected' });
+ let done!: Promise<void>;
+ act(() => {
+ done = connect();
+ });
+ popup.closed = true;
+ await act(async () => void (await vi.advanceTimersByTimeAsync(3000)));
+ await done;
+ expect(onStatus).toHaveBeenCalledWith('not_connected');
+ });
+
+ it('stops polling once its caller is gone', async () => {
+ actions.getIntegrationStatus.mockResolvedValue({ status: 'not_connected' });
+ act(() => {
+ void connect();
+ });
+ await act(async () => void (await vi.advanceTimersByTimeAsync(10)));
+ act(() => root.unmount());
+ actions.getIntegrationStatus.mockResolvedValue({ status: 'connected' });
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(onStatus).not.toHaveBeenCalled();
+ // Re-mount for afterEach's unmount.
+ root = createRoot(container);
+ });
+});
diff --git a/web/src/hooks/use-integration-connect.ts b/web/src/hooks/use-integration-connect.ts
new file mode 100644
index 000000000..9221b8cb6
--- /dev/null
+++ b/web/src/hooks/use-integration-connect.ts
@@ -0,0 +1,99 @@
+'use client';
+
+import { useEffect, useRef, useState } from 'react';
+import { toast } from 'sonner';
+import {
+ connectIntegration,
+ getIntegrationStatus,
+ type IntegrationProvider,
+ type IntegrationStatus,
+} from '@/lib/actions/integrations';
+
+/** How long the popup flow waits for Composio to report the account (#577). */
+const CONNECT_DEADLINE_MS = 120_000;
+const CONNECT_POLL_MS = 3000;
+
+/**
+ * Connect a Google integration in an OAuth popup, polling until Composio
+ * reports the account connected. Shared by Settings › Integrations and AI
+ * Traffic's data sources strip, so the user connects from where they are
+ * and never leaves the page. A blocked popup falls back to the same tab,
+ * and `callbackUrl` is where Composio sends them back.
+ *
+ * `onStatus` hears the outcome: 'connected', or whatever the final check
+ * said once the user closed the popup. An unmounted caller stops polling.
+ */
+export function useIntegrationConnect(
+ provider: IntegrationProvider,
+ {
+ label,
+ callbackUrl,
+ onStatus,
+ }: {
+ label: string;
+ callbackUrl: () => string;
+ onStatus: (status: IntegrationStatus) => void;
+ },
+) {
+ const [connecting, setConnecting] = useState(false);
+ // Bumped to stop a poll: a newer attempt, or the caller unmounting.
+ const pollGen = useRef(0);
+
+ useEffect(() => {
+ const gens = pollGen;
+ return () => {
+ gens.current++;
+ };
+ }, []);
+
+ const connect = async () => {
+ setConnecting(true);
+ const gen = ++pollGen.current;
+ try {
+ const { redirectUrl } = await connectIntegration(provider, callbackUrl());
+
+ const popup = window.open(redirectUrl, `${provider}-oauth`, 'width=560,height=720');
+ if (!popup) {
+ // Popup blocked — same-tab fallback; status resolves on return.
+ window.location.href = redirectUrl;
+ return;
+ }
+
+ const deadline = Date.now() + CONNECT_DEADLINE_MS;
+ while (Date.now() < deadline && pollGen.current === gen) {
+ await new Promise((r) => setTimeout(r, CONNECT_POLL_MS));
+ if (pollGen.current !== gen) return;
+ try {
+ const result = await getIntegrationStatus(provider);
+ if (result.status === 'connected') {
+ onStatus('connected');
+ toast.success(`${label} connected`);
+ popup.close();
+ return;
+ }
+ } catch {
+ // transient — keep polling until the deadline
+ }
+ if (popup.closed) {
+ // User closed the window — one final check, then give up quietly.
+ const result = await getIntegrationStatus(provider).catch(() => null);
+ if (pollGen.current !== gen) return;
+ onStatus(result?.status ?? 'not_connected');
+ if (result?.status === 'connected') {
+ toast.success(`${label} connected`);
+ }
+ return;
+ }
+ }
+ if (pollGen.current === gen) {
+ toast.error('Connection timed out — try again.');
+ }
+ } catch (err) {
+ toast.error(err instanceof Error ? err.message : 'Failed to start connection');
+ } finally {
+ if (pollGen.current === gen) setConnecting(false);
+ }
+ };
+
+ return { connecting, connect };
+}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index 94a577748..ae80ca408 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -62,6 +62,14 @@ export interface SourceState {
* synced yet. Suggestions generated before it could not draw on the source.
*/
firstDataAt: string | null;
+ /**
+ * When the brand's newest day of data landed: the last sync that brought
+ * anything. Read from the latest date's row, which the (brand, date) index
+ * finds at once; a sync only inserts new days, so it's when that ran.
+ */
+ lastDataAt: string | null;
+ /** The brand's property: a GSC property ("sc-domain:…" or a URL) or a GA4 property id. */
+ property: string | null;
}
export interface SuggestionSourceStates {
@@ -88,7 +96,16 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
.limit(1)
.maybeSingle();
- const [configRes, brandRes, connRes, gscFirst, gaFirst] = await Promise.all([
+ const latestRow = (table: 'gsc_query_stats' | 'ga_page_stats') =>
+ supabase
+ .from(table)
+ .select('created_at')
+ .eq('brand_id', brandId)
+ .order('date', { ascending: false })
+ .limit(1)
+ .maybeSingle();
+
+ const [configRes, brandRes, connRes, gscFirst, gaFirst, gscLast, gaLast] = await Promise.all([
fetch(`${API_BASE_URL}/api/integrations/config`, {
headers: await authHeaders(),
cache: 'no-store',
@@ -99,6 +116,8 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
supabase.from('integration_connections').select('provider, status'),
firstRow('gsc_query_stats'),
firstRow('ga_page_stats'),
+ latestRow('gsc_query_stats'),
+ latestRow('ga_page_stats'),
]);
const connected = new Set(
@@ -111,12 +130,16 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges
connected: connected.has('google-search-console'),
mapped: Boolean(brandRes.data?.gsc_property),
firstDataAt: gscFirst.data?.created_at ?? null,
+ lastDataAt: gscLast.data?.created_at ?? null,
+ property: brandRes.data?.gsc_property ?? null,
},
ga: {
configured: Boolean(configRes.googleAnalytics),
connected: connected.has('google-analytics'),
mapped: Boolean(brandRes.data?.ga_property_id),
firstDataAt: gaFirst.data?.created_at ?? null,
+ lastDataAt: gaLast.data?.created_at ?? null,
+ property: brandRes.data?.ga_property_id ?? null,
},
dataForSeo: { configured: Boolean(configRes.dataForSeo) },
};
diff --git a/web/src/lib/actions/traffic.ts b/web/src/lib/actions/traffic.ts
index 3ee28ad30..e8cfee46d 100644
--- a/web/src/lib/actions/traffic.ts
+++ b/web/src/lib/actions/traffic.ts
@@ -2,6 +2,7 @@
import { createClient } from '@/lib/supabase/server';
import { expandDateToEndOfDay } from '@/lib/dates';
+import { getSuggestionSourceStates, type SourceState } from '@/lib/actions/integrations';
export interface TrafficDateWindow {
dateFrom?: string;
@@ -33,6 +34,39 @@ export interface TrafficTrendPoint {
[platform: string]: string | number;
}
+/** What feeds the page, for the data sources strip (AT-001). */
+export interface TrafficSources {
+ /** The snippet's newest visit, or null when it has never sent one. */
+ snippetLastVisitAt: string | null;
+ ga: SourceState;
+ gsc: SourceState;
+}
+
+/**
+ * The tracking snippet, Google Analytics and Google Search Console as the
+ * strip shows them, in one call: the snippet's last visit beside each
+ * Google source's connection, the brand's property and its last sync.
+ */
+export async function getTrafficSources(brandId: string): Promise<TrafficSources> {
+ const supabase = await createClient();
+ const [states, lastVisit] = await Promise.all([
+ getSuggestionSourceStates(brandId),
+ supabase
+ .from('ai_traffic_logs')
+ .select('created_at')
+ .eq('brand_id', brandId)
+ .order('created_at', { ascending: false })
+ .limit(1)
+ .maybeSingle(),
+ ]);
+ if (lastVisit.error) throw new Error(lastVisit.error.message);
+ return {
+ snippetLastVisitAt: (lastVisit.data?.created_at as string | undefined) ?? null,
+ ga: states.ga,
+ gsc: states.gsc,
+ };
+}
+
function mapLogRow(row: Record<string, unknown>): TrafficLog {
return {
id: row.id as string,
diff --git a/web/src/lib/traffic-sources.test.ts b/web/src/lib/traffic-sources.test.ts
new file mode 100644
index 000000000..43fa46461
--- /dev/null
+++ b/web/src/lib/traffic-sources.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from 'vitest';
+import { googleSourceStatus, gscPropertyHost, snippetDetected } from './traffic-sources';
+
+const NOW = Date.parse('2026-10-18T12:00:00Z');
+const daysAgo = (d: number) => new Date(NOW - d * 86_400_000).toISOString();
+
+describe('snippetDetected', () => {
+ it('counts a visit in the last 7 days', () => {
+ expect(snippetDetected(daysAgo(0.1), NOW)).toBe(true);
+ expect(snippetDetected(daysAgo(6.9), NOW)).toBe(true);
+ });
+
+ it('reads an older last visit, or none, as not detected', () => {
+ expect(snippetDetected(daysAgo(7.1), NOW)).toBe(false);
+ expect(snippetDetected(null, NOW)).toBe(false);
+ });
+});
+
+describe('googleSourceStatus', () => {
+ const ready = { configured: true, connected: true, mapped: true, lastDataAt: daysAgo(0.1) };
+
+ it('is connected once data has arrived, syncing until then', () => {
+ expect(googleSourceStatus(ready)).toBe('connected');
+ expect(googleSourceStatus({ ...ready, lastDataAt: null })).toBe('syncing');
+ });
+
+ it('asks for a property when connected without one for the brand', () => {
+ expect(googleSourceStatus({ ...ready, mapped: false, lastDataAt: null })).toBe('unmapped');
+ });
+
+ it('is not connected, or not set up on a server without the keys', () => {
+ expect(googleSourceStatus({ ...ready, connected: false })).toBe('not_connected');
+ expect(googleSourceStatus({ ...ready, configured: false, connected: false })).toBe(
+ 'not_configured',
+ );
+ });
+});
+
+describe('gscPropertyHost', () => {
+ it('names a domain property by its domain, without "sc-domain:"', () => {
+ expect(gscPropertyHost('sc-domain:ansvisor.com')).toBe('ansvisor.com');
+ });
+
+ it('names a URL-prefix property by its host', () => {
+ expect(gscPropertyHost('https://blog.ansvisor.com/')).toBe('blog.ansvisor.com');
+ });
+
+ it('leaves anything else as it is', () => {
+ expect(gscPropertyHost('ansvisor.com')).toBe('ansvisor.com');
+ });
+});
diff --git a/web/src/lib/traffic-sources.ts b/web/src/lib/traffic-sources.ts
new file mode 100644
index 000000000..53e90793d
--- /dev/null
+++ b/web/src/lib/traffic-sources.ts
@@ -0,0 +1,53 @@
+/**
+ * The AI Traffic page's data sources strip (AT-001): which state each source
+ * is in, and how a Google property is named on it.
+ */
+
+/** A snippet with no visit for this long reads as not detected, and its code box opens. */
+export const SNIPPET_ACTIVE_DAYS = 7;
+
+const DAY_MS = 86_400_000;
+
+/** Whether the snippet has sent a visit in the last week. */
+export function snippetDetected(lastVisitAt: string | null, now = Date.now()): boolean {
+ if (!lastVisitAt) return false;
+ return now - new Date(lastVisitAt).getTime() < SNIPPET_ACTIVE_DAYS * DAY_MS;
+}
+
+/**
+ * A Google source's state: green once data has arrived, amber while the
+ * first sync runs, grey otherwise. "Unmapped" is connected with no property
+ * picked for this brand yet; "not configured" is a server without the keys
+ * to connect at all (self-hosted without Composio).
+ */
+export type GoogleSourceStatus =
+ | 'connected'
+ | 'syncing'
+ | 'unmapped'
+ | 'not_connected'
+ | 'not_configured';
+
+export function googleSourceStatus(source: {
+ configured: boolean;
+ connected: boolean;
+ mapped: boolean;
+ lastDataAt: string | null;
+}): GoogleSourceStatus {
+ if (!source.configured) return 'not_configured';
+ if (!source.connected) return 'not_connected';
+ if (!source.mapped) return 'unmapped';
+ return source.lastDataAt ? 'connected' : 'syncing';
+}
+
+/**
+ * A Search Console property as the strip names it: the plain domain, never
+ * "sc-domain:", and a URL-prefix property by its host.
+ */
+export function gscPropertyHost(property: string): string {
+ if (property.startsWith('sc-domain:')) return property.slice('sc-domain:'.length);
+ try {
+ return new URL(property).host;
+ } catch {
+ return property;
+ }
+}