Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat: add Settings Integrations tab with Google Search Console connection via Composio (#577) (#643)
Gökhan Geyikf04b5c548d7d
diff --git a/server/.env.example b/server/.env.exampleindex 0b5d65c19..8af4c7e71 100644--- a/server/.env.example+++ b/server/.env.example@@ -86,3 +86,8 @@ AI_VOLUME_MULTIPLIER=0.15# Public URL of the web app, used for links in Daily Pulse emails# PUBLIC_APP_URL=https://app.example.com++# Composio managed auth (Settings → Integrations, #577). Optional — without+# these the Integrations card shows "not configured" and everything else works.+# COMPOSIO_API_KEY=+# COMPOSIO_GSC_AUTH_CONFIG_ID=diff --git a/server/package-lock.json b/server/package-lock.jsonindex febf2e831..69f5dc4ed 100644--- a/server/package-lock.json+++ b/server/package-lock.json@@ -1,18 +1,19 @@{"name": "@ansvisor/ansvisor-server",- "version": "0.1.3",+ "version": "0.1.7","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@ansvisor/ansvisor-server",- "version": "0.1.3",+ "version": "0.1.7","license": "MIT","dependencies": {"@ai-sdk/anthropic": "^3.0.58","@ai-sdk/google": "^3.0.43","@ai-sdk/openai": "^3.0.41","@anthropic-ai/sdk": "^0.78.0",+ "@composio/core": "^0.14.1","@supabase/supabase-js": "^2.49.1","ai": "^6.0.116","body-parser": "^1.20.2",@@ -162,6 +163,40 @@"node": ">=6.9.0"}},+ "node_modules/@composio/client": {+ "version": "0.1.0-alpha.76",+ "resolved": "https://registry.npmjs.org/@composio/client/-/client-0.1.0-alpha.76.tgz",+ "integrity": "sha512-MXC5JGRVdiQ4EgLricy9o/mqBa1+1T7wHFZ6Q4ZJkrjzZqOMvxTgy21Zlb5J/1oGkB2bg9UDzpH8PkXCp/D4zA==",+ "license": "Apache-2.0"+ },+ "node_modules/@composio/core": {+ "version": "0.14.1",+ "resolved": "https://registry.npmjs.org/@composio/core/-/core-0.14.1.tgz",+ "integrity": "sha512-MumO81kU9ZwHELrN7b/ju9Ke7il/xz0d65yeSsbtp5V11LA4efLKgE4hKPxif55NK97pApBOj4UkQB+knzue9Q==",+ "license": "ISC",+ "dependencies": {+ "@composio/client": "0.1.0-alpha.76",+ "@composio/json-schema-to-zod": "0.2.1",+ "@types/json-schema": "^7.0.15",+ "openai": "^6.49.0",+ "picocolors": "^1.1.1",+ "pusher-js": "^8.6.0",+ "semver": "^7.8.5",+ "zod-to-json-schema": "^3.25.2"+ },+ "peerDependencies": {+ "zod": ">=3.25.76 <5"+ }+ },+ "node_modules/@composio/json-schema-to-zod": {+ "version": "0.2.1",+ "resolved": "https://registry.npmjs.org/@composio/json-schema-to-zod/-/json-schema-to-zod-0.2.1.tgz",+ "integrity": "sha512-ezIaQoXdqWJXFaI8+gTShpj8YZcRdSnLkA1hgzx1+kn2Bi1SXOtXjghoQDy2ZBYIOCefRXGmyaPl52+idjS9wA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": ">=3.25.76 <5"+ }+ },"node_modules/@esbuild/aix-ppc64": {"version": "0.27.7","resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.7.tgz",@@ -1729,7 +1764,6 @@"version": "7.0.15","resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz","integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==",- "dev": true,"license": "MIT"},"node_modules/@types/node": {@@ -4462,18 +4496,27 @@}},"node_modules/openai": {- "version": "6.27.0",- "resolved": "https://registry.npmjs.org/openai/-/openai-6.27.0.tgz",- "integrity": "sha512-osTKySlrdYrLYTt0zjhY8yp0JUBmWDCN+Q+QxsV4xMQnnoVFpylgKGgxwN8sSdTNw0G4y+WUXs4eCMWpyDNWZQ==",+ "version": "6.49.0",+ "resolved": "https://registry.npmjs.org/openai/-/openai-6.49.0.tgz",+ "integrity": "sha512-aYCc0C6L864eR6WSYIwQGyXriw/nIyZx0ObvhzOEVuk0zoBDpynjSbrionWI7q65B5H8jJX0DXR9snEzM6bfPg==","license": "Apache-2.0",- "bin": {- "openai": "bin/cli"- },"peerDependencies": {+ "@aws-sdk/credential-provider-node": ">=3.972.0 <4",+ "@smithy/hash-node": ">=4.3.0 <5",+ "@smithy/signature-v4": ">=5.4.0 <6","ws": "^8.18.0","zod": "^3.25 || ^4.0"},"peerDependenciesMeta": {+ "@aws-sdk/credential-provider-node": {+ "optional": true+ },+ "@smithy/hash-node": {+ "optional": true+ },+ "@smithy/signature-v4": {+ "optional": true+ },"ws": {"optional": true},@@ -4717,7 +4760,6 @@"version": "1.1.1","resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz","integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",- "dev": true,"license": "ISC"},"node_modules/picomatch": {@@ -5158,6 +5200,15 @@"node": ">=6"}},+ "node_modules/pusher-js": {+ "version": "8.6.0",+ "resolved": "https://registry.npmjs.org/pusher-js/-/pusher-js-8.6.0.tgz",+ "integrity": "sha512-wShJPfCS/kYkCBVzVW67wa9cnQIgHTszEK2XHNrFkOgGruuGw081aERAxfRjfdFU+WcIt8x6dvbwkTW4iZuQ8Q==",+ "license": "MIT",+ "dependencies": {+ "tweetnacl": "^1.0.3"+ }+ },"node_modules/qs": {"version": "6.14.2","resolved": "https://registry.npmjs.org/qs/-/qs-6.14.2.tgz",@@ -5413,9 +5464,9 @@}},"node_modules/semver": {- "version": "7.7.4",- "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.4.tgz",- "integrity": "sha512-vFKC2IEtQnVhpT78h1Yp8wzwrf8CM+MzKMHGJZfBtzhZNycRFnXsHk6E5TxIkkMsgNS7mdX3AGB7x2QM2di4lA==",+ "version": "7.8.5",+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==","license": "ISC","bin": {"semver": "bin/semver.js"@@ -6119,6 +6170,12 @@"node": ">= 0.8.0"}},+ "node_modules/tweetnacl": {+ "version": "1.0.3",+ "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",+ "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",+ "license": "Unlicense"+ },"node_modules/tx2": {"version": "1.0.5","resolved": "https://registry.npmjs.org/tx2/-/tx2-1.0.5.tgz",@@ -6641,6 +6698,15 @@"funding": {"url": "https://github.com/sponsors/colinhacks"}+ },+ "node_modules/zod-to-json-schema": {+ "version": "3.25.2",+ "resolved": "https://registry.npmjs.org/zod-to-json-schema/-/zod-to-json-schema-3.25.2.tgz",+ "integrity": "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA==",+ "license": "ISC",+ "peerDependencies": {+ "zod": "^3.25.28 || ^4"+ }}}}diff --git a/server/package.json b/server/package.jsonindex 2d9672f7c..ff1428b3a 100644--- a/server/package.json+++ b/server/package.json@@ -27,6 +27,7 @@"@ai-sdk/google": "^3.0.43","@ai-sdk/openai": "^3.0.41","@anthropic-ai/sdk": "^0.78.0",+ "@composio/core": "^0.14.1","@supabase/supabase-js": "^2.49.1","ai": "^6.0.116","body-parser": "^1.20.2",diff --git a/server/src/lib/composio.js b/server/src/lib/composio.jsnew file mode 100644index 000000000..472a54b75--- /dev/null+++ b/server/src/lib/composio.js@@ -0,0 +1,55 @@+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.+ */++let client = null;++export function isComposioConfigured() {+ return Boolean(process.env.COMPOSIO_API_KEY && process.env.COMPOSIO_GSC_AUTH_CONFIG_ID);+}++function getClient() {+ if (!client) {+ client = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });+ }+ 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(), {+ callbackUrl,+ });+ return {+ redirectUrl: request.redirectUrl,+ connectedAccountId: request.connectedAccountId ?? request.id ?? null,+ status: request.connectionStatus ?? 'INITIATED',+ };+}++/** The entity's ACTIVE Search Console connection on Composio, or null. */+export async function getActiveGscConnection(entityId) {+ const connections = await getClient().connectedAccounts.list({+ authConfigIds: [gscAuthConfigId()],+ userIds: [entityId],+ statuses: ['ACTIVE'],+ });+ return connections.items?.[0] ?? null;+}++export async function deleteGscConnection(connectedAccountId) {+ await getClient().connectedAccounts.delete(connectedAccountId);+}diff --git a/server/src/routes/index.js b/server/src/routes/index.jsindex dc59038c8..9c813bb08 100644--- a/server/src/routes/index.js+++ b/server/src/routes/index.js@@ -7,6 +7,7 @@ import competitorRoutes from './competitors.js';import topicRoutes from './topics.js';import auditRoutes from './audits.js';import reportRoutes from './reports.js';+import integrationRoutes from './integrations.js';const router = Router();@@ -18,6 +19,7 @@ router.use('/competitors', competitorRoutes);router.use('/topics', topicRoutes);router.use('/audits', auditRoutes);router.use('/reports', reportRoutes);+router.use('/integrations', integrationRoutes);router.get('/health', (req, res) => {res.json({ status: 'ok', user: req.user?.id });diff --git a/server/src/routes/integrations.js b/server/src/routes/integrations.jsnew file mode 100644index 000000000..10e510153--- /dev/null+++ b/server/src/routes/integrations.js@@ -0,0 +1,183 @@+import { Router } from 'express';+import supabaseAdmin from '../config/supabase.js';+import {+ isComposioConfigured,+ initiateGscConnection,+ getActiveGscConnection,+ deleteGscConnection,+} from '../lib/composio.js';++const router = Router();++const PROVIDER = 'google-search-console';+const WRITE_ROLES = ['admin', 'manager'];++/** Entity id: one Search Console connection per organization (#577). */+function entityIdFor(organizationId) {+ return `org_${organizationId}`;+}++async function getProfile(userId) {+ const { data: profile, error } = await supabaseAdmin+ .from('profiles')+ .select('organization_id, role')+ .eq('id', userId)+ .single();+ if (error) throw new Error(`Failed to load profile: ${error.message}`);+ if (!profile?.organization_id) {+ const err = new Error('No organization found for user.');+ err.status = 400;+ throw err;+ }+ return profile;+}++async function upsertConnectionRow(organizationId, fields) {+ const { error } = await supabaseAdmin.from('integration_connections').upsert(+ {+ organization_id: organizationId,+ provider: PROVIDER,+ updated_at: new Date().toISOString(),+ ...fields,+ },+ { onConflict: 'organization_id,provider' },+ );+ if (error) throw new Error(`Failed to save connection: ${error.message}`);+}++/**+ * GET /api/integrations/google-search-console/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) => {+ try {+ if (!isComposioConfigured()) {+ 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);+ if (active) {+ await upsertConnectionRow(profile.organization_id, {+ composio_account_id: active.id,+ composio_entity_id: entityId,+ status: 'connected',+ });+ return res.json({ configured: true, status: 'connected', accountId: active.id });+ }++ // No active account on Composio — reflect that in our row if it claims+ // otherwise (revoked from the Google side, expired, etc.).+ const { data: row } = await supabaseAdmin+ .from('integration_connections')+ .select('status')+ .eq('organization_id', profile.organization_id)+ .eq('provider', PROVIDER)+ .maybeSingle();++ if (row?.status === 'connected') {+ await upsertConnectionRow(profile.organization_id, {+ composio_account_id: null,+ composio_entity_id: entityId,+ status: 'disconnected',+ });+ }++ return res.json({ configured: true, status: 'not_connected' });+ } catch (err) {+ req.log.error({ err }, 'integrations status error');+ return res.status(err.status || 500).json({ error: err.message });+ }+});++/**+ * POST /api/integrations/google-search-console/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) => {+ 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 connect integrations.' });+ }++ const { callbackUrl } = req.body ?? {};+ if (typeof callbackUrl !== 'string' || !/^https?:\/\//.test(callbackUrl)) {+ return res.status(400).json({ error: 'callbackUrl is required' });+ }+ // Compare origins, not prefixes — PUBLIC_APP_URL may be misconfigured+ // with a path and must still validate correctly.+ const appUrl = process.env.PUBLIC_APP_URL;+ if (appUrl) {+ try {+ if (new URL(callbackUrl).origin !== new URL(appUrl).origin) {+ return res.status(400).json({ error: 'callbackUrl must be on the app origin' });+ }+ } catch {+ return res.status(400).json({ error: 'callbackUrl is not a valid URL' });+ }+ }++ const entityId = entityIdFor(profile.organization_id);+ const { redirectUrl, connectedAccountId } = await initiateGscConnection(entityId, callbackUrl);++ await upsertConnectionRow(profile.organization_id, {+ composio_account_id: connectedAccountId,+ composio_entity_id: entityId,+ status: 'pending',+ connected_by: req.user.id,+ });++ return res.json({ redirectUrl });+ } catch (err) {+ req.log.error({ err }, 'integrations connect error');+ return res.status(err.status || 500).json({ error: err.message });+ }+});++/**+ * DELETE /api/integrations/google-search-console+ * Removes the connected account on Composio and resets our row.+ */+router.delete('/google-search-console', 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 disconnect integrations.' });+ }++ const entityId = entityIdFor(profile.organization_id);+ const active = await getActiveGscConnection(entityId);+ if (active) {+ await deleteGscConnection(active.id);+ }++ const { error } = await supabaseAdmin+ .from('integration_connections')+ .delete()+ .eq('organization_id', profile.organization_id)+ .eq('provider', PROVIDER);+ if (error) throw new Error(`Failed to clear connection: ${error.message}`);++ return res.json({ success: true });+ } catch (err) {+ req.log.error({ err }, 'integrations disconnect error');+ return res.status(err.status || 500).json({ error: err.message });+ }+});++export default router;diff --git a/supabase/migrations/00045_integration_connections.sql b/supabase/migrations/00045_integration_connections.sqlnew file mode 100644index 000000000..e0185f8a2--- /dev/null+++ b/supabase/migrations/00045_integration_connections.sql@@ -0,0 +1,43 @@+-- Integration connections — Settings → Integrations surface (#577).+--+-- One row per (organization, provider). Only google-search-console for now;+-- the table is the generic surface future integrations plug into. OAuth+-- tokens never touch this table — Composio stores them; we keep only the+-- Composio account/entity ids and the connection status.+--+-- The server (service role) writes; org members read so the card state is+-- visible to teammates. Admin/manager write policies exist for completeness+-- even though the normal write path is the service role.++CREATE TABLE public.integration_connections (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ organization_id uuid NOT NULL REFERENCES public.organizations(id) ON DELETE CASCADE,+ provider text NOT NULL,+ composio_account_id text,+ composio_entity_id text NOT NULL,+ status text NOT NULL DEFAULT 'pending',+ connected_by uuid REFERENCES public.profiles(id) ON DELETE SET NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (organization_id, provider)+);++ALTER TABLE public.integration_connections ENABLE ROW LEVEL SECURITY;++CREATE POLICY "integration_connections: member select" ON public.integration_connections+ FOR SELECT USING (+ organization_id IN (+ SELECT p.organization_id FROM public.profiles p WHERE p.id = auth.uid()+ )+ );++CREATE POLICY "integration_connections: admin write" ON public.integration_connections+ FOR ALL USING (+ organization_id IN (+ SELECT p.organization_id FROM public.profiles p+ WHERE p.id = auth.uid()+ AND p.role = ANY (ARRAY['admin'::public.user_role, 'manager'::public.user_role])+ )+ );++GRANT SELECT ON public.integration_connections TO authenticated;diff --git a/supabase/schema.sql b/supabase/schema.sqlindex faec1dd8c..968e18d43 100644--- a/supabase/schema.sql+++ b/supabase/schema.sql@@ -4907,3 +4907,50 @@ SELECT l.brand_id,AND pr.created_at > l.last_at - interval '2 hours')FROM latest l;+-- ─────────────────────────────────────────────────────────────────────────+-- migrations/00045_integration_connections.sql+-- ─────────────────────────────────────────────────────────────────────────+-- Integration connections — Settings → Integrations surface (#577).+--+-- One row per (organization, provider). Only google-search-console for now;+-- the table is the generic surface future integrations plug into. OAuth+-- tokens never touch this table — Composio stores them; we keep only the+-- Composio account/entity ids and the connection status.+--+-- The server (service role) writes; org members read so the card state is+-- visible to teammates. Admin/manager write policies exist for completeness+-- even though the normal write path is the service role.++CREATE TABLE public.integration_connections (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ organization_id uuid NOT NULL REFERENCES public.organizations(id) ON DELETE CASCADE,+ provider text NOT NULL,+ composio_account_id text,+ composio_entity_id text NOT NULL,+ status text NOT NULL DEFAULT 'pending',+ connected_by uuid REFERENCES public.profiles(id) ON DELETE SET NULL,+ created_at timestamptz NOT NULL DEFAULT now(),+ updated_at timestamptz NOT NULL DEFAULT now(),+ UNIQUE (organization_id, provider)+);++ALTER TABLE public.integration_connections ENABLE ROW LEVEL SECURITY;++CREATE POLICY "integration_connections: member select" ON public.integration_connections+ FOR SELECT USING (+ organization_id IN (+ SELECT p.organization_id FROM public.profiles p WHERE p.id = auth.uid()+ )+ );++CREATE POLICY "integration_connections: admin write" ON public.integration_connections+ FOR ALL USING (+ organization_id IN (+ SELECT p.organization_id FROM public.profiles p+ WHERE p.id = auth.uid()+ AND p.role = ANY (ARRAY['admin'::public.user_role, 'manager'::public.user_role])+ )+ );++GRANT SELECT ON public.integration_connections TO authenticated;+diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsxindex 324ac84d2..63a456f07 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/page.tsx@@ -18,6 +18,7 @@ import { TeamSection } from '@/components/settings/team-section';import { ApiKeysSection } from '@/components/settings/api-keys-section';import { AgentSection } from '@/components/settings/agent-section';import { NotificationsSection } from '@/components/settings/notifications-section';+import { IntegrationsSection } from '@/components/settings/integrations-section';type Section =| 'account'@@ -25,6 +26,7 @@ type Section =| 'project'| 'team'| 'notifications'+ | 'integrations'| 'api-keys'| 'agent'| 'billing';@@ -41,6 +43,8 @@ export default function SettingsPage() {if (tabParam === 'agent' && isCloud) return 'agent';// Deep-linked from the Daily Pulse email's "manage notifications" footer.if (tabParam === 'notifications') return 'notifications';+ // OAuth popups land back here after the Composio consent flow (#577).+ if (tabParam === 'integrations') return 'integrations';return 'account';});const [displayName, setDisplayName] = useState('');@@ -67,6 +71,7 @@ export default function SettingsPage() {{ id: 'project', label: t('project') },{ id: 'team', label: t('team') },{ id: 'notifications', label: t('notifications') },+ { id: 'integrations', label: 'Integrations' },{ id: 'api-keys', label: 'API Keys' },// Agent BYOK is a cloud-only concern — self-host operators configure// ANTHROPIC_API_KEY in their own env, no UI needed.@@ -186,6 +191,8 @@ export default function SettingsPage() {{active === 'notifications' && <NotificationsSection />}+ {active === 'integrations' && <IntegrationsSection />}+{/* API Keys */}{active === 'api-keys' && <ApiKeysSection />}diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsxnew file mode 100644index 000000000..c2ad3f024--- /dev/null+++ b/web/src/components/settings/integrations-section.tsx@@ -0,0 +1,218 @@+'use client';++import { useCallback, useEffect, useRef, useState } from 'react';+import { toast } from 'sonner';+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';+import { Button } from '@/components/ui/button';+import { Badge } from '@/components/ui/badge';+import { Skeleton } from '@/components/ui/skeleton';+import {+ Dialog,+ DialogClose,+ DialogContent,+ DialogDescription,+ DialogFooter,+ DialogHeader,+ DialogTitle,+ DialogTrigger,+} from '@/components/ui/dialog';+import { Loader2, Search, Unplug } from 'lucide-react';+import {+ getGscStatus,+ connectGsc,+ disconnectGsc,+ type GscStatus,+} from '@/lib/actions/integrations';++/**+ * 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.+ */+export function IntegrationsSection() {+ const [status, setStatus] = useState<GscStatus | 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();+ setStatus(result.status);+ } catch (err) {+ console.error('Failed to load integration status:', err);+ toast.error('Failed to load integration status');+ setStatus('not_connected');+ }+ }, []);++ useEffect(() => {+ load();+ // Stop any in-flight poll when the section 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 connectGsc(callbackUrl);++ const popup = window.open(redirectUrl, 'gsc-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 getGscStatus();+ if (result.status === 'connected') {+ setStatus('connected');+ toast.success('Google Search Console 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 getGscStatus().catch(() => null);+ if (pollGen.current !== gen) return;+ setStatus(result?.status ?? 'not_connected');+ if (result?.status === 'connected') {+ toast.success('Google Search Console 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 {+ await disconnectGsc();+ setStatus('not_connected');+ toast.success('Google Search Console disconnected');+ } catch (err) {+ toast.error(err instanceof Error ? err.message : 'Failed to disconnect');+ } finally {+ setDisconnecting(false);+ }+ };++ 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>+ </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>+ )}+ </CardContent>+ </Card>+ );+}diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.tsnew file mode 100644index 000000000..4fdb5816f--- /dev/null+++ b/web/src/lib/actions/integrations.ts@@ -0,0 +1,54 @@+'use server';++import { createClient } from '@/lib/supabase/server';+import { API_BASE_URL } from '@/config/api';++export type GscStatus = 'not_configured' | 'not_connected' | 'connected';++export interface GscStatusResult {+ configured: boolean;+ status: GscStatus;+ accountId?: string;+}++async function authHeaders(): Promise<Record<string, string>> {+ const supabase = await createClient();+ const {+ data: { session },+ } = await supabase.auth.getSession();+ if (!session) throw new Error('Not authenticated');+ return {+ 'Content-Type': 'application/json',+ Authorization: `Bearer ${session.access_token}`,+ };+}++export async function getGscStatus(): Promise<GscStatusResult> {+ const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/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;+}++export async function connectGsc(callbackUrl: string): Promise<{ redirectUrl: string }> {+ const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/connect`, {+ method: 'POST',+ headers: await authHeaders(),+ body: JSON.stringify({ callbackUrl }),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);+ return body as { redirectUrl: string };+}++export async function disconnectGsc(): Promise<void> {+ const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console`, {+ method: 'DELETE',+ headers: await authHeaders(),+ });+ const body = await res.json().catch(() => ({}));+ if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);+}diff --git a/web/src/types/supabase.ts b/web/src/types/supabase.tsindex 3553171e5..d626e2bed 100644--- a/web/src/types/supabase.ts+++ b/web/src/types/supabase.ts@@ -441,6 +441,57 @@ export type Database = {},];};+ integration_connections: {+ Row: {+ composio_account_id: string | null;+ composio_entity_id: string;+ connected_by: string | null;+ created_at: string;+ id: string;+ organization_id: string;+ provider: string;+ status: string;+ updated_at: string;+ };+ Insert: {+ composio_account_id?: string | null;+ composio_entity_id: string;+ connected_by?: string | null;+ created_at?: string;+ id?: string;+ organization_id: string;+ provider: string;+ status?: string;+ updated_at?: string;+ };+ Update: {+ composio_account_id?: string | null;+ composio_entity_id?: string;+ connected_by?: string | null;+ created_at?: string;+ id?: string;+ organization_id?: string;+ provider?: string;+ status?: string;+ updated_at?: string;+ };+ Relationships: [+ {+ foreignKeyName: 'integration_connections_organization_id_fkey';+ columns: ['organization_id'];+ isOneToOne: false;+ referencedRelation: 'organizations';+ referencedColumns: ['id'];+ },+ {+ foreignKeyName: 'integration_connections_connected_by_fkey';+ columns: ['connected_by'];+ isOneToOne: false;+ referencedRelation: 'profiles';+ referencedColumns: ['id'];+ },+ ];+ };invitations: {Row: {accepted_at: string | null;