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(integrations): connect Google Analytics via Composio (#695)

Gökhan Geyikb0a24a49f908
diff --git a/server/.env.example b/server/.env.example
index 9a3d0d915..9796cb1db 100644
--- a/server/.env.example
+++ b/server/.env.example
@@ -88,9 +88,12 @@ AI_VOLUME_MULTIPLIER=0.15
# Composio managed auth (Settings → Integrations, #577). Optional — without
-# these the Integrations card shows "not configured" and everything else works.
+# these the Integrations cards show "not configured" and everything else works.
+# Each provider needs the shared API key plus its own auth config id, so
+# configuring one never implies the other is available.
# COMPOSIO_API_KEY=
# COMPOSIO_GSC_AUTH_CONFIG_ID=
+# COMPOSIO_GA_AUTH_CONFIG_ID=
# Pinned Search Console toolkit version for tool execution (optional override)
# COMPOSIO_GSC_TOOLKIT_VERSION=20260721_00
diff --git a/server/src/lib/composio.js b/server/src/lib/composio.js
index c75a5a5eb..7f3ce9aea 100644
--- a/server/src/lib/composio.js
+++ b/server/src/lib/composio.js
@@ -1,17 +1,54 @@
import { Composio } from '@composio/core';
/**
- * Composio managed-auth helper (#577). Composio's verified Google app runs
- * the OAuth consent flow and stores the tokens — we only ever hold the
- * connected-account id. Self-host installs without the env vars stay fully
- * functional: isComposioConfigured() gates every route and the UI renders a
- * "not configured" card instead of erroring.
+ * Composio managed-auth helper (#577, extended for Google Analytics in #658).
+ * Composio's verified Google app runs the OAuth consent flow and stores the
+ * tokens — we only ever hold the connected-account id. Self-host installs
+ * without the env vars stay fully functional: isComposioConfigured() gates
+ * every route and the UI renders a "not configured" card instead of erroring.
+ *
+ * Providers are described by the map below rather than by copy-pasted
+ * functions: the connect / status / disconnect flow is identical for every
+ * OAuth source, so only the auth-config env var differs. Provider-specific
+ * behaviour (listing GSC properties, querying analytics) stays in its own
+ * function further down.
*/
let client = null;
-export function isComposioConfigured() {
- return Boolean(process.env.COMPOSIO_API_KEY && process.env.COMPOSIO_GSC_AUTH_CONFIG_ID);
+/**
+ * Supported integration providers. The key is the public identifier used in
+ * API routes, the `integration_connections.provider` column and the UI.
+ */
+export const PROVIDERS = {
+ 'google-search-console': {
+ label: 'Google Search Console',
+ authConfigEnv: 'COMPOSIO_GSC_AUTH_CONFIG_ID',
+ },
+ 'google-analytics': {
+ label: 'Google Analytics',
+ authConfigEnv: 'COMPOSIO_GA_AUTH_CONFIG_ID',
+ },
+};
+
+export function isKnownProvider(provider) {
+ return Object.hasOwn(PROVIDERS, provider);
+}
+
+function authConfigId(provider) {
+ const config = PROVIDERS[provider];
+ if (!config) throw new Error(`Unknown integration provider: ${provider}`);
+ return process.env[config.authConfigEnv];
+}
+
+/**
+ * A provider is usable only when the API key AND its own auth config are
+ * present — one provider being configured must never imply the other is.
+ */
+export function isComposioConfigured(provider) {
+ if (!process.env.COMPOSIO_API_KEY) return false;
+ if (!isKnownProvider(provider)) return false;
+ return Boolean(authConfigId(provider));
}
function getClient() {
@@ -21,16 +58,12 @@ function getClient() {
return client;
}
-function gscAuthConfigId() {
- return process.env.COMPOSIO_GSC_AUTH_CONFIG_ID;
-}
-
/**
* Start the hosted OAuth flow for an entity. Returns the URL the client
* opens in a popup plus the pending connected-account id.
*/
-export async function initiateGscConnection(entityId, callbackUrl) {
- const request = await getClient().connectedAccounts.link(entityId, gscAuthConfigId(), {
+export async function initiateConnection(provider, entityId, callbackUrl) {
+ const request = await getClient().connectedAccounts.link(entityId, authConfigId(provider), {
callbackUrl,
});
return {
@@ -40,17 +73,17 @@ export async function initiateGscConnection(entityId, callbackUrl) {
};
}
-/** The entity's ACTIVE Search Console connection on Composio, or null. */
-export async function getActiveGscConnection(entityId) {
+/** The entity's ACTIVE connection for this provider on Composio, or null. */
+export async function getActiveConnection(provider, entityId) {
const connections = await getClient().connectedAccounts.list({
- authConfigIds: [gscAuthConfigId()],
+ authConfigIds: [authConfigId(provider)],
userIds: [entityId],
statuses: ['ACTIVE'],
});
return connections.items?.[0] ?? null;
}
-export async function deleteGscConnection(connectedAccountId) {
+export async function deleteConnection(connectedAccountId) {
await getClient().connectedAccounts.delete(connectedAccountId);
}
diff --git a/server/src/lib/gsc-sync.js b/server/src/lib/gsc-sync.js
index 425d23f12..1b742659f 100644
--- a/server/src/lib/gsc-sync.js
+++ b/server/src/lib/gsc-sync.js
@@ -89,7 +89,7 @@ async function syncBrand(brand) {
* manual trigger). Returns per-brand counts.
*/
export async function runGscSync({ organizationId } = {}) {
- if (!isComposioConfigured()) return { synced: 0, skipped: 0, results: [] };
+ if (!isComposioConfigured('google-search-console')) return { synced: 0, skipped: 0, results: [] };
// Orgs with a live connection…
let connQuery = supabaseAdmin
diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.js
index dc3d2df80..4327f677c 100644
--- a/server/src/routes/integrations.js
+++ b/server/src/routes/integrations.js
@@ -1,20 +1,22 @@
import { Router } from 'express';
import supabaseAdmin from '../config/supabase.js';
import {
+ PROVIDERS,
+ isKnownProvider,
isComposioConfigured,
- initiateGscConnection,
- getActiveGscConnection,
- deleteGscConnection,
+ initiateConnection,
+ getActiveConnection,
+ deleteConnection,
listGscSites,
} from '../lib/composio.js';
import { runGscSync } from '../lib/gsc-sync.js';
const router = Router();
-const PROVIDER = 'google-search-console';
+const GSC = 'google-search-console';
const WRITE_ROLES = ['admin', 'manager'];
-/** Entity id: one Search Console connection per organization (#577). */
+/** Entity id: one connection per organization per provider (#577). */
function entityIdFor(organizationId) {
return `org_${organizationId}`;
}
@@ -34,11 +36,11 @@ async function getProfile(userId) {
return profile;
}
-async function upsertConnectionRow(organizationId, fields) {
+async function upsertConnectionRow(organizationId, provider, fields) {
const { error } = await supabaseAdmin.from('integration_connections').upsert(
{
organization_id: organizationId,
- provider: PROVIDER,
+ provider,
updated_at: new Date().toISOString(),
...fields,
},
@@ -48,22 +50,48 @@ async function upsertConnectionRow(organizationId, fields) {
}
/**
- * GET /api/integrations/google-search-console/status
+ * Resolve `:provider` and reject anything unknown before it reaches Composio.
+ * Keeps the URL space closed — only providers declared in PROVIDERS exist.
+ */
+function resolveProvider(req, res) {
+ const { provider } = req.params;
+ if (!isKnownProvider(provider)) {
+ res.status(404).json({ error: 'Unknown integration provider.' });
+ return null;
+ }
+ return provider;
+}
+
+function notConfigured(res, provider) {
+ return res
+ .status(503)
+ .json({ error: `${PROVIDERS[provider].label} integration is not configured.` });
+}
+
+// ─── Shared connect / status / disconnect ────────────────────────────────────
+// Identical for every OAuth provider; only the auth config differs, which
+// lives in the PROVIDERS map.
+
+/**
+ * GET /api/integrations/:provider/status
* Resolves the live state against Composio (not just our stored row) and
* syncs the row so teammates see the same state.
*/
-router.get('/google-search-console/status', async (req, res) => {
+router.get('/:provider/status', async (req, res) => {
try {
- if (!isComposioConfigured()) {
+ const provider = resolveProvider(req, res);
+ if (!provider) return;
+
+ if (!isComposioConfigured(provider)) {
return res.json({ configured: false, status: 'not_configured' });
}
const profile = await getProfile(req.user.id);
const entityId = entityIdFor(profile.organization_id);
- const active = await getActiveGscConnection(entityId);
+ const active = await getActiveConnection(provider, entityId);
if (active) {
- await upsertConnectionRow(profile.organization_id, {
+ await upsertConnectionRow(profile.organization_id, provider, {
composio_account_id: active.id,
composio_entity_id: entityId,
status: 'connected',
@@ -77,11 +105,11 @@ router.get('/google-search-console/status', async (req, res) => {
.from('integration_connections')
.select('status')
.eq('organization_id', profile.organization_id)
- .eq('provider', PROVIDER)
+ .eq('provider', provider)
.maybeSingle();
if (row?.status === 'connected') {
- await upsertConnectionRow(profile.organization_id, {
+ await upsertConnectionRow(profile.organization_id, provider, {
composio_account_id: null,
composio_entity_id: entityId,
status: 'disconnected',
@@ -96,42 +124,16 @@ router.get('/google-search-console/status', async (req, res) => {
});
/**
- * GET /api/integrations/google-search-console/properties
- * Properties visible to the org's connected account (#642). Member-readable —
- * the mapping UI is shown to the whole org; writes stay role-gated elsewhere.
- */
-router.get('/google-search-console/properties', async (req, res) => {
- try {
- if (!isComposioConfigured()) {
- return res.status(503).json({ error: 'Search Console integration is not configured.' });
- }
-
- const profile = await getProfile(req.user.id);
- const entityId = entityIdFor(profile.organization_id);
-
- const active = await getActiveGscConnection(entityId);
- if (!active) {
- return res.status(409).json({ error: 'Google Search Console is not connected.' });
- }
-
- const properties = await listGscSites(entityId);
- return res.json({ properties });
- } catch (err) {
- req.log.error({ err }, 'integrations properties error');
- return res.status(err.status || 500).json({ error: err.message });
- }
-});
-
-/**
- * POST /api/integrations/google-search-console/connect
+ * POST /api/integrations/:provider/connect
* Body: { callbackUrl } — where Composio sends the browser after consent.
* Returns { redirectUrl } for the client to open.
*/
-router.post('/google-search-console/connect', async (req, res) => {
+router.post('/:provider/connect', async (req, res) => {
try {
- if (!isComposioConfigured()) {
- return res.status(503).json({ error: 'Search Console integration is not configured.' });
- }
+ const provider = resolveProvider(req, res);
+ if (!provider) return;
+
+ if (!isComposioConfigured(provider)) return notConfigured(res, provider);
const profile = await getProfile(req.user.id);
if (!WRITE_ROLES.includes(profile.role)) {
@@ -156,9 +158,13 @@ router.post('/google-search-console/connect', async (req, res) => {
}
const entityId = entityIdFor(profile.organization_id);
- const { redirectUrl, connectedAccountId } = await initiateGscConnection(entityId, callbackUrl);
+ const { redirectUrl, connectedAccountId } = await initiateConnection(
+ provider,
+ entityId,
+ callbackUrl,
+ );
- await upsertConnectionRow(profile.organization_id, {
+ await upsertConnectionRow(profile.organization_id, provider, {
composio_account_id: connectedAccountId,
composio_entity_id: entityId,
status: 'pending',
@@ -173,38 +179,15 @@ router.post('/google-search-console/connect', async (req, res) => {
});
/**
- * POST /api/integrations/google-search-console/sync
- * Runs the query-stats sync for the caller's org immediately (#644) —
- * testing and first-time backfill; the daily cycle runs the same sync.
- */
-router.post('/google-search-console/sync', async (req, res) => {
- try {
- if (!isComposioConfigured()) {
- return res.status(503).json({ error: 'Search Console integration is not configured.' });
- }
-
- const profile = await getProfile(req.user.id);
- if (!WRITE_ROLES.includes(profile.role)) {
- return res.status(403).json({ error: 'Only admins and managers can trigger a sync.' });
- }
-
- const result = await runGscSync({ organizationId: profile.organization_id });
- return res.json(result);
- } catch (err) {
- req.log.error({ err }, 'integrations sync error');
- return res.status(err.status || 500).json({ error: err.message });
- }
-});
-
-/**
- * DELETE /api/integrations/google-search-console
+ * DELETE /api/integrations/:provider
* Removes the connected account on Composio and resets our row.
*/
-router.delete('/google-search-console', async (req, res) => {
+router.delete('/:provider', async (req, res) => {
try {
- if (!isComposioConfigured()) {
- return res.status(503).json({ error: 'Search Console integration is not configured.' });
- }
+ const provider = resolveProvider(req, res);
+ if (!provider) return;
+
+ if (!isComposioConfigured(provider)) return notConfigured(res, provider);
const profile = await getProfile(req.user.id);
if (!WRITE_ROLES.includes(profile.role)) {
@@ -214,16 +197,16 @@ router.delete('/google-search-console', async (req, res) => {
}
const entityId = entityIdFor(profile.organization_id);
- const active = await getActiveGscConnection(entityId);
+ const active = await getActiveConnection(provider, entityId);
if (active) {
- await deleteGscConnection(active.id);
+ await deleteConnection(active.id);
}
const { error } = await supabaseAdmin
.from('integration_connections')
.delete()
.eq('organization_id', profile.organization_id)
- .eq('provider', PROVIDER);
+ .eq('provider', provider);
if (error) throw new Error(`Failed to clear connection: ${error.message}`);
return res.json({ success: true });
@@ -233,4 +216,56 @@ router.delete('/google-search-console', async (req, res) => {
}
});
+// ─── Search Console specific ─────────────────────────────────────────────────
+// Property listing and the query-stats sync have no Analytics equivalent yet
+// (that arrives with the GA data phase), so they stay on explicit paths
+// rather than under :provider.
+
+/**
+ * GET /api/integrations/google-search-console/properties
+ * Properties visible to the org's connected account (#642). Member-readable —
+ * the mapping UI is shown to the whole org; writes stay role-gated elsewhere.
+ */
+router.get('/google-search-console/properties', async (req, res) => {
+ try {
+ if (!isComposioConfigured(GSC)) return notConfigured(res, GSC);
+
+ const profile = await getProfile(req.user.id);
+ const entityId = entityIdFor(profile.organization_id);
+
+ const active = await getActiveConnection(GSC, entityId);
+ if (!active) {
+ return res.status(409).json({ error: 'Google Search Console is not connected.' });
+ }
+
+ const properties = await listGscSites(entityId);
+ return res.json({ properties });
+ } catch (err) {
+ req.log.error({ err }, 'integrations properties error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
+/**
+ * POST /api/integrations/google-search-console/sync
+ * Runs the query-stats sync for the caller's org immediately (#644) —
+ * testing and first-time backfill; the daily cycle runs the same sync.
+ */
+router.post('/google-search-console/sync', async (req, res) => {
+ try {
+ if (!isComposioConfigured(GSC)) return notConfigured(res, GSC);
+
+ const profile = await getProfile(req.user.id);
+ if (!WRITE_ROLES.includes(profile.role)) {
+ return res.status(403).json({ error: 'Only admins and managers can trigger a sync.' });
+ }
+
+ const result = await runGscSync({ organizationId: profile.organization_id });
+ return res.json(result);
+ } catch (err) {
+ req.log.error({ err }, 'integrations sync error');
+ return res.status(err.status || 500).json({ error: err.message });
+ }
+});
+
export default router;
diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsx
index 7610d784f..df38f3e8c 100644
--- a/web/src/components/settings/integrations-section.tsx
+++ b/web/src/components/settings/integrations-section.tsx
@@ -1,6 +1,6 @@
'use client';
-import { useCallback, useEffect, useRef, useState } from 'react';
+import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react';
import { toast } from 'sonner';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
@@ -23,46 +23,99 @@ import {
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
-import { Loader2, Search, Unplug } from 'lucide-react';
+import { BarChart3, Loader2, Search, Unplug } from 'lucide-react';
import {
- getGscStatus,
- connectGsc,
- disconnectGsc,
+ getIntegrationStatus,
+ connectIntegration,
+ disconnectIntegration,
getGscProperties,
getGscBrandMappings,
setBrandGscProperty,
- type GscStatus,
+ type IntegrationProvider,
+ type IntegrationStatus,
type GscProperty,
type GscBrandMapping,
} from '@/lib/actions/integrations';
import { matchGscProperty } from '@/lib/gsc';
/**
- * Settings → Integrations (#577). One card per integration — only Google
- * Search Console for now; the list layout takes more cards as they land.
- * Card states: not configured (self-host without Composio env) → not
- * connected → connecting (OAuth popup open, polling) → connected.
+ * Settings → Integrations (#577, Google Analytics added in #658).
+ *
+ * Every OAuth provider shares the same lifecycle — not configured (self-host
+ * without Composio env) → not connected → connecting (OAuth popup open,
+ * polling) → connected — so the card and its state live in one place and each
+ * provider only supplies its labels and any post-connection UI of its own.
*/
export function IntegrationsSection() {
- const [status, setStatus] = useState<GscStatus | null>(null);
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>Integrations</CardTitle>
+ <CardDescription>
+ Connect external data sources. Connections are shared with your whole organization.
+ </CardDescription>
+ </CardHeader>
+ <CardContent className="space-y-4">
+ <IntegrationCard
+ provider="google-search-console"
+ label="Google Search Console"
+ description="Real search queries and impressions for your site — powers prompt suggestions and search-vs-AI insights."
+ icon={<Search className="h-5 w-5 text-muted-foreground" />}
+ authConfigEnv="COMPOSIO_GSC_AUTH_CONFIG_ID"
+ >
+ <GscPropertyMapping />
+ </IntegrationCard>
+
+ <IntegrationCard
+ provider="google-analytics"
+ label="Google Analytics"
+ description="Sessions and conversions from your GA4 property — the basis for AI traffic history without installing the tracking snippet."
+ icon={<BarChart3 className="h-5 w-5 text-muted-foreground" />}
+ authConfigEnv="COMPOSIO_GA_AUTH_CONFIG_ID"
+ />
+ </CardContent>
+ </Card>
+ );
+}
+
+/**
+ * One integration row: status badge, Connect / Disconnect, and whatever the
+ * provider wants to render once connected (`children`).
+ */
+function IntegrationCard({
+ provider,
+ label,
+ description,
+ icon,
+ authConfigEnv,
+ children,
+}: {
+ provider: IntegrationProvider;
+ label: string;
+ description: string;
+ icon: ReactNode;
+ authConfigEnv: string;
+ children?: ReactNode;
+}) {
+ const [status, setStatus] = useState<IntegrationStatus | null>(null);
const [connecting, setConnecting] = useState(false);
const [disconnecting, setDisconnecting] = useState(false);
const pollGen = useRef(0);
const load = useCallback(async () => {
try {
- const result = await getGscStatus();
+ const result = await getIntegrationStatus(provider);
setStatus(result.status);
} catch (err) {
- console.error('Failed to load integration status:', err);
+ console.error(`Failed to load ${provider} status:`, err);
toast.error('Failed to load integration status');
setStatus('not_connected');
}
- }, []);
+ }, [provider]);
useEffect(() => {
load();
- // Stop any in-flight poll when the section unmounts.
+ // Stop any in-flight poll when the card unmounts.
const gen = pollGen.current;
return () => {
if (pollGen.current === gen) pollGen.current++;
@@ -74,9 +127,9 @@ export function IntegrationsSection() {
const gen = ++pollGen.current;
try {
const callbackUrl = `${window.location.origin}/dashboard/settings?tab=integrations`;
- const { redirectUrl } = await connectGsc(callbackUrl);
+ const { redirectUrl } = await connectIntegration(provider, callbackUrl);
- const popup = window.open(redirectUrl, 'gsc-oauth', 'width=560,height=720');
+ 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;
@@ -89,10 +142,10 @@ export function IntegrationsSection() {
await new Promise((r) => setTimeout(r, 3000));
if (pollGen.current !== gen) return;
try {
- const result = await getGscStatus();
+ const result = await getIntegrationStatus(provider);
if (result.status === 'connected') {
setStatus('connected');
- toast.success('Google Search Console connected');
+ toast.success(`${label} connected`);
popup.close();
return;
}
@@ -101,11 +154,11 @@ export function IntegrationsSection() {
}
if (popup.closed) {
// User closed the window — one final check, then give up quietly.
- const result = await getGscStatus().catch(() => null);
+ const result = await getIntegrationStatus(provider).catch(() => null);
if (pollGen.current !== gen) return;
setStatus(result?.status ?? 'not_connected');
if (result?.status === 'connected') {
- toast.success('Google Search Console connected');
+ toast.success(`${label} connected`);
}
return;
}
@@ -123,9 +176,9 @@ export function IntegrationsSection() {
const handleDisconnect = async () => {
setDisconnecting(true);
try {
- await disconnectGsc();
+ await disconnectIntegration(provider);
setStatus('not_connected');
- toast.success('Google Search Console disconnected');
+ toast.success(`${label} disconnected`);
} catch (err) {
toast.error(err instanceof Error ? err.message : 'Failed to disconnect');
} finally {
@@ -134,101 +187,90 @@ export function IntegrationsSection() {
};
return (
- <Card>
- <CardHeader>
- <CardTitle>Integrations</CardTitle>
- <CardDescription>
- Connect external data sources. Connections are shared with your whole organization.
- </CardDescription>
- </CardHeader>
- <CardContent className="space-y-4">
- <div className="flex items-center justify-between gap-4 rounded-lg border p-4">
- <div className="flex items-center gap-3 min-w-0">
- <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted/50">
- <Search className="h-5 w-5 text-muted-foreground" />
- </div>
- <div className="min-w-0">
- <div className="flex items-center gap-2">
- <p className="text-sm font-medium">Google Search Console</p>
- {status === 'connected' && (
- <Badge
- variant="outline"
- className="border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
- >
- Connected
- </Badge>
- )}
- </div>
- <p className="text-xs text-muted-foreground truncate">
- Real search queries and impressions for your site — powers upcoming prompt
- suggestions and search-vs-AI insights.
- </p>
+ <div className="space-y-4">
+ <div className="flex items-center justify-between gap-4 rounded-lg border p-4">
+ <div className="flex items-center gap-3 min-w-0">
+ <div className="flex h-10 w-10 shrink-0 items-center justify-center rounded-md border bg-muted/50">
+ {icon}
+ </div>
+ <div className="min-w-0">
+ <div className="flex items-center gap-2">
+ <p className="text-sm font-medium">{label}</p>
+ {status === 'connected' && (
+ <Badge
+ variant="outline"
+ className="border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
+ >
+ Connected
+ </Badge>
+ )}
</div>
+ <p className="text-xs text-muted-foreground truncate">{description}</p>
</div>
-
- {status === null ? (
- <Skeleton className="h-8 w-24" />
- ) : status === 'not_configured' ? (
- <Badge variant="outline" className="text-muted-foreground shrink-0">
- Not configured
- </Badge>
- ) : status === 'connected' ? (
- <Dialog>
- <DialogTrigger
- render={<Button variant="outline" size="sm" className="gap-2 shrink-0" />}
- >
- <Unplug className="h-3.5 w-3.5" />
- Disconnect
- </DialogTrigger>
- <DialogContent className="sm:max-w-sm">
- <DialogHeader>
- <DialogTitle>Disconnect Google Search Console</DialogTitle>
- <DialogDescription>
- The stored connection is removed for the whole organization. You can reconnect
- at any time.
- </DialogDescription>
- </DialogHeader>
- <DialogFooter>
- <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
- <DialogClose
- render={
- <Button
- variant="destructive"
- onClick={handleDisconnect}
- disabled={disconnecting}
- />
- }
- >
- Disconnect
- </DialogClose>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- ) : (
- <Button
- size="sm"
- className="gap-2 shrink-0"
- onClick={handleConnect}
- disabled={connecting}
- >
- {connecting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
- {connecting ? 'Connecting…' : 'Connect'}
- </Button>
- )}
</div>
- {status === 'not_configured' && (
- <p className="text-xs text-muted-foreground">
- This server has no Composio credentials configured. Set{' '}
- <code className="rounded bg-muted px-1">COMPOSIO_API_KEY</code> and{' '}
- <code className="rounded bg-muted px-1">COMPOSIO_GSC_AUTH_CONFIG_ID</code> in the server
- environment to enable integrations.
- </p>
+ {status === null ? (
+ <Skeleton className="h-8 w-24" />
+ ) : status === 'not_configured' ? (
+ <Badge variant="outline" className="text-muted-foreground shrink-0">
+ Not configured
+ </Badge>
+ ) : status === 'connected' ? (
+ <Dialog>
+ <DialogTrigger
+ render={<Button variant="outline" size="sm" className="gap-2 shrink-0" />}
+ >
+ <Unplug className="h-3.5 w-3.5" />
+ Disconnect
+ </DialogTrigger>
+ <DialogContent className="sm:max-w-sm">
+ <DialogHeader>
+ <DialogTitle>Disconnect {label}</DialogTitle>
+ <DialogDescription>
+ The stored connection is removed for the whole organization. You can reconnect at
+ any time.
+ </DialogDescription>
+ </DialogHeader>
+ <DialogFooter>
+ <DialogClose render={<Button variant="outline" />}>Cancel</DialogClose>
+ <DialogClose
+ render={
+ <Button
+ variant="destructive"
+ onClick={handleDisconnect}
+ disabled={disconnecting}
+ />
+ }
+ >
+ Disconnect
+ </DialogClose>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ ) : (
+ <Button
+ size="sm"
+ className="gap-2 shrink-0"
+ onClick={handleConnect}
+ disabled={connecting}
+ >
+ {connecting && <Loader2 className="h-3.5 w-3.5 animate-spin" />}
+ {connecting ? 'Connecting…' : 'Connect'}
+ </Button>
)}
+ </div>
- {status === 'connected' && <GscPropertyMapping />}
- </CardContent>
- </Card>
+ {status === 'not_configured' && (
+ <p className="text-xs text-muted-foreground">
+ This server has no Composio credentials for {label}. Set{' '}
+ <code className="rounded bg-muted px-1">COMPOSIO_API_KEY</code> and{' '}
+ <code className="rounded bg-muted px-1">{authConfigEnv}</code> in the server environment
+ to enable it.
+ </p>
+ )}
+
+ {status === 'connected' && children}
+ </div>
);
}
diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.ts
index 7c0f8f18a..ec93264eb 100644
--- a/web/src/lib/actions/integrations.ts
+++ b/web/src/lib/actions/integrations.ts
@@ -3,11 +3,14 @@
import { createClient } from '@/lib/supabase/server';
import { API_BASE_URL } from '@/config/api';
-export type GscStatus = 'not_configured' | 'not_connected' | 'connected';
+/** Providers that expose the shared connect / status / disconnect flow. */
+export type IntegrationProvider = 'google-search-console' | 'google-analytics';
-export interface GscStatusResult {
+export type IntegrationStatus = 'not_configured' | 'not_connected' | 'connected';
+
+export interface IntegrationStatusResult {
configured: boolean;
- status: GscStatus;
+ status: IntegrationStatus;
accountId?: string;
}
@@ -23,18 +26,23 @@ async function authHeaders(): Promise<Record<string, string>> {
};
}
-export async function getGscStatus(): Promise<GscStatusResult> {
- const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/status`, {
+export async function getIntegrationStatus(
+ provider: IntegrationProvider,
+): Promise<IntegrationStatusResult> {
+ const res = await fetch(`${API_BASE_URL}/api/integrations/${provider}/status`, {
headers: await authHeaders(),
cache: 'no-store',
});
const body = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);
- return body as GscStatusResult;
+ return body as IntegrationStatusResult;
}
-export async function connectGsc(callbackUrl: string): Promise<{ redirectUrl: string }> {
- const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/connect`, {
+export async function connectIntegration(
+ provider: IntegrationProvider,
+ callbackUrl: string,
+): Promise<{ redirectUrl: string }> {
+ const res = await fetch(`${API_BASE_URL}/api/integrations/${provider}/connect`, {
method: 'POST',
headers: await authHeaders(),
body: JSON.stringify({ callbackUrl }),
@@ -44,8 +52,8 @@ export async function connectGsc(callbackUrl: string): Promise<{ redirectUrl: st
return body as { redirectUrl: string };
}
-export async function disconnectGsc(): Promise<void> {
- const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console`, {
+export async function disconnectIntegration(provider: IntegrationProvider): Promise<void> {
+ const res = await fetch(`${API_BASE_URL}/api/integrations/${provider}`, {
method: 'DELETE',
headers: await authHeaders(),
});