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
fix(settings): load each integration card on its own and open Connect at once (#1783)
Cihandf4d0f80f8f9
diff --git a/server/src/middleware/rate-limiter.js b/server/src/middleware/rate-limiter.jsindex 3b0a193fe..c8286a0a7 100644--- a/server/src/middleware/rate-limiter.js+++ b/server/src/middleware/rate-limiter.js@@ -190,6 +190,22 @@ export const cmsLimiter = rateLimit({},});+// The Library's checks whether pages sent to a CMS were published there:+// three each time it opens, answered from a two-minute memory per brand. A+// bucket of their own, so opening the Library never uses up a member's+// cmsLimiter, and connecting a CMS stays open to them.+export const cmsStatusLimiter = rateLimit({+ windowMs: 15 * 60 * 1000,+ max: 180,+ keyGenerator: apiLimiterKey,+ standardHeaders: true,+ legacyHeaders: false,+ message: {+ success: false,+ message: 'Too many requests, please try again later.',+ },+});+// Test Webhook (#1568 review): each test posts to an address the caller// typed, so a member's are few, 10 a minute.export const webhookTestLimiter = rateLimit({diff --git a/server/src/middleware/rate-limiter.test.js b/server/src/middleware/rate-limiter.test.jsindex ff6e12e9b..ca3d8ec97 100644--- a/server/src/middleware/rate-limiter.test.js+++ b/server/src/middleware/rate-limiter.test.js@@ -6,6 +6,7 @@ import {catalogCategoryLimiter,catalogLimiter,cmsLimiter,+ cmsStatusLimiter,isJourneyBeacon,journeyEventKey,shoppingPathLimiter,@@ -173,6 +174,34 @@ describe('rate-limiter – catalog buckets', () => {});});+describe('rate-limiter – CMS buckets', () => {+ it("keeps the Library's publish checks apart from connecting a CMS", async () => {+ const app = express();+ app.post('/webflow-status', cmsStatusLimiter, (_req, res) => res.json({}));+ app.post('/cms', cmsLimiter, (_req, res) => res.json({}));+ const server = await new Promise((resolve) => {+ const listening = app.listen(0, '127.0.0.1', () => resolve(listening));+ });+ const base = `http://127.0.0.1:${server.address().port}`;+ const statuses = async (path, n) => {+ const out = [];+ for (let i = 0; i < n; i += 1)+ out.push((await fetch(base + path, { method: 'POST' })).status);+ return out;+ };+ try {+ // Opening the Library 60 times (3 checks each) uses up its own 180…+ const checks = await statuses('/webflow-status', 181);+ expect(new Set(checks.slice(0, 180))).toEqual(new Set([200]));+ expect(checks.at(-1)).toBe(429);+ // …and connecting a CMS still goes through (its bucket is the module's: a few here).+ expect(new Set(await statuses('/cms', 5))).toEqual(new Set([200]));+ } finally {+ await new Promise((resolve) => server.close(resolve));+ }+ });+});+describe('rate-limiter – shopping path builds', () => {it("gives a draft's shopping path builds a bucket of their own: 30 a quarter-hour", async () => {const app = express();diff --git a/server/src/routes/content-drafts.js b/server/src/routes/content-drafts.jsindex 9c1a6ee0e..0bd0df24a 100644--- a/server/src/routes/content-drafts.js+++ b/server/src/routes/content-drafts.js@@ -11,7 +11,7 @@ import { checkFramerPublished } from '../lib/cms/framer-status.js';import { checkWebflowPublished } from '../lib/cms/webflow-status.js';import { checkWordPressPublished } from '../lib/cms/wordpress-status.js';import { liveAddress, publishDraft } from '../lib/content-published.js';-import { cmsLimiter, shoppingPathLimiter } from '../middleware/rate-limiter.js';+import { cmsStatusLimiter, shoppingPathLimiter } from '../middleware/rate-limiter.js';import { stopDraftRun } from '../lib/content-runs.js';import { startDraftWriting, writeDraftInput } from '../lib/content-writer.js';import supabaseAdmin from '../config/supabase.js';@@ -143,7 +143,7 @@ const webflowStatusBody = z.object({ brandId: z.guid() });* of the brand's workspace (the Library asks when it opens), a brand at most* every two minutes: { checked, published: [{ draftId, url }], recent? }.*/-router.post('/webflow-status', cmsLimiter, async (req, res) => {+router.post('/webflow-status', cmsStatusLimiter, async (req, res) => {const parsed = webflowStatusBody.safeParse(req.body ?? {});if (!parsed.success) return res.status(400).json({ error: 'Invalid request', code: 'invalid' });const { brandId } = parsed.data;@@ -178,7 +178,7 @@ const wordpressChecked = new Map();* since, marked published at the post's link (cms/wordpress-status.js). As* /webflow-status: any member, a brand at most every two minutes.*/-router.post('/wordpress-status', cmsLimiter, async (req, res) => {+router.post('/wordpress-status', cmsStatusLimiter, async (req, res) => {const parsed = webflowStatusBody.safeParse(req.body ?? {});if (!parsed.success) return res.status(400).json({ error: 'Invalid request', code: 'invalid' });const { brandId } = parsed.data;@@ -213,7 +213,7 @@ const framerChecked = new Map();* marked published at the item's page (cms/framer-status.js). As* /webflow-status: any member, a brand at most every two minutes.*/-router.post('/framer-status', cmsLimiter, async (req, res) => {+router.post('/framer-status', cmsStatusLimiter, async (req, res) => {const parsed = webflowStatusBody.safeParse(req.body ?? {});if (!parsed.success) return res.status(400).json({ error: 'Invalid request', code: 'invalid' });const { brandId } = parsed.data;diff --git a/web/messages/en.json b/web/messages/en.jsonindex eec2471e9..55b304f5e 100644--- a/web/messages/en.json+++ b/web/messages/en.json@@ -9513,6 +9513,13 @@"integrations_cancel": "Cancel","integrations_connecting": "Connecting…","integrations_connect": "Connect",+ "integrations_connectFailed": "Couldn't start connecting {label}. Try again in a moment.",+ "integrations_connectTimedOut": "Connecting {label} took too long to start. Try again in a moment.",+ "integrations_connectForbidden": "Only admins and managers can connect integrations.",+ "integrations_statusFailed": "Couldn't check whether {label} is connected. Try again in a moment.",+ "integrations_statusTimedOut": "Checking {label} took too long. Try again in a moment.",+ "integrations_propertiesTimedOut": "Reading the properties took too long. Try again in a moment.",+ "integrations_retry": "Try again","integrations_propertyMapping": "Property mapping","integrations_notMapped": "Not mapped","integrations_selectProperty": "Select a property",@@ -9636,7 +9643,6 @@},"merchantCenter": {"description": "Your products and the problems Merchant Center reports for them. Google AI Overviews and AI Mode show products from it.",- "comingSoon": "Until it's available, add your products with a feed URL or a file upload in Product catalog below.","title": "Merchant Center account for {brand}","hint": "Pick the account that sells this brand's products. They're read every day into the brand's product catalog below, with their issues.","noBrand": "Pick a brand to add its Merchant Center account.",@@ -9874,7 +9880,6 @@},"integrations_connected": "Connected","integrations_notConfigured": "Not configured",- "integrations_comingSoon": "Coming soon","integrations_disconnect": "Disconnect","integrations_disconnectDescription": "The stored connection is removed for the whole organization. You can reconnect at any time.","removeMember": "Remove team member",diff --git a/web/src/app/api/aeo/[...path]/route.test.ts b/web/src/app/api/aeo/[...path]/route.test.tsnew file mode 100644index 000000000..7f4258ead--- /dev/null+++ b/web/src/app/api/aeo/[...path]/route.test.ts@@ -0,0 +1,84 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { NextRequest } from 'next/server';++/**+ * The same-origin proxy to the API: a read the API hasn't started answering+ * within a minute comes back as a 504 the page can say something about,+ * instead of hanging until the platform cuts the function off. Changes keep+ * their long limit (the suggestion runs).+ */++vi.mock('@/config/api', () => ({ API_BASE_URL: 'https://api.example' }));++const { GET, POST } = await import('./route');++const fetchMock = vi.fn();+beforeEach(() => {+ vi.useFakeTimers();+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ vi.spyOn(console, 'error').mockImplementation(() => {});+});+afterEach(() => {+ vi.useRealTimers();+});++/** An upstream that never answers, until the call is aborted. */+function hangs() {+ fetchMock.mockImplementation(+ (_url: URL, init: RequestInit) =>+ new Promise((_resolve, reject) => {+ init.signal?.addEventListener('abort', () =>+ reject(new DOMException('This operation was aborted', 'AbortError')),+ );+ }),+ );+}+const call = (handler: typeof GET, method: string, path: string[]) =>+ handler(+ new NextRequest(`http://localhost/api/aeo/${path.join('/')}`, {+ method,+ ...(method === 'GET' ? {} : { body: '{}' }),+ }),+ { params: Promise.resolve({ path }) },+ );++describe('/api/aeo proxy', () => {+ it("answers a read the API hasn't started answering in a minute with a 504", async () => {+ hangs();+ const pending = call(GET, 'GET', ['api', 'integrations', 'config']);+ await vi.advanceTimersByTimeAsync(59_000);+ expect(fetchMock.mock.calls[0][1].signal.aborted).toBe(false);+ await vi.advanceTimersByTimeAsync(1_000);+ const res = await pending;+ expect(res.status).toBe(504);+ expect(await res.json()).toEqual({+ error: 'API server took too long to answer',+ code: 'upstream_timeout',+ });+ expect(String(fetchMock.mock.calls[0][0])).toBe('https://api.example/api/integrations/config');+ });++ it('passes a read that answers in time through, and an unreachable API as a 502', async () => {+ fetchMock.mockResolvedValue(+ new Response(JSON.stringify({ ok: 1 }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ }),+ );+ const res = await call(GET, 'GET', ['api', 'catalog', 'connectors']);+ expect(res.status).toBe(200);+ expect(await res.json()).toEqual({ ok: 1 });++ fetchMock.mockRejectedValue(new TypeError('fetch failed'));+ const down = await call(GET, 'GET', ['api', 'catalog', 'connectors']);+ expect(down.status).toBe(502);+ expect(await down.json()).toEqual({ error: 'API server is unreachable' });+ });++ it('leaves a change without the read limit', async () => {+ fetchMock.mockResolvedValue(new Response('{}', { status: 200 }));+ await call(POST, 'POST', ['api', 'topics', 'suggest']);+ expect(fetchMock.mock.calls[0][1].signal).toBeUndefined();+ });+});diff --git a/web/src/app/api/aeo/[...path]/route.ts b/web/src/app/api/aeo/[...path]/route.tsindex e7ba19fe3..1fa8d6458 100644--- a/web/src/app/api/aeo/[...path]/route.ts+++ b/web/src/app/api/aeo/[...path]/route.ts@@ -37,6 +37,15 @@ export const maxDuration = 300;/** Never cache a proxied call: every one of these is per-brand and mutating-ish. */export const dynamic = 'force-dynamic';+/**+ * A read (GET, HEAD) gives up once the API hasn't started answering in this+ * long, with a 504 the page can say something about: a hung upstream used to+ * leave cards on their skeletons until the platform cut the function off,+ * minutes later. Changes keep maxDuration: the suggestion runs above are+ * POSTs. Once the API answers, its body streams through without a limit.+ */+const READ_TIMEOUT_MS = 60_000;+/*** Headers that describe *this* connection rather than the request, and so* must not be replayed upstream — `host` would misroute virtual hosts, and a@@ -72,6 +81,10 @@ async function forward(request: NextRequest, params: Promise<{ path: string[] }>const hasBody = request.method !== 'GET' && request.method !== 'HEAD';+ // A read's time limit runs until the API's answer starts, not through its body.+ const timeout = hasBody ? null : new AbortController();+ const timer = timeout && setTimeout(() => timeout.abort(), READ_TIMEOUT_MS);+let response: Response;try {response = await fetch(upstream, {@@ -79,12 +92,22 @@ async function forward(request: NextRequest, params: Promise<{ path: string[] }>headers,body: hasBody ? await request.arrayBuffer() : undefined,cache: 'no-store',+ signal: timeout?.signal,});} catch (err) {+ if (timeout?.signal.aborted) {+ console.error('[aeo-proxy] upstream timed out', upstream.pathname);+ return NextResponse.json(+ { error: 'API server took too long to answer', code: 'upstream_timeout' },+ { status: 504 },+ );+ }// The upstream being unreachable used to surface as an opaque browser// network error. Name it, so the next outage is one log line away.console.error('[aeo-proxy] upstream unreachable', upstream.pathname, err);return NextResponse.json({ error: 'API server is unreachable' }, { status: 502 });+ } finally {+ if (timer) clearTimeout(timer);}// Only content-type is copied. `fetch` has already decoded the body, sodiff --git a/web/src/components/settings/catalog-sources-card.test.tsx b/web/src/components/settings/catalog-sources-card.test.tsxindex 0904b8543..0f8ffd2dd 100644--- a/web/src/components/settings/catalog-sources-card.test.tsx+++ b/web/src/components/settings/catalog-sources-card.test.tsx@@ -530,4 +530,22 @@ describe('CatalogSourcesCard', () => {expect.objectContaining({ brandId: 'b1', sources: [FEED] }),);});++ it("says the sources can't be read once a read takes too long, instead of a lasting skeleton", async () => {+ vi.useFakeTimers();+ try {+ listCatalogSources.mockReturnValue(new Promise(() => {}));+ const onSources = vi.fn();+ await render({ onSources });+ expect(container.querySelector('[data-slot="skeleton"]')).not.toBeNull();+ await act(async () => void (await vi.advanceTimersByTimeAsync(15_000)));+ expect(container.querySelector('[data-slot="skeleton"]')).toBeNull();+ expect(container.textContent).toContain("Couldn't read the catalog's sources right now.");+ expect(onSources).toHaveBeenLastCalledWith(+ expect.objectContaining({ brandId: 'b1', sources: null }),+ );+ } finally {+ vi.useRealTimers();+ }+ });});diff --git a/web/src/components/settings/catalog-sources-card.tsx b/web/src/components/settings/catalog-sources-card.tsxindex 4ec1a0854..294795f07 100644--- a/web/src/components/settings/catalog-sources-card.tsx+++ b/web/src/components/settings/catalog-sources-card.tsx@@ -12,6 +12,7 @@ import { Link } from '@/i18n/navigation';import { useUserRole } from '@/hooks/use-user-role';import { useUpgradeGate } from '@/components/providers/upgrade-gate';import { addFeedSource, listCatalogSources, removeCatalogSource } from '@/lib/actions/catalog';+import { withReadTimeout } from '@/lib/integrations-client';import { isStoreSource, SIGN_IN_PLATFORM_LABELS, type CatalogSource } from '@/lib/catalog';import {connectStore,@@ -106,7 +107,8 @@ export function CatalogSourcesCard({useEffect(() => {if (!activeBrandId) return;let cancelled = false;- listCatalogSources(activeBrandId).then(+ // A read that takes too long says the sources can't be read, like one that fails.+ withReadTimeout(listCatalogSources(activeBrandId)).then((sources) => {if (!cancelled) setLoaded({ brandId: activeBrandId, sources, at: new Date() });},diff --git a/web/src/components/settings/integrations-section.test.tsx b/web/src/components/settings/integrations-section.test.tsxindex 237298a37..a8470aa22 100644--- a/web/src/components/settings/integrations-section.test.tsx+++ b/web/src/components/settings/integrations-section.test.tsx@@ -5,24 +5,39 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import messages from '../../../messages/en.json';import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';-/** Each provider's status as the API answers it: an Error is a failed read. */-const statuses: Record<string, string | Error> = {};-const cloud = { on: false };-vi.mock('@/config/plans', async (importOriginal) => ({- ...(await importOriginal<typeof import('@/config/plans')>()),- isCloud: () => cloud.on,+/**+ * Each provider's status as the API answers it: a failure is a read that+ * didn't come back (timed out or failed), a promise one still on its way.+ */+type StatusAnswer =+ | string+ | { ok: false; reason: 'timeout' | 'failed' }+ | Promise<{ ok: true; value: string }>;+const statuses: Record<string, StatusAnswer> = {};+/** The server's config: whether it offers Merchant Center, null when it can't be read. */+const config = vi.hoisted(() => ({+ answer: { googleMerchantCenter: true } as+ | { googleMerchantCenter: boolean }+ | null+ | Promise<{ googleMerchantCenter: boolean } | null>,}));const integrations = vi.hoisted(() => ({- getIntegrationStatus: vi.fn(),disconnectIntegration: vi.fn(),- getGscProperties: vi.fn(),getGscBrandMappings: vi.fn(),setBrandGscProperty: vi.fn(),- getGaProperties: vi.fn(),getGaBrandMappings: vi.fn(),setBrandGaProperty: vi.fn(),}));vi.mock('@/lib/actions/integrations', () => integrations);+const client = vi.hoisted(() => ({+ readIntegrationStatus: vi.fn(),+ readIntegrationsConfig: vi.fn(),+ readGscProperties: vi.fn(),+ readGaProperties: vi.fn(),+ withReadTimeout: <T,>(promise: Promise<T>) => promise,+ isTimeout: (err: unknown) => (err as { name?: string })?.name === 'TimeoutError',+}));+vi.mock('@/lib/integrations-client', () => client);vi.mock('@/hooks/use-integration-connect', () => ({useIntegrationConnect: () => ({ connecting: false, connect: vi.fn() }),}));@@ -61,11 +76,12 @@ const openUpgrade = vi.fn();beforeEach(() => {vi.clearAllMocks();for (const key of Object.keys(statuses)) delete statuses[key];- cloud.on = false;- integrations.getIntegrationStatus.mockImplementation(async (provider: string) => {+ config.answer = { googleMerchantCenter: true };+ client.readIntegrationsConfig.mockImplementation(async () => config.answer);+ client.readIntegrationStatus.mockImplementation(async (provider: string) => {const status = statuses[provider] ?? 'not_connected';- if (status instanceof Error) throw status;- return { status };+ if (typeof status === 'string') return { ok: true, value: status };+ return status;});container = document.createElement('div');document.body.appendChild(container);@@ -103,8 +119,14 @@ function groupOf(element: Element | null) {}const byText = (text: string) =>[...container.querySelectorAll('p')].find((p) => p.textContent === text) ?? null;-/** Merchant Center's card: its row and the lines under it. */-const merchantCenter = () => byText('Google Merchant Center')?.closest('.space-y-4') ?? null;+/** A card by its name: its row and the lines under it. */+const cardOf = (label: string) => byText(label)?.closest('.space-y-4') ?? null;+const merchantCenter = () => cardOf('Google Merchant Center');+/** A group's section, by its heading. */+const groupNamed = (title: string) =>+ headings()+ .find((h) => h.textContent === title)+ ?.closest('section') ?? null;/** The badges a card shows, by their words. */const badges = (card: Element) =>[...card.querySelectorAll('[class*="group/badge"]')].map((b) => b.textContent);@@ -135,56 +157,92 @@ describe('IntegrationsSection', () => {expect(groupOf(byText('Google Analytics'))).toBeNull();});- it("keeps Merchant Center's card hidden while its status can't be read, without a toast", async () => {- statuses['google-merchant-center'] = new Error('Unknown integration provider.');- vi.mocked(toast.error).mockClear();+ it("hides Merchant Center's card where the server doesn't offer it, with no Coming soon", async () => {+ config.answer = { googleMerchantCenter: false };await render();expect(byText('Google Merchant Center')).toBeNull();- expect(toast.error).not.toHaveBeenCalled();- // The other cards are there.- expect(byText('Google Search Console')).not.toBeNull();- expect(container.querySelector('[data-card="catalog"]')).not.toBeNull();+ expect(container.textContent).not.toContain('Coming soon');+ expect(container.textContent).not.toContain('COMPOSIO_GMC_AUTH_CONFIG_ID');+ // Its status isn't read at all.+ expect(client.readIntegrationStatus).not.toHaveBeenCalledWith('google-merchant-center');+ // The group keeps its heading, with the product catalog alone in it.+ const stores = groupNamed('Stores and marketplaces')!;+ expect(stores.querySelector('[data-card="catalog"]')).not.toBeNull();+ expect(stores.querySelector('[data-slot="skeleton"]')).toBeNull();});- it('says Coming soon on the cloud while it is not set up there, with nothing to connect', async () => {- statuses['google-merchant-center'] = 'not_configured';- cloud.on = true;+ it("hides Merchant Center's card when the config can't be read: an older API offers nothing", async () => {+ config.answer = null;await render();- const card = merchantCenter()!;- expect(card).not.toBeNull();- expect(badges(card)).toEqual(['Coming soon']);- expect(card.textContent).toContain(- "Until it's available, add your products with a feed URL or a file upload in Product catalog below.",- );- expect(card.querySelector('button')).toBeNull();- // Not the self-hosted set-up line, nor its badge.- expect(card.textContent).not.toContain('Not configured');- expect(card.textContent).not.toContain('COMPOSIO_GMC_AUTH_CONFIG_ID');+ expect(byText('Google Merchant Center')).toBeNull();+ expect(byText('Google Search Console')).not.toBeNull();+ expect(container.querySelector('[data-card="catalog"]')).not.toBeNull();});- it('keeps the set-up line on a self-hosted server that is not set up for it', async () => {- statuses['google-merchant-center'] = 'not_configured';- cloud.on = false;+ it("shows no skeleton for Merchant Center while the config is read, and doesn't wait on a status", async () => {+ let offer!: (answer: { googleMerchantCenter: boolean }) => void;+ config.answer = new Promise((resolve) => (offer = resolve));+ // Search Console's status still on its way: the config doesn't wait for it.+ statuses['google-search-console'] = new Promise(() => {});await render();- const card = merchantCenter()!;- expect(card).not.toBeNull();- expect(badges(card)).toEqual(['Not configured']);- expect(card.textContent).toContain('COMPOSIO_GMC_AUTH_CONFIG_ID');- expect(card.textContent).not.toContain('Coming soon');- expect(card.textContent).not.toContain('Until it');+ const stores = groupNamed('Stores and marketplaces')!;+ expect(byText('Google Merchant Center')).toBeNull();+ expect(stores.querySelector('[data-slot="skeleton"]')).toBeNull();+ expect(stores.querySelector('[data-card="catalog"]')).not.toBeNull();++ await act(async () => offer({ googleMerchantCenter: true }));+ expect(groupOf(byText('Google Merchant Center'))).toBe('Stores and marketplaces');+ expect(cardOf('Google Search Console')!.querySelector('[data-slot="skeleton"]')).not.toBeNull();+ });- // A provider without it keeps the set-up line.+ it('keeps the set-up line on a server without credentials for a provider', async () => {statuses['google-search-console'] = 'not_configured';- act(() => root.unmount());- root = createRoot(container);await render();- const gsc = byText('Google Search Console')!.closest('.space-y-4')!;- expect(gsc.textContent).toContain('Not configured');+ const gsc = cardOf('Google Search Console')!;+ expect(badges(gsc)).toEqual(['Not configured']);expect(gsc.textContent).toContain('COMPOSIO_GSC_AUTH_CONFIG_ID');- expect(gsc.textContent).not.toContain('Coming soon');});- it('connects Merchant Center as before once the server is set up for it', async () => {+ it('reads each card on its own: a status that hangs leaves the others ready', async () => {+ statuses['google-analytics'] = new Promise(() => {});+ await render();+ // Analytics waits on its own skeleton…+ expect(cardOf('Google Analytics')!.querySelector('[data-slot="skeleton"]')).not.toBeNull();+ // …while Search Console and Merchant Center can connect, and the catalog is there.+ for (const label of ['Google Search Console', 'Google Merchant Center']) {+ expect([...cardOf(label)!.querySelectorAll('button')].map((b) => b.textContent)).toEqual([+ 'Connect',+ ]);+ }+ expect(container.querySelector('[data-card="catalog"]')).not.toBeNull();+ });++ it.each([+ ['timeout', 'Checking Google Analytics took too long. Try again in a moment.'],+ ['failed', "Couldn't check whether Google Analytics is connected. Try again in a moment."],+ ] as const)(+ "says a status that %s couldn't be checked, with Try again in place of the skeleton",+ async (reason, message) => {+ statuses['google-analytics'] = { ok: false, reason };+ await render();+ const ga = cardOf('Google Analytics')!;+ expect(ga.querySelector('[data-slot="skeleton"]')).toBeNull();+ expect(ga.querySelector('[role="status"]')?.textContent).toBe(message);+ // Not a Connect that may not be needed, nor a toast.+ const retry = [...ga.querySelectorAll('button')];+ expect(retry.map((b) => b.textContent)).toEqual(['Try again']);+ expect(toast.error).not.toHaveBeenCalled();++ // Try again reads it again.+ statuses['google-analytics'] = 'not_connected';+ await act(async () => retry[0].click());+ expect(client.readIntegrationStatus).toHaveBeenLastCalledWith('google-analytics');+ expect([...ga.querySelectorAll('button')].map((b) => b.textContent)).toEqual(['Connect']);+ expect(ga.querySelector('[role="status"]')).toBeNull();+ },+ );++ it('connects Merchant Center as before where the server offers it', async () => {statuses['google-merchant-center'] = 'not_connected';await render();const card = merchantCenter()!;@@ -250,14 +308,17 @@ async function pick(row: number, label: string) {*/describe('IntegrationsSection property mapping', () => {beforeEach(() => {- integrations.getIntegrationStatus.mockImplementation(async (provider: string) => ({- configured: provider === 'google-search-console',- status: provider === 'google-search-console' ? 'connected' : 'not_configured',+ client.readIntegrationStatus.mockImplementation(async (provider: string) => ({+ ok: true,+ value: provider === 'google-search-console' ? 'connected' : 'not_configured',}));- integrations.getGscProperties.mockResolvedValue([- { siteUrl: 'https://acme.com/', permissionLevel: 'siteOwner' },- { siteUrl: 'https://other.example/', permissionLevel: 'siteOwner' },- ]);+ client.readGscProperties.mockResolvedValue({+ ok: true,+ value: [+ { siteUrl: 'https://acme.com/', permissionLevel: 'siteOwner' },+ { siteUrl: 'https://other.example/', permissionLevel: 'siteOwner' },+ ],+ });// Acme matches one property by its domain; Beta matches none.integrations.getGscBrandMappings.mockResolvedValue([{ brandId: 'b1', brandName: 'Acme', gscProperty: null, domains: ['acme.com'] },@@ -290,4 +351,18 @@ describe('IntegrationsSection property mapping', () => {);expect(openUpgrade).not.toHaveBeenCalled();});++ it('says the properties took too long, and reads them again on Try again', async () => {+ client.readGscProperties.mockResolvedValueOnce({ ok: false, reason: 'timeout' });+ await render(false);+ expect(container.textContent).toContain("Couldn't load Search Console properties.");+ expect(container.textContent).toContain(+ 'Reading the properties took too long. Try again in a moment.',+ );+ const retry = [...container.querySelectorAll('button')].find(+ (b) => b.textContent === 'Try again',+ )!;+ await act(async () => retry.click());+ expect(container.querySelectorAll('[role="combobox"]')).toHaveLength(2);+ });});diff --git a/web/src/components/settings/integrations-section.tsx b/web/src/components/settings/integrations-section.tsxindex 1820f11f9..9aa0ff878 100644--- a/web/src/components/settings/integrations-section.tsx+++ b/web/src/components/settings/integrations-section.tsx@@ -26,20 +26,26 @@ import {import { BarChart3, Loader2, Search, ShoppingBag, Unplug } from 'lucide-react';import { useTranslations } from 'next-intl';import {- getIntegrationStatus,disconnectIntegration,- getGscProperties,getGscBrandMappings,setBrandGscProperty,- getGaProperties,getGaBrandMappings,setBrandGaProperty,type IntegrationProvider,type IntegrationStatus,} from '@/lib/actions/integrations';+import {+ readGaProperties,+ readGscProperties,+ readIntegrationStatus,+ readIntegrationsConfig,+ isTimeout,+ withReadTimeout,+ type IntegrationFailure,+ type IntegrationResult,+} from '@/lib/integrations-client';import { matchProperty } from '@/lib/property-match';import { MERCHANT_CENTER_LABEL } from '@/lib/catalog';-import { isCloud } from '@/config/plans';import { CatalogSourcesCard, type CatalogSourcesRead } from './catalog-sources-card';import { CatalogCategoryPages } from './catalog-category-pages';import { FramerCard } from './framer-card';@@ -61,9 +67,26 @@ import { useUpgradeGate } from '@/components/providers/upgrade-gate';* way, then each brand picks its account, whose products land in the* product catalog card below it. Content management systems: where Send to* CMS puts a brand's pages.+ *+ * Every card reads on its own, from the browser or with a timeout, so a slow+ * or failing one never holds up the rest: each says when it couldn't be read.*/export function IntegrationsSection() {const t = useTranslations('settings');+ // Merchant Center's card shows only where this server offers it (its Composio auth config),+ // as the API's config says: env only, read at once and never behind a status. Until it+ // says so the card isn't there, with no skeleton; a config that can't be read (an older+ // API, or one that is down) offers nothing.+ const [merchantCenterOffered, setMerchantCenterOffered] = useState(false);+ useEffect(() => {+ let cancelled = false;+ void readIntegrationsConfig().then((config) => {+ if (!cancelled) setMerchantCenterOffered(config?.googleMerchantCenter === true);+ });+ return () => {+ cancelled = true;+ };+ }, []);// Bumped when a brand adds a Merchant Center account, so the catalog card lists it.const [catalogReads, setCatalogReads] = useState(0);// The catalog's sources as its card read them, for the picker to mark the accounts added.@@ -108,20 +131,20 @@ export function IntegrationsSection() {</IntegrationCard><IntegrationGroup title={t('integrations_stores')}>- <IntegrationCard- provider="google-merchant-center"- label={MERCHANT_CENTER_LABEL}- description={t('merchantCenter.description')}- icon={<ShoppingBag className="h-5 w-5 text-muted-foreground" />}- authConfigEnv="COMPOSIO_GMC_AUTH_CONFIG_ID"- hideUnavailable- comingSoon={t('merchantCenter.comingSoon')}- >- <MerchantCenterAccounts- sources={catalogSources}- onConnected={() => setCatalogReads((n) => n + 1)}- />- </IntegrationCard>+ {merchantCenterOffered && (+ <IntegrationCard+ provider="google-merchant-center"+ label={MERCHANT_CENTER_LABEL}+ description={t('merchantCenter.description')}+ icon={<ShoppingBag className="h-5 w-5 text-muted-foreground" />}+ authConfigEnv="COMPOSIO_GMC_AUTH_CONFIG_ID"+ >+ <MerchantCenterAccounts+ sources={catalogSources}+ onConnected={() => setCatalogReads((n) => n + 1)}+ />+ </IntegrationCard>+ )}<CatalogSourcesCard refreshKey={catalogReads} onSources={onCatalogSources} />@@ -161,15 +184,9 @@ function IntegrationGroup({ title, children }: { title: string; children: ReactN* One integration row: status badge, Connect / Disconnect, and whatever the* provider wants to render once connected (`children`).*- * `hideUnavailable`: a newer integration's card isn't shown while its status- * can't be read (an API older than the web), nor on the cloud while it isn't- * set up there; a self-hosted server keeps the set-up line.- *- * `comingSoon`: while the cloud isn't set up for it, the card says Coming- * soon and this line instead, with nothing to connect (Google Merchant- * Center, until Google approves the connection); a self-hosted server keeps- * the set-up line. Sources a brand added before stay in Product catalog,- * where they're removed.+ * Its status is read on its own (lib/integrations-client.ts): one that is+ * slow or fails leaves the other cards be, and after its timeout the card+ * says it couldn't check, with Try again in place of the skeleton.*/function IntegrationCard({provider,@@ -177,8 +194,6 @@ function IntegrationCard({description,icon,authConfigEnv,- hideUnavailable = false,- comingSoon,children,}: {provider: IntegrationProvider;@@ -186,13 +201,12 @@ function IntegrationCard({description: string;icon: ReactNode;authConfigEnv: string;- hideUnavailable?: boolean;- comingSoon?: string;children?: ReactNode;}) {const t = useTranslations('settings');const [status, setStatus] = useState<IntegrationStatus | null>(null);- const [unreadable, setUnreadable] = useState(false);+ // Why the last read of the status didn't come back, while there's no status.+ const [failure, setFailure] = useState<IntegrationFailure | null>(null);const [disconnecting, setDisconnecting] = useState(false);const { connecting, connect: handleConnect } = useIntegrationConnect(provider, {label,@@ -201,22 +215,14 @@ function IntegrationCard({});const load = useCallback(async () => {- try {- const result = await getIntegrationStatus(provider);- setStatus(result.status);- } catch (err) {- console.error(`Failed to load ${provider} status:`, err);- if (hideUnavailable) {- setUnreadable(true);- return;- }- toast.error('Failed to load integration status');- setStatus('not_connected');- }- }, [provider, hideUnavailable]);+ setFailure(null);+ const result = await readIntegrationStatus(provider);+ if (result.ok) setStatus(result.value);+ else setFailure(result.reason);+ }, [provider]);useEffect(() => {- load();+ void load();}, [load]);const handleDisconnect = async () => {@@ -232,11 +238,6 @@ function IntegrationCard({}};- const soon = comingSoon !== undefined && status === 'not_configured' && isCloud();- if (hideUnavailable && (unreadable || (status === 'not_configured' && isCloud() && !soon))) {- return null;- }-return (<div className="space-y-4"><div className="flex items-center justify-between gap-4 rounded-lg border p-4">@@ -255,17 +256,16 @@ function IntegrationCard({{t('integrations_connected')}</Badge>)}- {soon && (- <Badge variant="secondary" className="bg-muted text-muted-foreground">- {t('integrations_comingSoon')}- </Badge>- )}</div><p className="text-xs text-muted-foreground truncate">{description}</p></div></div>- {soon ? null : status === null ? (+ {status === null && failure ? (+ <Button variant="outline" size="sm" className="shrink-0" onClick={() => void load()}>+ {t('integrations_retry')}+ </Button>+ ) : status === null ? (<Skeleton className="h-8 w-24" />) : status === 'not_configured' ? (<Badge variant="outline" className="text-muted-foreground shrink-0">@@ -317,9 +317,15 @@ function IntegrationCard({)}</div>- {soon && <p className="text-xs text-muted-foreground">{comingSoon}</p>}+ {status === null && failure && (+ <p role="status" className="text-xs text-muted-foreground">+ {t(failure === 'timeout' ? 'integrations_statusTimedOut' : 'integrations_statusFailed', {+ label,+ })}+ </p>+ )}- {status === 'not_configured' && !soon && (+ {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{' '}@@ -372,14 +378,15 @@ function PropertyMapping({sourceName: string;description: string;emptyMessage: string;- loadOptions: () => Promise<PropertyOption[]>;+ loadOptions: () => Promise<IntegrationResult<PropertyOption[]>>;loadRows: () => Promise<BrandPropertyRow[]>;save: (brandId: string, value: string | null) => Promise<void>;}) {const t = useTranslations('settings');const [options, setOptions] = useState<PropertyOption[] | null>(null);const [rows, setRows] = useState<BrandPropertyRow[] | null>(null);- const [loadFailed, setLoadFailed] = useState<string | null>(null);+ // Why the properties couldn't be read: they took too long, or the API's words.+ const [loadFailed, setLoadFailed] = useState<'timeout' | { message: string } | null>(null);const [savingBrandId, setSavingBrandId] = useState<string | null>(null);const autoMatched = useRef(false);// A read-only workspace (plan not active): picking a property opens the@@ -390,11 +397,23 @@ function PropertyMapping({const load = useCallback(async () => {setLoadFailed(null);try {- const [properties, brands] = await Promise.all([loadOptions(), loadRows()]);- setOptions(properties);+ const [properties, brands] = await Promise.all([loadOptions(), withReadTimeout(loadRows())]);+ if (!properties.ok) {+ setLoadFailed(+ properties.reason === 'timeout'+ ? 'timeout'+ : { message: properties.error ?? 'Failed to load properties' },+ );+ return;+ }+ setOptions(properties.value);setRows(brands);} catch (err) {- setLoadFailed(err instanceof Error ? err.message : 'Failed to load properties');+ setLoadFailed(+ isTimeout(err)+ ? 'timeout'+ : { message: err instanceof Error ? err.message : 'Failed to load properties' },+ );}}, [loadOptions, loadRows]);@@ -445,9 +464,11 @@ function PropertyMapping({return (<div className="rounded-lg border p-4 text-sm"><p className="text-muted-foreground">Couldn't load {sourceName} properties.</p>- <p className="mt-1 text-xs text-muted-foreground">{loadFailed}</p>+ <p className="mt-1 text-xs text-muted-foreground">+ {loadFailed === 'timeout' ? t('integrations_propertiesTimedOut') : loadFailed.message}+ </p><Button variant="outline" size="sm" className="mt-3" onClick={load}>- Retry+ {t('integrations_retry')}</Button></div>);@@ -515,9 +536,13 @@ function PropertyMapping({// Loaders live at module scope so their identity is stable across renders —// PropertyMapping's effects depend on them.-async function loadGscOptions(): Promise<PropertyOption[]> {- const properties = await getGscProperties();- return properties.map((p) => ({ value: p.siteUrl, label: p.siteUrl, siteUrls: [p.siteUrl] }));+async function loadGscOptions(): Promise<IntegrationResult<PropertyOption[]>> {+ const result = await readGscProperties();+ if (!result.ok) return result;+ return {+ ok: true,+ value: result.value.map((p) => ({ value: p.siteUrl, label: p.siteUrl, siteUrls: [p.siteUrl] })),+ };}async function loadGscRows(): Promise<BrandPropertyRow[]> {@@ -543,16 +568,20 @@ function GscPropertyMapping() {);}-async function loadGaOptions(): Promise<PropertyOption[]> {- const properties = await getGaProperties();- return properties.map((p) => ({- value: p.propertyId,- // Display names repeat across accounts ("GA4"), so the id disambiguates.- label: p.accountName- ? `${p.displayName} · ${p.accountName} (${p.propertyId})`- : `${p.displayName} (${p.propertyId})`,- siteUrls: p.siteUrls,- }));+async function loadGaOptions(): Promise<IntegrationResult<PropertyOption[]>> {+ const result = await readGaProperties();+ if (!result.ok) return result;+ return {+ ok: true,+ value: result.value.map((p) => ({+ value: p.propertyId,+ // Display names repeat across accounts ("GA4"), so the id disambiguates.+ label: p.accountName+ ? `${p.displayName} · ${p.accountName} (${p.propertyId})`+ : `${p.displayName} (${p.propertyId})`,+ siteUrls: p.siteUrls,+ })),+ };}async function loadGaRows(): Promise<BrandPropertyRow[]> {diff --git a/web/src/hooks/use-integration-connect.test.tsx b/web/src/hooks/use-integration-connect.test.tsxindex 908096ed0..3511aca97 100644--- a/web/src/hooks/use-integration-connect.test.tsx+++ b/web/src/hooks/use-integration-connect.test.tsx@@ -9,17 +9,20 @@ import { UpgradeDialogContext } from '@/components/providers/upgrade-gate';* 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. On a read-only workspace (plan not active)- * it opens the upgrade dialog instead and starts nothing.+ * it opens the upgrade dialog instead and starts nothing. Its calls go from+ * the browser (never a server action waiting behind the page's), and a+ * Connect that can't start says why.*/const actions = vi.hoisted(() => ({- connectIntegration: vi.fn(),- getIntegrationStatus: vi.fn(),+ startIntegrationConnect: vi.fn(),+ readIntegrationStatus: vi.fn(),}));-vi.mock('@/lib/actions/integrations', () => actions);+vi.mock('@/lib/integrations-client', () => actions);vi.mock('sonner', () => ({ toast: { success: vi.fn(), error: vi.fn() } }));const { useIntegrationConnect } = await import('./use-integration-connect');+const { toast } = await import('sonner');(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =true;@@ -48,7 +51,10 @@ beforeEach(() => {vi.useFakeTimers();vi.clearAllMocks();popup.closed = false;- actions.connectIntegration.mockResolvedValue({ redirectUrl: 'https://oauth.example/start' });+ actions.startIntegrationConnect.mockResolvedValue({+ ok: true,+ value: 'https://oauth.example/start',+ });vi.spyOn(window, 'open').mockReturnValue(popup as unknown as Window);container = document.createElement('div');root = createRoot(container);@@ -76,9 +82,9 @@ afterEach(() => {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' });+ actions.readIntegrationStatus+ .mockResolvedValueOnce({ ok: true, value: 'not_connected' })+ .mockResolvedValueOnce({ ok: true, value: 'connected' });let done!: Promise<void>;act(() => {done = connect();@@ -86,7 +92,7 @@ describe('useIntegrationConnect', () => {await act(async () => void (await vi.advanceTimersByTimeAsync(6000)));await done;- expect(actions.connectIntegration).toHaveBeenCalledWith(+ expect(actions.startIntegrationConnect).toHaveBeenCalledWith('google-analytics','https://app.example/dashboard/traffic',);@@ -100,7 +106,7 @@ describe('useIntegrationConnect', () => {});it('reports the final status when the user closes the popup', async () => {- actions.getIntegrationStatus.mockResolvedValue({ status: 'not_connected' });+ actions.readIntegrationStatus.mockResolvedValue({ ok: true, value: 'not_connected' });let done!: Promise<void>;act(() => {done = connect();@@ -112,13 +118,13 @@ describe('useIntegrationConnect', () => {});it('stops polling once its caller is gone', async () => {- actions.getIntegrationStatus.mockResolvedValue({ status: 'not_connected' });+ actions.readIntegrationStatus.mockResolvedValue({ ok: true, value: 'not_connected' });act(() => {void connect();});await act(async () => void (await vi.advanceTimersByTimeAsync(10)));act(() => root.unmount());- actions.getIntegrationStatus.mockResolvedValue({ status: 'connected' });+ actions.readIntegrationStatus.mockResolvedValue({ ok: true, value: 'connected' });await vi.advanceTimersByTimeAsync(10_000);expect(onStatus).not.toHaveBeenCalled();// Re-mount for afterEach's unmount.@@ -129,7 +135,40 @@ describe('useIntegrationConnect', () => {render(true);await act(async () => void harness.connect!());expect(openUpgrade).toHaveBeenCalledExactlyOnceWith('Connecting an integration needs a plan');- expect(actions.connectIntegration).not.toHaveBeenCalled();+ expect(actions.startIntegrationConnect).not.toHaveBeenCalled();+ expect(window.open).not.toHaveBeenCalled();+ });++ it('keeps polling through a status read that fails', async () => {+ actions.readIntegrationStatus+ .mockResolvedValueOnce({ ok: false, reason: 'timeout' })+ .mockResolvedValueOnce({ ok: true, value: 'connected' });+ let done!: Promise<void>;+ act(() => {+ done = connect();+ });+ await act(async () => void (await vi.advanceTimersByTimeAsync(6000)));+ await done;+ expect(onStatus).toHaveBeenCalledExactlyOnceWith('connected');+ });++ it.each([+ ['failed', "Couldn't start connecting Google Analytics. Try again in a moment."],+ ['timeout', 'Connecting Google Analytics took too long to start. Try again in a moment.'],+ ['forbidden', 'Only admins and managers can connect integrations.'],+ ])('says why a Connect could not start (%s), and opens no popup', async (reason, message) => {+ actions.startIntegrationConnect.mockResolvedValue({ ok: false, reason });+ await act(async () => void (await connect()));+ expect(toast.error).toHaveBeenCalledExactlyOnceWith(message);+ expect(window.open).not.toHaveBeenCalled();+ expect(onStatus).not.toHaveBeenCalled();+ });++ it("opens the upgrade dialog when the API says the workspace's plan isn't active", async () => {+ actions.startIntegrationConnect.mockResolvedValue({ ok: false, reason: 'subscription' });+ await act(async () => void (await connect()));+ expect(openUpgrade).toHaveBeenCalledOnce();+ expect(toast.error).not.toHaveBeenCalled();expect(window.open).not.toHaveBeenCalled();});});diff --git a/web/src/hooks/use-integration-connect.ts b/web/src/hooks/use-integration-connect.tsindex 943ef7597..ce786ca03 100644--- a/web/src/hooks/use-integration-connect.ts+++ b/web/src/hooks/use-integration-connect.ts@@ -4,17 +4,24 @@ import { useEffect, useRef, useState } from 'react';import { useTranslations } from 'next-intl';import { toast } from 'sonner';import { useUpgradeGate } from '@/components/providers/upgrade-gate';+import type { IntegrationProvider, IntegrationStatus } from '@/lib/actions/integrations';import {- connectIntegration,- getIntegrationStatus,- type IntegrationProvider,- type IntegrationStatus,-} from '@/lib/actions/integrations';+ readIntegrationStatus,+ startIntegrationConnect,+ type IntegrationFailure,+} from '@/lib/integrations-client';/** How long the popup flow waits for Composio to report the account (#577). */const CONNECT_DEADLINE_MS = 120_000;const CONNECT_POLL_MS = 3000;+/** What a Connect that couldn't start says (a read-only workspace opens the upgrade dialog). */+const CONNECT_ERRORS = {+ timeout: 'integrations_connectTimedOut',+ forbidden: 'integrations_connectForbidden',+ failed: 'integrations_connectFailed',+} as const satisfies Record<Exclude<IntegrationFailure, 'subscription'>, string>;+/*** Connect a Google integration in an OAuth popup, polling until Composio* reports the account connected. Shared by Settings › Integrations and AI@@ -25,7 +32,9 @@ const CONNECT_POLL_MS = 3000;* `onStatus` hears the outcome: 'connected', or whatever the final check* said once the user closed the popup. An unmounted caller stops polling.* On a read-only workspace (plan not active) `connect` opens the upgrade- * dialog instead.+ * dialog instead. The calls go from the browser (lib/integrations-client.ts),+ * so Connect never waits behind a page's server actions, and one that can't+ * start says why.*/export function useIntegrationConnect(provider: IntegrationProvider,@@ -40,7 +49,8 @@ export function useIntegrationConnect(},) {const [connecting, setConnecting] = useState(false);- const { guard } = useUpgradeGate();+ const { guard, openUpgrade } = useUpgradeGate();+ const t = useTranslations('settings');const tActions = useTranslations('readOnly.actions');// Bumped to stop a poll: a newer attempt, or the caller unmounting.const pollGen = useRef(0);@@ -56,7 +66,13 @@ export function useIntegrationConnect(setConnecting(true);const gen = ++pollGen.current;try {- const { redirectUrl } = await connectIntegration(provider, callbackUrl());+ const started = await startIntegrationConnect(provider, callbackUrl());+ if (!started.ok) {+ if (started.reason === 'subscription') openUpgrade();+ else toast.error(t(CONNECT_ERRORS[started.reason], { label }));+ return;+ }+ const redirectUrl = started.value;const popup = window.open(redirectUrl, `${provider}-oauth`, 'width=560,height=720');if (!popup) {@@ -69,23 +85,21 @@ export function useIntegrationConnect(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+ // A read that fails is transient: keep polling until the deadline.+ const result = await readIntegrationStatus(provider);+ if (result.ok && result.value === 'connected') {+ onStatus('connected');+ toast.success(`${label} connected`);+ popup.close();+ return;}if (popup.closed) {// User closed the window — one final check, then give up quietly.- const result = await getIntegrationStatus(provider).catch(() => null);+ const final = await readIntegrationStatus(provider);if (pollGen.current !== gen) return;- onStatus(result?.status ?? 'not_connected');- if (result?.status === 'connected') {+ const status = final.ok ? final.value : 'not_connected';+ onStatus(status);+ if (status === 'connected') {toast.success(`${label} connected`);}return;@@ -95,7 +109,8 @@ export function useIntegrationConnect(toast.error('Connection timed out — try again.');}} catch (err) {- toast.error(err instanceof Error ? err.message : 'Failed to start connection');+ console.error(`Failed to connect ${provider}:`, err);+ toast.error(t('integrations_connectFailed', { label }));} finally {if (pollGen.current === gen) setConnecting(false);}diff --git a/web/src/lib/actions/integrations.test.ts b/web/src/lib/actions/integrations.test.tsnew file mode 100644index 000000000..d382b9e43--- /dev/null+++ b/web/src/lib/actions/integrations.test.ts@@ -0,0 +1,65 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The integrations server actions that remain: each call to the API has a+ * time limit, so one that hangs can't hold up the page's other server actions+ * (Next runs them one at a time) for good.+ */++const update = vi.hoisted(() => vi.fn());+vi.mock('@/lib/supabase/server', () => ({+ createClient: async () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'tok' } } }) },+ from: () => ({ update: () => ({ eq: update }) }),+ }),+}));+vi.mock('@/lib/subscription-guard', () => ({ assertWritable: async () => {} }));+vi.mock('@/config/api', () => ({ API_BASE_URL: 'https://api.example' }));++const { disconnectIntegration, getMerchantCenterOffered, setBrandGscProperty } =+ await import('./integrations');++const fetchMock = vi.fn();+beforeEach(() => {+ fetchMock.mockReset();+ update.mockReset().mockResolvedValue({ error: null });+ vi.stubGlobal('fetch', fetchMock);+});++const answer = (status: number, body: unknown) =>+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));+const timedOut = () =>+ fetchMock.mockRejectedValue(new DOMException('The operation timed out.', 'TimeoutError'));++describe('integrations actions', () => {+ it('offers Merchant Center only when the config says so, within a time limit', async () => {+ answer(200, { googleMerchantCenter: true });+ expect(await getMerchantCenterOffered()).toBe(true);+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.example/api/integrations/config');+ expect(init.signal).toBeInstanceOf(AbortSignal);+ // An older API without the config, and one that hangs, offer nothing.+ answer(404, { error: 'Not found' });+ expect(await getMerchantCenterOffered()).toBe(false);+ timedOut();+ expect(await getMerchantCenterOffered()).toBe(false);+ });++ it('disconnects within a time limit', async () => {+ answer(200, { success: true });+ await disconnectIntegration('google-search-console');+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.example/api/integrations/google-search-console');+ expect(init.method).toBe('DELETE');+ expect(init.signal).toBeInstanceOf(AbortSignal);+ });++ it("starts a mapped brand's first sync within a time limit, and keeps the pick when it can't", async () => {+ timedOut();+ await expect(setBrandGscProperty('b1', 'https://acme.com/')).resolves.toBeUndefined();+ expect(update).toHaveBeenCalledWith('id', 'b1');+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://api.example/api/integrations/google-search-console/sync');+ expect(init.signal).toBeInstanceOf(AbortSignal);+ });+});diff --git a/web/src/lib/actions/integrations.ts b/web/src/lib/actions/integrations.tsindex c17cd352f..2094ca2fa 100644--- a/web/src/lib/actions/integrations.ts+++ b/web/src/lib/actions/integrations.ts@@ -12,11 +12,15 @@ export type IntegrationProvider =export type IntegrationStatus = 'not_configured' | 'not_connected' | 'connected';-export interface IntegrationStatusResult {- configured: boolean;- status: IntegrationStatus;- accountId?: string;-}+/**+ * How long a call to the API waits. A provider's status, live connect and+ * property lists are read from the browser instead (lib/integrations-client.ts):+ * Next runs server actions one at a time, so they held each other up.+ */+const CONFIG_TIMEOUT_MS = 10_000;+const DISCONNECT_TIMEOUT_MS = 20_000;+/** The API answers a sync at once and runs it in the background. */+const SYNC_START_TIMEOUT_MS = 5_000;async function authHeaders(): Promise<Record<string, string>> {const supabase = await createClient();@@ -40,6 +44,7 @@ export async function getMerchantCenterOffered(): Promise<boolean> {const res = await fetch(`${API_BASE_URL}/api/integrations/config`, {headers: await authHeaders(),cache: 'no-store',+ signal: AbortSignal.timeout(CONFIG_TIMEOUT_MS),});if (!res.ok) return false;const config = (await res.json()) as { googleMerchantCenter?: boolean };@@ -49,22 +54,10 @@ export async function getMerchantCenterOffered(): Promise<boolean> {}}-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 IntegrationStatusResult;-}-/*** Everything the suggestion-sources panel needs, in two round trips (#659).*- * Deliberately does NOT call `getIntegrationStatus`. That resolves the live+ * Deliberately does NOT read the provider's status. That resolves the live* state against Composio and re-syncs our row, which costs ~450ms per* provider — measured — and made the panel appear well after the suggestions* it sits above. This reads the row Composio's own status check maintains,@@ -132,6 +125,7 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Suggesfetch(`${API_BASE_URL}/api/integrations/config`, {headers: await authHeaders(),cache: 'no-store',+ signal: AbortSignal.timeout(CONFIG_TIMEOUT_MS),}).then((r) => (r.ok ? (r.json() as Promise<ConfigBody>) : ({} as ConfigBody))).catch(() => ({}) as ConfigBody),@@ -168,24 +162,11 @@ export async function getSuggestionSourceStates(brandId: string): Promise<Sugges};}-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 }),- });- 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 disconnectIntegration(provider: IntegrationProvider): Promise<void> {const res = await fetch(`${API_BASE_URL}/api/integrations/${provider}`, {method: 'DELETE',headers: await authHeaders(),+ signal: AbortSignal.timeout(DISCONNECT_TIMEOUT_MS),});const body = await res.json().catch(() => ({}));if (!res.ok) throw new Error(body.error || `Server error: ${res.status}`);@@ -205,6 +186,7 @@ async function startBrandSync(provider: IntegrationProvider, brandId: string): Pmethod: 'POST',headers: await authHeaders(),body: JSON.stringify({ brandId }),+ signal: AbortSignal.timeout(SYNC_START_TIMEOUT_MS),});} catch {// The nightly sync picks the brand up.@@ -216,16 +198,6 @@ export interface GscProperty {permissionLevel: string | null;}-export async function getGscProperties(): Promise<GscProperty[]> {- const res = await fetch(`${API_BASE_URL}/api/integrations/google-search-console/properties`, {- 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.properties ?? []) as GscProperty[];-}-export interface GscBrandMapping {brandId: string;brandName: string;@@ -272,16 +244,6 @@ export interface GaProperty {siteUrls: string[];}-export async function getGaProperties(): Promise<GaProperty[]> {- const res = await fetch(`${API_BASE_URL}/api/integrations/google-analytics/properties`, {- 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.properties ?? []) as GaProperty[];-}-export interface GaBrandMapping {brandId: string;brandName: string;diff --git a/web/src/lib/catalog-client.ts b/web/src/lib/catalog-client.tsindex a06c44da8..1a7af39d0 100644--- a/web/src/lib/catalog-client.ts+++ b/web/src/lib/catalog-client.ts@@ -1,6 +1,7 @@import { BROWSER_API_BASE_URL } from '@/config/api';import { apiFailure } from '@/lib/api-failure';import { createClient } from '@/lib/supabase/client';+import { INTEGRATION_READ_TIMEOUT_MS } from '@/lib/integrations-client';import {CATALOG_UPLOAD_MAX_BYTES,type CatalogCounts,@@ -238,6 +239,7 @@ export async function listStoreConnectors(): Promise<{if (!session) return null;const res = await fetch(`${BROWSER_API_BASE_URL}/api/catalog/connectors`, {headers: { Authorization: `Bearer ${session.access_token}` },+ signal: AbortSignal.timeout(INTEGRATION_READ_TIMEOUT_MS),});if (!res.ok) return null;const body = (await res.json()) as {@@ -405,7 +407,7 @@ async function categoryCall<T>(export function listCategoryPages(brandId: string) {return categoryCall<CategoryPage[]>(`/categories?${new URLSearchParams({ brandId })}`,- {},+ { signal: AbortSignal.timeout(INTEGRATION_READ_TIMEOUT_MS) },(body) => (body.categories as CategoryPage[] | undefined) ?? [],[],);diff --git a/web/src/lib/framer-client.ts b/web/src/lib/framer-client.tsindex 15569437d..f19923d8b 100644--- a/web/src/lib/framer-client.ts+++ b/web/src/lib/framer-client.ts@@ -1,6 +1,7 @@import { BROWSER_API_BASE_URL } from '@/config/api';import { apiFailure } from '@/lib/api-failure';import { createClient } from '@/lib/supabase/client';+import { INTEGRATION_READ_TIMEOUT_MS } from '@/lib/integrations-client';/*** A brand's Framer connection for Send to CMS (#1331, phase 2; 00295), from@@ -145,7 +146,9 @@ async function call<T>(/** The brand's connection, and whether this server can keep a Framer key. */export function readFramer(brandId: string) {- return call<{ configured: boolean; connection: FramerConnection | null }>(brandId, '');+ return call<{ configured: boolean; connection: FramerConnection | null }>(brandId, '', {+ signal: AbortSignal.timeout(INTEGRATION_READ_TIMEOUT_MS),+ });}/**diff --git a/web/src/lib/integrations-client.test.ts b/web/src/lib/integrations-client.test.tsnew file mode 100644index 000000000..edaf89a98--- /dev/null+++ b/web/src/lib/integrations-client.test.ts@@ -0,0 +1,153 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * Settings › Integrations' Google reads and Connect, from the browser through+ * the API's proxy: never a server action, which Next would run one at a time,+ * and each call giving up after its timeout.+ */++vi.mock('@/lib/supabase/client', () => ({+ createClient: () => ({+ auth: { getSession: async () => ({ data: { session: { access_token: 'tok' } } }) },+ }),+}));++const {+ readGscProperties,+ readIntegrationStatus,+ readIntegrationsConfig,+ startIntegrationConnect,+ withReadTimeout,+} = await import('./integrations-client');++const fetchMock = vi.fn();+beforeEach(() => {+ fetchMock.mockReset();+ vi.stubGlobal('fetch', fetchMock);+ vi.spyOn(console, 'error').mockImplementation(() => {});+});+afterEach(() => {+ vi.useRealTimers();+});++const answer = (status: number, body: unknown) =>+ fetchMock.mockResolvedValue(new Response(JSON.stringify(body), { status }));+const BASE = '/api/aeo/api/integrations';+const timedOut = () =>+ fetchMock.mockRejectedValue(new DOMException('The operation timed out.', 'TimeoutError'));++describe('integrations-client', () => {+ it("reads a provider's status with the session, and gives up after a timeout", async () => {+ answer(200, { configured: true, status: 'connected', accountId: 'ca_1' });+ expect(await readIntegrationStatus('google-analytics')).toEqual({+ ok: true,+ value: 'connected',+ });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(`${BASE}/google-analytics/status`);+ expect(init.headers).toEqual({ Authorization: 'Bearer tok' });+ expect(init.signal).toBeInstanceOf(AbortSignal);+ });++ it('says a read that took too long timed out, and one the API refused failed', async () => {+ timedOut();+ expect(await readIntegrationStatus('google-search-console')).toEqual({+ ok: false,+ reason: 'timeout',+ });+ // The proxy's 502 while the API is down, and a network error.+ answer(502, { error: 'API server is unreachable' });+ expect(await readIntegrationStatus('google-search-console')).toEqual({+ ok: false,+ reason: 'failed',+ error: 'API server is unreachable',+ });+ fetchMock.mockRejectedValue(new TypeError('Failed to fetch'));+ expect(await readIntegrationStatus('google-search-console')).toEqual({+ ok: false,+ reason: 'failed',+ });+ // An answer without a status it knows isn't one.+ answer(200, { status: 'weird' });+ expect((await readIntegrationStatus('google-search-console')).ok).toBe(false);+ });++ it("reads the server's config, and offers nothing when an older API has none", async () => {+ const config = {+ googleSearchConsole: true,+ googleAnalytics: true,+ googleMerchantCenter: false,+ dataForSeo: false,+ };+ answer(200, config);+ expect(await readIntegrationsConfig()).toEqual(config);+ expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}/config`);+ answer(404, { error: 'Not found' });+ expect(await readIntegrationsConfig()).toBeNull();+ timedOut();+ expect(await readIntegrationsConfig()).toBeNull();+ });++ it('starts a connection with the callback, and says why one could not start', async () => {+ answer(200, { redirectUrl: 'https://oauth.example/start' });+ expect(+ await startIntegrationConnect('google-search-console', 'https://app.example/back'),+ ).toEqual({ ok: true, value: 'https://oauth.example/start' });+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe(`${BASE}/google-search-console/connect`);+ expect(init.method).toBe('POST');+ expect(JSON.parse(init.body)).toEqual({ callbackUrl: 'https://app.example/back' });+ expect(init.headers).toEqual({+ 'Content-Type': 'application/json',+ Authorization: 'Bearer tok',+ });++ answer(403, { error: 'Only admins and managers can connect integrations.' });+ expect((await startIntegrationConnect('google-search-console', 'https://a.b/')).ok).toBe(false);+ expect(await startIntegrationConnect('google-search-console', 'https://a.b/')).toMatchObject({+ reason: 'forbidden',+ });+ answer(402, { error: 'Subscription inactive', code: 'subscription_inactive' });+ expect(await startIntegrationConnect('google-search-console', 'https://a.b/')).toMatchObject({+ reason: 'subscription',+ });+ answer(500, { error: 'Composio is down' });+ expect(await startIntegrationConnect('google-search-console', 'https://a.b/')).toEqual({+ ok: false,+ reason: 'failed',+ error: 'Composio is down',+ });+ // An answer without an address to open can't start one.+ answer(200, {});+ expect(await startIntegrationConnect('google-search-console', 'https://a.b/')).toMatchObject({+ reason: 'failed',+ });+ timedOut();+ expect(await startIntegrationConnect('google-search-console', 'https://a.b/')).toEqual({+ ok: false,+ reason: 'timeout',+ });+ });++ it("reads the connected account's properties", async () => {+ answer(200, { properties: [{ siteUrl: 'https://acme.com/', permissionLevel: 'siteOwner' }] });+ expect(await readGscProperties()).toEqual({+ ok: true,+ value: [{ siteUrl: 'https://acme.com/', permissionLevel: 'siteOwner' }],+ });+ expect(fetchMock.mock.calls[0][0]).toBe(`${BASE}/google-search-console/properties`);+ });++ it("stops waiting for a server action after the timeout, and passes on one that's in time", async () => {+ vi.useFakeTimers();+ const late = withReadTimeout(new Promise(() => {}), 1000);+ const settled = late.catch((err: Error) => err);+ await vi.advanceTimersByTimeAsync(1000);+ expect(await settled).toMatchObject({ name: 'TimeoutError' });++ await expect(withReadTimeout(Promise.resolve('sources'), 1000)).resolves.toBe('sources');+ await expect(withReadTimeout(Promise.reject(new Error('denied')), 1000)).rejects.toThrow(+ 'denied',+ );+ });+});diff --git a/web/src/lib/integrations-client.ts b/web/src/lib/integrations-client.tsnew file mode 100644index 000000000..fe590cca3--- /dev/null+++ b/web/src/lib/integrations-client.ts@@ -0,0 +1,166 @@+import { BROWSER_API_BASE_URL } from '@/config/api';+import { isSubscriptionInactive } from '@/lib/api-failure';+import { createClient } from '@/lib/supabase/client';+import type {+ GaProperty,+ GscProperty,+ IntegrationProvider,+ IntegrationStatus,+} from '@/lib/actions/integrations';++/**+ * Settings › Integrations' Google reads and Connect, from the browser through+ * the API's same-origin proxy: never through a server action, which Next runs+ * one at a time. Each card's status is a Composio round trip, so a slow one+ * left the cards after it on their skeletons, and Connect, queued behind them+ * all, seemed to do nothing. Each call here runs on its own and gives up+ * after its timeout, so a card says it couldn't be read rather than wait.+ */++/** A read that hangs gives up after this: a status is one Composio round trip (~450 ms). */+export const INTEGRATION_READ_TIMEOUT_MS = 10_000;+/** Connect (the sign-in address Composio makes) and the properties Google lists wait longer. */+const GOOGLE_CALL_TIMEOUT_MS = 20_000;++/**+ * Why a call came back without its answer: it took too long, the person's+ * role can't do it, the workspace is read-only (the upgrade dialog, not a+ * message), or anything else, with the API's own words when it gave them.+ */+export type IntegrationFailure = 'timeout' | 'forbidden' | 'subscription' | 'failed';+export type IntegrationResult<T> =+ | { ok: true; value: T }+ | { ok: false; reason: IntegrationFailure; error?: string };++/** Which integrations this server has credentials for: env only, no Composio round trip. */+export interface IntegrationsConfig {+ googleSearchConsole: boolean;+ googleAnalytics: boolean;+ googleMerchantCenter: boolean;+ dataForSeo: boolean;+}++/** A call given up on after its timeout: AbortSignal.timeout's TimeoutError, or withReadTimeout's. */+export function isTimeout(err: unknown): boolean {+ return (+ typeof err === 'object' && err !== null && (err as { name?: unknown }).name === 'TimeoutError'+ );+}++async function call<T>(+ path: string,+ init: RequestInit,+ timeoutMs: number,+ read: (body: Record<string, unknown>) => T | undefined,+): Promise<IntegrationResult<T>> {+ try {+ const {+ data: { session },+ } = await createClient().auth.getSession();+ if (!session) return { ok: false, reason: 'failed' };+ const res = await fetch(`${BROWSER_API_BASE_URL}/api/integrations${path}`, {+ ...init,+ headers: {+ ...(init.body ? { 'Content-Type': 'application/json' } : {}),+ Authorization: `Bearer ${session.access_token}`,+ },+ cache: 'no-store',+ signal: AbortSignal.timeout(timeoutMs),+ });+ const body = (await res.json().catch(() => ({}))) as Record<string, unknown>;+ const value = res.ok ? read(body) : undefined;+ if (value !== undefined) return { ok: true, value };+ if (isSubscriptionInactive(body)) return { ok: false, reason: 'subscription' };+ if (res.status === 403) return { ok: false, reason: 'forbidden' };+ console.error(`Integration call ${path} failed:`, res.status, body.error);+ return {+ ok: false,+ reason: 'failed',+ ...(typeof body.error === 'string' ? { error: body.error } : {}),+ };+ } catch (err) {+ if (isTimeout(err)) return { ok: false, reason: 'timeout' };+ console.error(`Integration call ${path} failed:`, err);+ return { ok: false, reason: 'failed' };+ }+}++/**+ * The server's integrations config, or null when it can't be read: an API+ * older than the web (404), or one that is down. Null offers nothing.+ */+export async function readIntegrationsConfig(): Promise<IntegrationsConfig | null> {+ const result = await call(+ '/config',+ {},+ INTEGRATION_READ_TIMEOUT_MS,+ (body) => body as unknown as IntegrationsConfig,+ );+ return result.ok ? result.value : null;+}++const STATUSES: readonly IntegrationStatus[] = ['not_configured', 'not_connected', 'connected'];++/** A provider's live status, which the API checks with Composio. */+export function readIntegrationStatus(+ provider: IntegrationProvider,+): Promise<IntegrationResult<IntegrationStatus>> {+ return call(`/${provider}/status`, {}, INTEGRATION_READ_TIMEOUT_MS, (body) =>+ STATUSES.find((s) => s === body.status),+ );+}++/** Starts the provider's OAuth: the address to open, where the person signs in with Google. */+export function startIntegrationConnect(+ provider: IntegrationProvider,+ callbackUrl: string,+): Promise<IntegrationResult<string>> {+ return call(+ `/${provider}/connect`,+ { method: 'POST', body: JSON.stringify({ callbackUrl }) },+ GOOGLE_CALL_TIMEOUT_MS,+ (body) => (typeof body.redirectUrl === 'string' ? body.redirectUrl : undefined),+ );+}++/** The Search Console properties the connected Google account opens. */+export function readGscProperties(): Promise<IntegrationResult<GscProperty[]>> {+ return call('/google-search-console/properties', {}, GOOGLE_CALL_TIMEOUT_MS, (body) =>+ Array.isArray(body.properties) ? (body.properties as GscProperty[]) : [],+ );+}++/** The GA4 properties the connected Google account opens. */+export function readGaProperties(): Promise<IntegrationResult<GaProperty[]>> {+ return call('/google-analytics/properties', {}, GOOGLE_CALL_TIMEOUT_MS, (body) =>+ Array.isArray(body.properties) ? (body.properties as GaProperty[]) : [],+ );+}++/**+ * A server action's answer, or a TimeoutError once it's taken longer than a+ * read should. A server action can't be called off: this only stops waiting+ * for it, so a card can say it couldn't be read instead of a lasting skeleton.+ */+export function withReadTimeout<T>(+ promise: Promise<T>,+ ms: number = INTEGRATION_READ_TIMEOUT_MS,+): Promise<T> {+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ const err = new Error('The read took too long.');+ err.name = 'TimeoutError';+ reject(err);+ }, ms);+ promise.then(+ (value) => {+ clearTimeout(timer);+ resolve(value);+ },+ (err: unknown) => {+ clearTimeout(timer);+ reject(err);+ },+ );+ });+}diff --git a/web/src/lib/webflow-client.ts b/web/src/lib/webflow-client.tsindex 84f309646..d79c6b0a9 100644--- a/web/src/lib/webflow-client.ts+++ b/web/src/lib/webflow-client.ts@@ -1,6 +1,7 @@import { BROWSER_API_BASE_URL } from '@/config/api';import { apiFailure } from '@/lib/api-failure';import { createClient } from '@/lib/supabase/client';+import { INTEGRATION_READ_TIMEOUT_MS } from '@/lib/integrations-client';/*** A brand's Webflow connection for Send to CMS (#1331, phase 2), from the@@ -134,7 +135,9 @@ async function call<T>(/** The brand's connection, and whether this server has Webflow set up. */export function readWebflow(brandId: string) {- return call<{ configured: boolean; connection: WebflowConnection | null }>(brandId, '');+ return call<{ configured: boolean; connection: WebflowConnection | null }>(brandId, '', {+ signal: AbortSignal.timeout(INTEGRATION_READ_TIMEOUT_MS),+ });}/** Connects the brand's site with its token, or replaces the token. */diff --git a/web/src/lib/wordpress-client.ts b/web/src/lib/wordpress-client.tsindex 09a3d8ff5..9adacafb2 100644--- a/web/src/lib/wordpress-client.ts+++ b/web/src/lib/wordpress-client.ts@@ -1,6 +1,7 @@import { BROWSER_API_BASE_URL } from '@/config/api';import { apiFailure } from '@/lib/api-failure';import { createClient } from '@/lib/supabase/client';+import { INTEGRATION_READ_TIMEOUT_MS } from '@/lib/integrations-client';/*** A brand's WordPress connection for Send to CMS (#1331, phase 2; 00294),@@ -99,7 +100,9 @@ async function call<T>(brandId: string, init: RequestInit = {}): Promise<WordPre/** The brand's connection, and whether this server can keep a WordPress sign-in. */export function readWordPress(brandId: string) {- return call<{ configured: boolean; connection: WordPressConnection | null }>(brandId);+ return call<{ configured: boolean; connection: WordPressConnection | null }>(brandId, {+ signal: AbortSignal.timeout(INTEGRATION_READ_TIMEOUT_MS),+ });}/** Connects the brand's site, or replaces its sign-in: the API checks it with the site first. */