@fayz-ai/admin 0.67.0 → 0.67.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{ConnectedUserProfile-2PP755RY.js → ConnectedUserProfile-HL6Q6ECE.js} +3 -3
- package/dist/{ConnectedUserProfile-2PP755RY.js.map → ConnectedUserProfile-HL6Q6ECE.js.map} +1 -1
- package/dist/{TeamTab-M5SAKV6M.js → TeamTab-EIP4QLIV.js} +4 -4
- package/dist/{TeamTab-M5SAKV6M.js.map → TeamTab-EIP4QLIV.js.map} +1 -1
- package/dist/{chunk-RLZCH4NU.js → chunk-F54JFP54.js} +56 -19
- package/dist/chunk-F54JFP54.js.map +1 -0
- package/dist/{chunk-AIDRTAXD.js → chunk-LO26TZS3.js} +3 -3
- package/dist/{chunk-AIDRTAXD.js.map → chunk-LO26TZS3.js.map} +1 -1
- package/dist/{chunk-PYTAPPG2.js → chunk-MHWWD5MF.js} +3 -2
- package/dist/chunk-MHWWD5MF.js.map +1 -0
- package/dist/{connect-5ZSLYJAS.js → connect-JBAPWQVP.js} +3 -3
- package/dist/{connect-5ZSLYJAS.js.map → connect-JBAPWQVP.js.map} +1 -1
- package/dist/crud/RelatedSection.d.ts.map +1 -1
- package/dist/crud/price-table-lookup.d.ts +50 -0
- package/dist/crud/price-table-lookup.d.ts.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +104 -11
- package/dist/index.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-PYTAPPG2.js.map +0 -1
- package/dist/chunk-RLZCH4NU.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/lib/fayz-agent.ts","../src/components/connect/ConnectConsentPage.tsx","../src/components/connect/model.ts","../src/components/connect/ConnectorRow.tsx","../src/components/connect/credentials.ts","../src/components/connect/ConnectorDisclosure.tsx","../src/components/connect/ConnectorPermissions.tsx","../src/components/connect/ConnectorSyncActions.tsx","../src/components/connect/when.ts","../src/components/connect/ConnectorRuns.tsx","../src/components/connect/ConnectorSettings.tsx","../src/components/connect/ConnectorDetail.tsx","../src/components/connect/connector-status.ts","../src/components/connect/useConnectors.ts","../src/components/connect/ConnectorsPanel.tsx","../src/components/connect/AddConnectorPanel.tsx","../src/components/connect/ConnectorsTab.tsx","../src/components/connect/oauth-return.ts","../src/components/connect/ConnectorDeliveries.tsx","../src/components/connect/connector-sources.ts","../src/components/connect/connector-search.ts"],"names":["React","jsxs","jsx","Button","Fragment","ChevronRight","toast","CheckCircle2","Loader2","ArrowDownToLine","ArrowUpFromLine","Sparkles","RefreshCw","connectorSettings","AlertTriangle","Info","getConnectorCredentialSink","ConfirmDialog","Skeleton","Input","Section","Search","Plus","usePluginRuntimeOptional","XCircle","STATE_RANK"],"mappings":";;;;;;;;;;;;;;;;;;AAwBA,SAAS,IAAI,GAAA,EAAiC;AAC5C,EAAA,MAAM,KAAA,GAAS,MAAA,CAAA,IAAA,CAAY,GAAA,CAA2C,GAAG,CAAA;AACzE,EAAA,OAAO,OAAO,UAAU,QAAA,IAAY,KAAA,CAAM,MAAK,GAAI,KAAA,CAAM,MAAK,GAAI,MAAA;AACpE;AAUO,SAAS,sBAAsB,QAAA,EAAuC;AAC3E,EAAA,OAAO,QAAA,IAAY,IAAI,wBAAwB,CAAA;AACjD;AAOO,SAAS,2BACd,QAAA,EACoC;AACpC,EAAA,IAAI,QAAA,KAAa,OAAO,OAAO,IAAA;AAE/B,EAAA,MAAM,SAAA,GAAY,QAAA,EAAU,SAAA,IAAa,GAAA,CAAI,sBAAsB,CAAA;AACnE,EAAA,MAAM,UAAA,GAAa,QAAA,EAAU,UAAA,IAAc,GAAA,CAAI,wBAAwB,CAAA;AACvE,EAAA,MAAM,cAAA,GAAiB,QAAA,EAAU,cAAA,IAAkB,GAAA,CAAI,qBAAqB,CAAA;AAE5E,EAAA,IAAI,CAAC,SAAA,IAAa,CAAC,UAAA,IAAc,CAAC,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AAA,GAAQ,mBAAA,CAAoB,KAAA,CAAM,KAAK,CAAA;AAC7C,EAAA,IAAI,CAAC,KAAA,CAAM,GAAA,EAAK,OAAO,EAAC;AAExB,EAAA,MAAM,IAAA,GAAO;AAAA,IACX,GAAG,KAAA,CAAM,UAAA,CAAW,GAAA,CAAI,aAAa,CAAA;AAAA,IACrC,GAAG,KAAA,CAAM,KAAA,CAAM,GAAA,CAAI,SAAS;AAAA,GAC9B;AAEA,EAAA,OAAO,IAAA,CACJ,IAAI,CAAC,GAAA,MAAS,EAAE,GAAG,GAAA,EAAK,OAAO,KAAA,CAAM,GAAA,EAAK,KAAK,CAAA,EAAE,CAAE,EACnD,MAAA,CAAO,CAAC,QAAQ,GAAA,CAAI,KAAA,GAAQ,CAAC,CAAA,CAC7B,IAAA;AAAA,IACC,CAAC,CAAA,EAAG,CAAA,KACF,EAAE,KAAA,GAAQ,CAAA,CAAE,SACZA,WAAAA,CAAW,CAAA,CAAE,KAAK,CAAA,GAAIA,WAAAA,CAAW,EAAE,KAAK,CAAA,IACxC,EAAE,IAAA,CAAK,aAAA,CAAc,EAAE,IAAI;AAAA,GAC/B,CACC,KAAA,CAAM,CAAA,EAAG,KAAA,CAAM,SAAS,CAAC,CAAA;AAC9B;AAgBO,SAAS,iBAAiB,KAAA,EAA0D;AACzF,EAAA,QAAQ,KAAA;AAAO,IACb,KAAK,WAAA;AAAA,IACL,KAAK,aAAA;AAAA,IACL,KAAK,OAAA;AACH,MAAA,OAAO,IAAA;AAAA,IACT,KAAK,MAAA;AAAA,IACL,KAAK,cAAA;AACH,MAAA,OAAO,KAAA;AAAA;AAEb;AAWO,SAAS,eAAe,UAAA,EAAyD;AACtF,EAAA,OAAO,gBAAA,CAAiB,WAAW,KAAK,CAAA;AAC1C","file":"chunk-MHWWD5MF.js","sourcesContent":["import { createFayzAgentClient, type FayzAgentClient } from '@fayz-ai/sdk/agent'\n\n/**\n * Resolves the connection to the project's Fayz agent.\n *\n * The container writes `VITE_FAYZ_PROJECT_ID`, `VITE_FAYZ_API_BASE_URL` and\n * `VITE_FAYZ_AGENT_KEY` into every preview's `.env`, so enabling an agent in\n * Fayz is enough to light up the app's assistant — no app-side config edit and\n * no key to copy. `chat.agent` overrides are for self-hosted deployments where\n * the app is built outside a Fayz container.\n */\n\nexport interface FayzAgentConnectionConfig {\n projectId?: string\n apiBaseUrl?: string\n publishableKey?: string\n}\n\nexport interface ResolvedFayzAgentConnection {\n projectId: string\n apiBaseUrl: string\n publishableKey: string\n}\n\nfunction env(key: string): string | undefined {\n const value = (import.meta.env as Record<string, string | undefined>)[key]\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\n/**\n * Just the platform address, for the endpoints that need no credential.\n *\n * Separate from `resolveFayzAgentConnection` because that one requires all three\n * variables: an app without an agent key still has a platform to talk to, and\n * gating the anonymous endpoints on the agent key would silently switch them off\n * for most of the fleet.\n */\nexport function resolveFayzApiBaseUrl(override?: string): string | undefined {\n return override ?? env('VITE_FAYZ_API_BASE_URL')\n}\n\n/** The other half of the address: which project on that platform this app is. */\nexport function resolveFayzProjectId(override?: string): string | undefined {\n return override ?? env('VITE_FAYZ_PROJECT_ID')\n}\n\nexport function resolveFayzAgentConnection(\n override?: FayzAgentConnectionConfig | false,\n): ResolvedFayzAgentConnection | null {\n if (override === false) return null\n\n const projectId = override?.projectId ?? env('VITE_FAYZ_PROJECT_ID')\n const apiBaseUrl = override?.apiBaseUrl ?? env('VITE_FAYZ_API_BASE_URL')\n const publishableKey = override?.publishableKey ?? env('VITE_FAYZ_AGENT_KEY')\n\n if (!projectId || !apiBaseUrl || !publishableKey) return null\n return { projectId, apiBaseUrl, publishableKey }\n}\n\n/**\n * WHY the assistant is dark, in the words of whoever can fix it.\n *\n * `resolveFayzAgentConnection` answering `null` is one bit, and the panel used\n * to translate that bit into \"defina chat.apiEndpoint\" — advice that is wrong\n * for every app in the fleet, because none of them set `apiEndpoint`: they are\n * wired by env. Three apps (control, full-control, ticket-control) shipped for\n * weeks with a dead FAB and nobody could read why from the screen.\n *\n * So the gap names the MISSING VARIABLES. Never the values — a publishable key\n * is public by design, but a diagnostic that prints credentials becomes a\n * screenshot in a support thread.\n */\nexport function describeFayzAgentGap(\n override?: FayzAgentConnectionConfig | false,\n): { missing: string[] } | null {\n if (override === false) return null\n const missing: string[] = []\n if (!(override?.projectId ?? env('VITE_FAYZ_PROJECT_ID'))) missing.push('VITE_FAYZ_PROJECT_ID')\n if (!(override?.apiBaseUrl ?? env('VITE_FAYZ_API_BASE_URL'))) missing.push('VITE_FAYZ_API_BASE_URL')\n if (!(override?.publishableKey ?? env('VITE_FAYZ_AGENT_KEY'))) missing.push('VITE_FAYZ_AGENT_KEY')\n return missing.length ? { missing } : null\n}\n\nlet cached: { key: string; client: FayzAgentClient } | null = null\n\nexport function getFayzAgentClient(connection: ResolvedFayzAgentConnection): FayzAgentClient {\n const key = `${connection.apiBaseUrl}|${connection.projectId}|${connection.publishableKey}`\n if (cached?.key === key) return cached.client\n\n const client = createFayzAgentClient({\n baseUrl: connection.apiBaseUrl,\n projectId: connection.projectId,\n publishableKey: connection.publishableKey,\n })\n cached = { key, client }\n return client\n}\n","import React from 'react'\nimport { getFayzSupabaseClientOptional } from '../../data/client'\nimport { resolveFayzAgentConnection } from '../../lib/fayz-agent'\nimport { Button, Skeleton, Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@fayz-ai/ui'\nimport { knownClientMark } from './client-marks'\n\n/**\n * The consent screen an external agent sends the user to.\n *\n * It lives in the APP, not in fayz, and that placement is the point: the person\n * approving is the salon owner, who has a session here and no fayz account at\n * all. Hosting this in the platform would bounce them to a login they cannot\n * pass.\n *\n * What it must show, and why each one:\n *\n * - **who is asking** — name, site and the exact redirect URI, fetched from\n * the client's own metadata rather than echoed from the query string, so\n * the name on screen is the identity the client actually claims.\n * - **what they get** — read-only, said plainly. The request usually asks for\n * `write` too; the server drops it, and this screen shows what was GRANTED,\n * never what was requested. A consent screen that lists a capability the\n * connection does not have is worse than no screen.\n * - **which organization** — the thing being handed over is an organization's\n * data, so the organization has to be named, and picked when the user\n * belongs to more than one. Approving without knowing whose data it is is\n * not consent.\n */\n\ninterface ConsentClient {\n name: string\n website?: string\n logoUri?: string\n redirectUri: string\n /**\n * The identity was attested — its metadata came from the origin its client_id\n * names. False means the client typed its own name when registering, and the\n * screen says so instead of dressing it up.\n */\n identityVerified?: boolean\n}\n\ninterface ConsentAccess {\n scopes: string[]\n readOnly: boolean\n summary: string\n /**\n * What is being handed over, entity by entity, when the connection is another\n * PRODUCT rather than an assistant.\n *\n * Absent for an agent connection, which reaches the whole read surface and\n * has no declared subset to enumerate. Present, it is the honest version of\n * `summary`: a sentence can say \"seus dados\" and be true of anything, and\n * once a connection can WRITE, \"true of anything\" stops being good enough.\n */\n entities?: Array<{\n label: string\n reason: string\n operations: Array<'read' | 'create' | 'update'>\n }>\n}\n\ninterface ConsentOrganization {\n tenantId: string\n name: string\n role?: string\n}\n\ninterface ConsentPayload {\n client: ConsentClient\n access: ConsentAccess\n user: { id: string; email?: string }\n organizations: ConsentOrganization[]\n}\n\nexport interface ConnectConsentPageProps {\n /** Product name shown next to the requesting client. Defaults to the document title. */\n appName?: string\n /**\n * ICON-ONLY mark. Not the wordmark: this badge is square, and a wordmark in\n * it is cropped. Absent, the app's initial is used, which is always legible.\n */\n logo?: React.ReactNode\n}\n\ntype State =\n | { status: 'loading' }\n | { status: 'error'; message: string }\n | { status: 'ready'; payload: ConsentPayload }\n | { status: 'approving' }\n\nexport function ConnectConsentPage({ appName, logo }: ConnectConsentPageProps) {\n const [state, setState] = React.useState<State>({ status: 'loading' })\n const [tenantId, setTenantId] = React.useState<string>('')\n const request = React.useMemo(\n () => new URLSearchParams(window.location.search).get('request') ?? '',\n [],\n )\n\n const connection = React.useMemo(() => resolveFayzAgentConnection(), [])\n const product = appName ?? document.title ?? 'este app'\n\n const authorizedFetch = React.useCallback(\n async (path: string, init?: RequestInit): Promise<Response> => {\n if (!connection) throw new Error('Este app não está ligado a um projeto Fayz.')\n const supabase = getFayzSupabaseClientOptional()\n const session = (await supabase?.auth.getSession())?.data.session\n if (!session?.access_token) {\n // Not an error state — the user simply needs to sign in first, and must\n // come back to the SAME authorization request afterwards.\n const back = encodeURIComponent(window.location.pathname + window.location.search)\n window.location.href = `/login?redirect=${back}`\n throw new Error('redirecting')\n }\n return fetch(\n `${connection.apiBaseUrl}/public/projects/${connection.projectId}/agents/oauth${path}`,\n {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${session.access_token}`,\n 'Content-Type': 'application/json',\n },\n },\n )\n },\n [connection],\n )\n\n React.useEffect(() => {\n let cancelled = false\n ;(async () => {\n if (!request) {\n setState({ status: 'error', message: 'Link de autorização inválido ou incompleto.' })\n return\n }\n try {\n const response = await authorizedFetch(`/consent/request?request=${encodeURIComponent(request)}`)\n const body = (await response.json()) as ConsentPayload & { message?: string }\n if (cancelled) return\n if (!response.ok) {\n setState({ status: 'error', message: body.message ?? 'Não foi possível ler o pedido.' })\n return\n }\n setState({ status: 'ready', payload: body })\n // Pre-select when there is nothing to choose.\n if (body.organizations.length === 1) setTenantId(body.organizations[0].tenantId)\n } catch (error) {\n if (cancelled || (error as Error).message === 'redirecting') return\n setState({ status: 'error', message: (error as Error).message })\n }\n })()\n return () => {\n cancelled = true\n }\n }, [request, authorizedFetch])\n\n async function approve() {\n if (!tenantId) return\n const previous = state\n setState({ status: 'approving' })\n try {\n const response = await authorizedFetch('/consent', {\n method: 'POST',\n body: JSON.stringify({ request, tenantId }),\n })\n const body = (await response.json()) as { redirectTo?: string; message?: string }\n if (!response.ok || !body.redirectTo) {\n setState({ status: 'error', message: body.message ?? 'Não foi possível autorizar.' })\n return\n }\n // Hand the browser back to the client that started this.\n window.location.href = body.redirectTo\n } catch (error) {\n if ((error as Error).message === 'redirecting') return\n setState(previous)\n }\n }\n\n function cancel() {\n window.history.length > 1 ? window.history.back() : (window.location.href = '/')\n }\n\n return (\n <div className=\"flex min-h-screen items-center justify-center bg-sidebar p-4\">\n <div className=\"relative w-full max-w-md rounded-2xl border border-border/50 bg-card p-8 shadow-2xl\">\n {/* The card's shape is known before the request resolves, so it is\n drawn first. A dialog that asks for a decision should not appear to\n change size while the user is reading it. */}\n {state.status === 'loading' && <ConsentSkeleton />}\n\n {state.status === 'error' && (\n <div className=\"py-6 text-center\">\n <h1 className=\"text-lg font-semibold text-foreground\">Não deu para autorizar</h1>\n <p className=\"mt-2 text-sm text-muted-foreground\">{state.message}</p>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={cancel}\n className=\"mt-6 rounded-button border border-border px-4 py-2 text-sm font-medium hover:bg-muted\"\n >\n Voltar\n </Button>\n </div>\n )}\n\n {(state.status === 'ready' || state.status === 'approving') && (\n <ConsentBody\n payload={state.status === 'ready' ? state.payload : undefined}\n product={product}\n logo={logo}\n tenantId={tenantId}\n onTenantChange={setTenantId}\n onApprove={approve}\n onCancel={cancel}\n busy={state.status === 'approving'}\n />\n )}\n </div>\n </div>\n )\n}\n\nfunction ConsentBody({\n payload,\n product,\n logo,\n tenantId,\n onTenantChange,\n onApprove,\n onCancel,\n busy,\n}: {\n payload?: ConsentPayload\n product: string\n logo?: React.ReactNode\n tenantId: string\n onTenantChange: (id: string) => void\n onApprove: () => void\n onCancel: () => void\n busy: boolean\n}) {\n if (!payload) return <ConsentSkeleton />\n\n const { client, access, organizations } = payload\n const org = organizations.find((o) => o.tenantId === tenantId)\n const mark =\n client.logoUri ?? knownClientMark(client.website, client.identityVerified === true, client.name)\n\n return (\n <>\n <div className=\"mb-6 flex items-center justify-center gap-3\">\n <MarkBadge fallback={client.name}>\n {mark ? <img src={mark} alt=\"\" className=\"h-full w-full object-cover\" /> : null}\n </MarkBadge>\n <span className=\"text-muted-foreground\">⇄</span>\n <MarkBadge fallback={product}>{logo}</MarkBadge>\n </div>\n\n <h1 className=\"text-center text-xl font-semibold text-foreground\">\n {client.name} quer acessar seus dados\n </h1>\n\n <dl className=\"mt-6 divide-y divide-border overflow-hidden rounded-xl border border-border text-sm\">\n <Row\n label=\"Aplicativo\"\n value={\n <span>\n {client.name}\n {client.identityVerified !== true && (\n // Not an alarm — most CLI clients register themselves and are\n // perfectly legitimate. But the user is about to hand over an\n // organization's data, and \"this name is self-declared\" is a\n // fact they are entitled to before deciding.\n <span className=\"block text-xs text-muted-foreground\">\n nome informado pelo próprio aplicativo\n </span>\n )}\n </span>\n }\n />\n {client.website && (\n <Row\n label=\"Site\"\n value={\n <a href={client.website} target=\"_blank\" rel=\"noreferrer noopener\" className=\"text-primary hover:underline\">\n {client.website}\n </a>\n }\n />\n )}\n {/* Shown because it is the one field that decides where the access\n actually ends up — a user who recognises the name but not the\n destination has not been told enough. */}\n <Row label=\"Retorna para\" value={<span className=\"break-all font-mono text-xs\">{client.redirectUri}</span>} />\n <Row\n label=\"Acesso\"\n value={\n <span>\n {access.readOnly ? 'Somente leitura' : 'Leitura e escrita'}\n <span className=\"block text-xs text-muted-foreground\">{access.summary}</span>\n </span>\n }\n />\n </dl>\n\n {/* Named one by one, because this is where a summary stops being enough.\n A connection that only reads can be described in a sentence; one that\n writes back has to say WHAT it writes, or the person approving is\n agreeing to a category instead of to a decision. */}\n {access.entities && access.entities.length > 0 && (\n <ul className=\"mt-4 space-y-2 rounded-lg border border-border bg-muted/30 p-3\">\n {access.entities.map((entity) => {\n const writes = entity.operations.some((operation) => operation !== 'read')\n return (\n <li key={entity.label} className=\"text-sm\">\n <span className=\"font-medium text-foreground\">{entity.label}</span>\n <span className=\"ml-2 text-xs text-muted-foreground\">\n {writes ? 'ler e escrever' : 'somente ler'}\n </span>\n <span className=\"block text-xs text-muted-foreground\">{entity.reason}</span>\n </li>\n )\n })}\n </ul>\n )}\n\n <div className=\"mt-5\">\n <label className=\"mb-1.5 block text-sm font-medium text-foreground\">\n Organização que está liberando\n </label>\n {organizations.length === 0 ? (\n <p className=\"rounded-lg border border-border bg-muted/40 p-3 text-sm text-muted-foreground\">\n Sua conta não pertence a nenhuma organização neste app, então não há dados para liberar.\n </p>\n ) : organizations.length === 1 ? (\n <div className=\"rounded-lg border border-border bg-muted/40 px-3 py-2.5 text-sm\">\n {organizations[0].name}\n {organizations[0].role && (\n <span className=\"ml-2 text-xs text-muted-foreground\">({organizations[0].role})</span>\n )}\n </div>\n ) : (\n <Select value={tenantId || undefined} onValueChange={onTenantChange}>\n <SelectTrigger className=\"h-auto rounded-lg border-border py-2.5 shadow-none\">\n <SelectValue placeholder=\"Escolha uma organização…\" />\n </SelectTrigger>\n <SelectContent>\n {organizations.map((o) => (\n <SelectItem key={o.tenantId} value={o.tenantId}>\n {o.name}\n {o.role ? ` (${o.role})` : ''}\n </SelectItem>\n ))}\n </SelectContent>\n </Select>\n )}\n </div>\n\n <p className=\"mt-5 text-xs leading-relaxed text-muted-foreground\">\n Ao aprovar, {client.name} poderá ler os dados\n {org ? ` de ${org.name}` : ' da organização escolhida'} até você desconectar.\n Você pode desfazer isso a qualquer momento em <strong>Configurações → Conectores</strong>.\n </p>\n\n <div className=\"mt-6 flex justify-end gap-2\">\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={onCancel}\n disabled={busy}\n className=\"rounded-button border border-border px-4 py-2 text-sm font-medium hover:bg-muted disabled:opacity-50\"\n >\n Cancelar\n </Button>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={onApprove}\n disabled={busy || !tenantId}\n className=\"rounded-lg bg-primary px-5 py-2 text-sm font-medium text-primary-foreground hover:opacity-90 disabled:opacity-50\"\n >\n {busy ? 'Aprovando…' : 'Aprovar'}\n </Button>\n </div>\n </>\n )\n}\n\nfunction ConsentSkeleton() {\n return (\n <div aria-hidden>\n <div className=\"mb-6 flex items-center justify-center gap-3\">\n <Skeleton className=\"h-12 w-12 rounded-xl\" />\n <Skeleton className=\"h-4 w-4 rounded-full\" />\n <Skeleton className=\"h-12 w-12 rounded-xl\" />\n </div>\n <Skeleton className=\"mx-auto h-6 w-64\" />\n <div className=\"mt-6 divide-y divide-border overflow-hidden rounded-xl border border-border\">\n {[0, 1, 2, 3].map((i) => (\n <div key={i} className=\"flex gap-4 px-4 py-3\">\n <Skeleton className=\"h-4 w-24 shrink-0\" />\n <Skeleton className=\"h-4 flex-1\" />\n </div>\n ))}\n </div>\n <Skeleton className=\"mt-5 h-4 w-52\" />\n <Skeleton className=\"mt-2 h-11 w-full rounded-lg\" />\n <div className=\"mt-6 flex justify-end gap-2\">\n <Skeleton className=\"h-9 w-24 rounded-lg\" />\n <Skeleton className=\"h-9 w-24 rounded-lg\" />\n </div>\n </div>\n )\n}\n\n/**\n * A 48px square for a product mark.\n *\n * When there IS a mark, it fills the square with no frame of its own: these\n * marks already come with their own rounded background, and wrapping one in a\n * bordered, padded box draws a second frame around the first. The chrome exists\n * only for the fallback, where a bare initial floating in the layout would read\n * as a missing image rather than a deliberate placeholder.\n */\nfunction MarkBadge({\n children,\n fallback,\n}: {\n children?: React.ReactNode\n fallback: string\n}) {\n if (children) {\n return (\n // The node is the app's own, sized for wherever it normally lives (the\n // sidebar rail sizes it too, via cloneElement). It is stretched to the\n // badge here rather than by changing the component, which would follow it\n // everywhere else it is used.\n <div className=\"h-12 w-12 shrink-0 overflow-hidden rounded-xl [&>*]:h-full [&>*]:w-full [&_img]:h-full [&_img]:w-full [&_img]:rounded-xl [&_img]:object-cover [&_svg]:h-full [&_svg]:w-full\">\n {children}\n </div>\n )\n }\n return (\n <div className=\"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl border border-border bg-muted text-lg font-semibold\">\n {fallback.slice(0, 1).toUpperCase()}\n </div>\n )\n}\n\nfunction Row({ label, value }: { label: string; value: React.ReactNode }) {\n return (\n <div className=\"flex gap-4 px-4 py-3\">\n <dt className=\"w-28 shrink-0 text-muted-foreground\">{label}</dt>\n <dd className=\"min-w-0 flex-1 text-foreground\">{value}</dd>\n </div>\n )\n}\n","import type {\n ConnectorCategory,\n ConnectorDefinition,\n ConnectorPermission,\n ConnectorPlane,\n ConnectorDirection,\n ConnectorAgentTool,\n ConnectorInvocation,\n ConnectorManagedAutomation,\n} from '@fayz-ai/core'\nimport {\n connectorEntities,\n connectorPermissions,\n connectorPlanes,\n connectorSubscribesTo,\n preferredPlane,\n connectorDirection,\n eventKeyMatches,\n isConnectorCategory,\n} from '@fayz-ai/core'\nimport { SDK_INTEGRATIONS, type SdkIntegration } from './connector-map.generated'\n\n/**\n * One list, one noun.\n *\n * A \"conector\" and an \"integração\" were the same thing described from two\n * screens: the plugin's Integrações tab knew how to authorize a provider, and\n * Settings → Conectores knew what had been granted. Neither could answer the\n * question the person running the business actually asks — *o que está ligado\n * no meu negócio, e quem consegue fazer o quê?* — because each held half the\n * answer.\n *\n * So both surfaces now project onto this one view model. Four facets tell the\n * rows apart, and none of them justifies a second screen:\n *\n * - `direction` — quem alcança quem (o Claude lê minha agenda ↔ minha agenda\n * vai pro Google)\n * - `plane` — como a integração é honrada: entregue ao assistente (agêntica)\n * ou espelhada por uma esteira (sync)\n * - `hostPluginId` — qual plugin hospeda o conector (agenda, financeiro)\n * - `state` — o quanto dessa jornada já aconteceu\n */\n\nexport type { ConnectorPlane, ConnectorDirection, ConnectorAgentTool }\n\n/**\n * How far along the journey a connector is.\n *\n * Every state is about a connector THIS app backs. Rows for what the platform\n * *could* build were the defect — see {@link buildConnectorList} — and no state\n * here may bring them back.\n *\n * `needs_setup` is not a fourth kind of \"maybe connected\": the authorization\n * happened and nothing about it needs redoing. It exists because the connect\n * step stopped asking for operational configuration, so there is now a real gap\n * between \"authorized\" and \"able to work\" — and a carrier that cannot quote\n * because nobody chose an origin postcode must not read as ready. The truth\n * lives in `connections.status = 'pending'`; this is its name in the UI.\n *\n * These tokens are not only rendered — they are the assistant's vocabulary too.\n * {@link ConnectorSuggestionState} is this union plus the two shelf answers, and\n * `findConnectors` puts the same word on the wire for a model to read, which is\n * what makes \"the tool and the screen never disagree\" a fact about the types\n * rather than something to keep in sync. Hence `needs_setup` and not\n * `needs-setup`: its siblings over there are `soon` and `needs_module`.\n */\nexport type ConnectorState =\n /** Live — granted (inbound) or authorized (outbound). */\n | 'connected'\n /** Authorized, and unable to work until a required-to-operate setting is chosen. */\n | 'needs_setup'\n /** Installed in this app: a plugin here contributes it, so it can be connected now. */\n | 'ready'\n\nexport interface UnifiedConnector {\n /** Stable row key — connector id, catalog slug, or grant id. */\n id: string\n /** Catalog slug / connector id, used to match the three sources together. */\n slug: string\n name: string\n description?: string\n direction: ConnectorDirection\n /** Planes this connector can be honoured on. */\n planes: ConnectorPlane[]\n /** The plane it is running on right now (only meaningful when connected). */\n activePlane?: ConnectorPlane\n state: ConnectorState\n /** Setting keys still to be chosen, when `state` is 'needs_setup'. Keys only. */\n missingSettings?: string[]\n hostPluginId?: string\n category?: string\n /** Lucide icon name (installed connectors). */\n icon?: string\n /** Brand mark from the catalogue or the granting client. */\n logoUrl?: string\n /** Canonical entities the connector touches — derived from `permissions`. */\n entities?: string[]\n /** What the connector declared it needs access to, and why. Consent view's source. */\n permissions?: ConnectorPermission[]\n /** How many record types it reaches, when the source only counts them. */\n entityCount?: number\n /** Tools the assistant gains — declared (outbound) or granted (inbound). */\n agentTools?: ConnectorAgentTool[]\n detail?: string\n /** What is wrong with a live connection, when the connector enumerates it. */\n issues?: string[]\n docsUrl?: string\n\n // --- inbound grant extras (an external agent holding access to this org) ---\n /**\n * This row is a GRANT — somebody else holding access to this organization —\n * and not a connector this app reaches out to.\n *\n * Explicit because `direction` cannot answer it: that field describes which\n * way the DATA flows, so Bling, NeoChef and every acquirer declare `inbound`\n * while being things this app reaches out to. Reading the two as one word put\n * half the shelf under \"Conectados a você\".\n */\n granted?: boolean\n builtIn?: boolean\n revocable?: boolean\n readOnly?: boolean\n scopes?: string[]\n grantedByMe?: boolean\n identityVerified?: boolean\n clientWebsite?: string\n createdAt?: string | null\n lastUsedAt?: string | null\n /** Runtime facts about a granted assistant (model, execution plane). */\n agentConfig?: AgentGrant['config']\n\n /** The live definition, when this app actually has the connector installed. */\n definition?: ConnectorDefinition\n}\n\n/** An inbound grant as the agent connections API returns it. */\nexport interface AgentGrant {\n id: string\n direction: 'inbound' | 'outbound'\n kind: string\n builtIn?: boolean\n revocable?: boolean\n clientName: string\n clientWebsite?: string\n clientLogoUri?: string\n identityVerified?: boolean\n description?: string | null\n enabled?: boolean\n scopes: string[]\n readOnly: boolean\n grantedByMe: boolean\n createdAt: string | null\n lastUsedAt: string | null\n config?: {\n model?: string | null\n channel?: { status: string; audience: string } | null\n executionPlane?: string\n }\n capabilities?: { entities: number; tools: string[] }\n}\n\n/** A row of the Fayz connector directory — read here for copy and brand mark only. */\nexport interface CatalogConnector {\n slug: string\n name: string\n description?: string\n category?: string\n /** Builder-audience flag (\"the Fayz panel has this wired\"). Never a tenant signal. */\n enabled?: boolean\n logoUrl?: string\n iconUrl?: string\n}\n\n/**\n * Every category, in the tenant's language.\n *\n * Keyed by `ConnectorCategory` and not `string`, so the compiler is what catches\n * the next shelf the catalogue adds. This map trailed the catalogue by five\n * entries when M6 opened — `marketplace`, `crm`, `banking`, `local` and\n * `courses` all rendered no badge — and nothing failed, which is exactly the\n * failure mode a `Record<string, string>` guarantees.\n */\nexport const CATEGORY_LABELS: Record<ConnectorCategory, string> = {\n database: 'Dados',\n payments: 'Pagamentos',\n banking: 'Banco',\n erp: 'ERP',\n logistics: 'Logística',\n marketplace: 'Marketplace',\n ecommerce: 'Loja',\n crm: 'CRM',\n courses: 'Cursos',\n scheduling: 'Agenda',\n messaging: 'Mensagens',\n analytics: 'Análise',\n local: 'Presença local',\n ai: 'IA',\n automation: 'Automação',\n}\n\n/**\n * The badge text for a category, or nothing.\n *\n * Still tolerant of an unknown string at runtime: a connector definition may\n * arrive from a published third-party package built against an older core, and\n * a raw `logistics` in front of a salon owner reads as a bug while a missing\n * badge costs nothing.\n */\nexport function categoryLabel(category?: string): string | undefined {\n return category && isConnectorCategory(category) ? CATEGORY_LABELS[category] : undefined\n}\n\nexport interface ConnectorGroup {\n key: string\n label: string\n connectors: UnifiedConnector[]\n}\n\n/**\n * The order the shelves appear in, and it is not alphabetical.\n *\n * It reads as a business: what the money comes through, what the back office\n * is, where else it sells, how it ships — then the softer ones. Alphabetical\n * would put `Análise` above `Pagamentos`, which is true of the words and false\n * of the shop.\n */\n/** The order the shelves appear in, wherever connectors are grouped — the\n * settings list and the assistant's suggestions read the same way. */\nexport const CATEGORY_ORDER: ConnectorCategory[] = [\n 'payments',\n 'banking',\n 'erp',\n 'marketplace',\n 'ecommerce',\n 'logistics',\n 'crm',\n 'messaging',\n 'scheduling',\n 'courses',\n 'analytics',\n 'local',\n 'ai',\n 'automation',\n 'database',\n]\n\n/**\n * Split anything that carries a `category` into labelled shelves, in\n * CATEGORY_ORDER. Generic because the settings list groups `UnifiedConnector`\n * and the assistant groups its own card shape, and they must shelve alike.\n *\n * An unknown category keeps its place at the END rather than disappearing — a\n * connector from a package built against an older core is a real case.\n */\nexport function shelveByCategory<T extends { category?: string }>(\n items: T[],\n): Array<{ key: string; label: string; items: T[] }> {\n const byCategory = new Map<string, T[]>()\n for (const item of items) {\n const key = item.category ?? '_other'\n const bucket = byCategory.get(key)\n if (bucket) bucket.push(item)\n else byCategory.set(key, [item])\n }\n\n const shelves: Array<{ key: string; label: string; items: T[] }> = []\n for (const category of CATEGORY_ORDER) {\n const bucket = byCategory.get(category)\n if (!bucket) continue\n shelves.push({ key: category, label: categoryLabel(category) || '', items: bucket })\n byCategory.delete(category)\n }\n for (const [key, bucket] of byCategory) {\n shelves.push({ key, label: key === '_other' ? '' : categoryLabel(key) || '', items: bucket })\n }\n return shelves\n}\n\n/**\n * The list, cut into labelled shelves.\n *\n * What was GRANTED comes first and is one group regardless of category, because\n * it answers a different question: everything below is something this app\n * reaches out to, and this is somebody else holding access to this\n * organization. Filing a connected assistant under `Análise` because of a\n * category field would bury the only rows on the screen that represent that.\n *\n * A row whose category the build does not know keeps its place rather than\n * disappearing — `categoryLabel` already returns nothing for an unknown string,\n * and a connector from a package built against an older core is a real case.\n */\nexport function groupConnectors(connectors: UnifiedConnector[]): ConnectorGroup[] {\n // `granted` and NOT `direction`: that field says which way the data flows, so\n // Bling, NeoChef and every acquirer declare `inbound` while being things this\n // app reaches out to. Reading the two as one word put half the shelf under\n // \"Conectados a você\".\n const granted = connectors.filter((c) => c.granted)\n const reached = connectors.filter((c) => !c.granted)\n\n const byCategory = new Map<string, UnifiedConnector[]>()\n for (const connector of reached) {\n const key = connector.category && isConnectorCategory(connector.category) ? connector.category : '_other'\n const bucket = byCategory.get(key)\n if (bucket) bucket.push(connector)\n else byCategory.set(key, [connector])\n }\n\n const groups: ConnectorGroup[] = []\n if (granted.length > 0) {\n groups.push({ key: 'granted', label: 'Conectados a você', connectors: granted })\n }\n for (const category of CATEGORY_ORDER) {\n const bucket = byCategory.get(category)\n if (bucket) groups.push({ key: category, label: CATEGORY_LABELS[category], connectors: bucket })\n }\n const other = byCategory.get('_other')\n if (other) groups.push({ key: 'other', label: 'Outros', connectors: other })\n\n return groups\n}\n\n/** An installed connector plus the status the hub already resolved for it. */\nexport interface InstalledConnector {\n definition: ConnectorDefinition\n connected?: boolean\n detail?: string\n /** Everything wrong with the live connection, when there is more than one thing. */\n issues?: string[]\n /** Plane reported by `getStatus()`; falls back to the preferred one. */\n plane?: ConnectorPlane\n /** Connected, waiting on a required-to-operate setting. */\n needsSetup?: boolean\n /** Which setting keys are missing. Keys only. */\n missingSettings?: string[]\n}\n\n/**\n * The catalogue slug a connector joins on.\n *\n * The id names the implementation and the slug names the provider; they are\n * only usually the same word. `plugbank` IS the directory's `tecnospeed` — and\n * until the definition said so, that row looked up a slug that is not there and\n * rendered a grey plug next to a household brand.\n */\nexport function connectorSlug(def: Pick<ConnectorDefinition, 'id' | 'catalogSlug'>): string {\n return def.catalogSlug ?? def.id\n}\n\n/**\n * The brand mark baked in at build time, by slug.\n *\n * {@link SDK_INTEGRATIONS} already carries the mark the catalogue would lend —\n * the emit script fails CI on a connector with no face — so it is the fallback\n * for a screen that skips the catalogue fetch on purpose. Automações is one:\n * it reads the connector list without grants and without the directory so the\n * page makes no network call, and until this existed that choice cost Bling its\n * logo and put a grey plug next to a household name.\n */\nconst MARK_BY_SLUG = new Map<string, string>()\nfor (const row of SDK_INTEGRATIONS) {\n if (row.logoUrl && !MARK_BY_SLUG.has(row.slug)) MARK_BY_SLUG.set(row.slug, row.logoUrl)\n}\n\nfunction fromInstalled(entry: InstalledConnector, catalog?: CatalogConnector): UnifiedConnector {\n const def = entry.definition\n const planes = connectorPlanes(def)\n return {\n id: def.id,\n slug: connectorSlug(def),\n name: def.name,\n // The catalogue's copy wins: it is served in the user's locale, while a\n // definition carries whatever language its plugin author wrote it in.\n description: catalog?.description ?? def.description,\n direction: connectorDirection(def),\n planes,\n activePlane: entry.connected ? (entry.plane ?? preferredPlane(def)) : undefined,\n state: entry.connected ? (entry.needsSetup ? 'needs_setup' : 'connected') : 'ready',\n missingSettings: entry.needsSetup ? entry.missingSettings : undefined,\n hostPluginId: def.hostPluginId,\n category: def.category ?? catalog?.category,\n icon: def.icon,\n logoUrl: def.logoUrl ?? catalog?.logoUrl ?? catalog?.iconUrl ?? MARK_BY_SLUG.get(connectorSlug(def)),\n // Derived, never read off the field: a connector that declares permissions\n // does not also keep a parallel list of names for this to pick between.\n entities: orUndefined(connectorEntities(def)),\n permissions: orUndefined(connectorPermissions(def)),\n agentTools: def.agentTools,\n detail: entry.detail,\n issues: orUndefined(entry.issues ?? []),\n docsUrl: def.docsUrl,\n definition: def,\n }\n}\n\n/**\n * An inbound grant is agentic by construction: nothing was copied anywhere, an\n * assistant was handed tools over MCP. That is the same shape as an outbound\n * connector resolved on the agentic plane, which is exactly why they share a\n * list — `direction` is what tells them apart, not a separate page.\n */\nfunction fromGrant(grant: AgentGrant): UnifiedConnector {\n const tools = grant.capabilities?.tools ?? []\n return {\n id: grant.id,\n slug: grant.kind || grant.id,\n name: grant.clientName,\n description: grant.description ?? undefined,\n direction: grant.direction,\n granted: true,\n planes: ['agentic'],\n activePlane: 'agentic',\n state: 'connected',\n logoUrl: grant.clientLogoUri,\n agentTools: tools.map((name) => ({ name })),\n entityCount: grant.capabilities?.entities,\n builtIn: grant.builtIn,\n revocable: grant.revocable,\n readOnly: grant.readOnly,\n scopes: grant.scopes,\n grantedByMe: grant.grantedByMe,\n identityVerified: grant.identityVerified,\n clientWebsite: grant.clientWebsite,\n createdAt: grant.createdAt,\n lastUsedAt: grant.lastUsedAt,\n agentConfig: grant.config,\n }\n}\n\n/**\n * Merge the sources into the single list both surfaces render.\n *\n * A row exists if and only if something in THIS app backs it: an installed\n * `ConnectorDefinition`, or a grant somebody approved. The Fayz catalogue is\n * enrichment and nothing else — it lends an installed connector its localized\n * copy and its brand mark, and contributes no row of its own.\n *\n * It used to. The catalogue is the *builder* directory: `enabled` there means\n * \"the Fayz panel has this wired for a builder org\" (its Supabase row is about\n * provisioning an app's database), and reading that flag from a tenant screen\n * offered Supabase, Anthropic and Google Analytics to the owner of a salon.\n * An audience flag consumed audience-blind is not a filter problem — the rows\n * were never addressed to this reader.\n */\nexport function buildConnectorList(input: {\n installed?: InstalledConnector[]\n grants?: AgentGrant[]\n catalog?: CatalogConnector[]\n}): UnifiedConnector[] {\n const catalogBySlug = new Map((input.catalog ?? []).map((c) => [c.slug, c]))\n const built = (input.installed ?? []).map((entry) => ({\n entry,\n row: fromInstalled(entry, catalogBySlug.get(connectorSlug(entry.definition))),\n }))\n\n // The catalogue names the PROVIDER, and a provider can be integrated twice for\n // genuinely different reasons — Stripe is the platform paying a course creator\n // (`stripe-connect`) and the tenant billing their own customer (`stripe`).\n // Side by side, one localized sentence about \"Stripe\" describes both equally\n // and tells them apart not at all, which is what put two identical rows on the\n // connectors screen. So the catalogue keeps winning while a slug appears once\n // — that is the locale argument above, and it holds — and each connector's own\n // sentence wins the moment it has a twin to be distinguished from.\n const perSlug = new Map<string, number>()\n for (const { row } of built) perSlug.set(row.slug, (perSlug.get(row.slug) ?? 0) + 1)\n\n const installed = built.map(({ entry, row }) =>\n (perSlug.get(row.slug) ?? 0) > 1 && entry.definition.description\n ? { ...row, description: entry.definition.description }\n : row,\n )\n const grants = (input.grants ?? []).map(fromGrant)\n return sortConnectors([...grants, ...installed])\n}\n\n// What still needs a decision comes first: it is the only row on the screen with\n// something to do about it.\nconst STATE_RANK: Record<ConnectorState, number> = { needs_setup: 0, connected: 1, ready: 2 }\n\n/** Connected first, then what can be connected here; alphabetical within each. */\nexport function sortConnectors(list: UnifiedConnector[]): UnifiedConnector[] {\n return [...list].sort((a, b) => {\n const byState = STATE_RANK[a.state] - STATE_RANK[b.state]\n if (byState !== 0) return byState\n return a.name.localeCompare(b.name)\n })\n}\n\n/** One event a live connector says it listens to, with the reaction it owns. */\nexport interface ConnectorSubscription {\n /** Exact key of a managed automation, or the raw pattern when none covers it. */\n key: string\n /** What the tenant is told happens — only for an automation the connector owns. */\n label?: string\n}\n\n/**\n * What a connector listens to, once it is live.\n *\n * Empty until connected on purpose: a subscription is a fact about a running\n * connection, and listing it next to a connect button would read as a promise\n * the app has not made yet.\n */\nexport function connectorSubscriptions(connector: UnifiedConnector): ConnectorSubscription[] {\n // A connection waiting on configuration is still live: the facts reach it, it\n // just cannot do its job with them yet. Hiding the list there would answer\n // \"what is it listening to?\" with silence for the one state where somebody is\n // actively looking.\n if (!isLive(connector.state)) return []\n return declaredSubscriptions(connector.definition)\n}\n\n/** Live — authorized, whether or not it is fully configured. */\nexport function isLive(state: ConnectorState): boolean {\n return state === 'connected' || state === 'needs_setup'\n}\n\n/** Keeps an empty derived list out of the view model, where it read as \"declared nothing\". */\nfunction orUndefined<T>(list: T[]): T[] | undefined {\n return list.length > 0 ? list : undefined\n}\n\n/** The subscription list a definition declares, regardless of connection state. */\nfunction declaredSubscriptions(def: ConnectorDefinition | undefined): ConnectorSubscription[] {\n const automations = def?.managedAutomations ?? []\n const out: ConnectorSubscription[] = []\n for (const pattern of connectorSubscribesTo(def)) {\n const covered = automations.filter((a: ConnectorManagedAutomation) => eventKeyMatches(pattern, a.eventKey))\n if (covered.length === 0) out.push({ key: pattern })\n else for (const a of covered) out.push({ key: a.eventKey, label: a.label })\n }\n return out.filter((s, i) => out.findIndex((x) => x.key === s.key) === i)\n}\n\n/**\n * \"Acionado em quais momentos\" — the two answers, kept apart.\n *\n * `calls` are invocations that exist in code and may be described plainly.\n * `events` are subscriptions, which the platform does not dispatch yet, so the\n * copy next to them says \"ouve\" and never \"reage\". Splitting them here rather\n * than in the component is what keeps that distinction assertable.\n *\n * Unlike {@link connectorSubscriptions}, this answers before the connection\n * exists: it describes what the connector IS, which is what step 1 is for.\n */\nexport function connectorMoments(connector: UnifiedConnector): {\n calls: ConnectorInvocation[]\n events: ConnectorSubscription[]\n} {\n return {\n calls: connector.definition?.invokedAt ?? [],\n events: declaredSubscriptions(connector.definition),\n }\n}\n\n// ---------------------------------------------------------------------------\n// The shelf — what the modules in play put within reach\n// ---------------------------------------------------------------------------\n\n/**\n * A slug a module put on the shelf, and cannot be connected right now.\n *\n * Deliberately NOT a {@link UnifiedConnector}: there is no connection, no\n * status to probe and nothing to click, and giving it a `state` would be the\n * third state #89 deleted — the one that turned \"the platform could build this\"\n * into a row a salon owner was invited to press. What it carries instead is\n * why: a module that is not here, or an integration that is not built yet.\n */\nexport interface ShelfIntegration {\n id: string\n slug: string\n name: string\n description?: string\n category?: string\n icon?: string\n logoUrl?: string\n planes?: ConnectorPlane[]\n direction?: ConnectorDirection\n /** Plugin id of the module that brings it — labelled through i18n. */\n moduleId: string\n /** Whether that module is mounted in this build. */\n moduleInstalled: boolean\n /** `available` — implemented, waiting on the module. `soon` — declared, not built. */\n status: 'available' | 'soon'\n}\n\n/**\n * The rows \"Adicionar conector\" can offer: everything an installed plugin backs.\n *\n * What it drops is a granted assistant — that arrives by approving a consent\n * screen, not by being added, and it is already in the list behind the panel.\n * The tell is having no `definition`, NOT `direction`: direction is which side\n * reaches for the other, and filtering on it silently hid Bling, PlugBank and\n * RankLayer — three connectors an installed plugin ships and a shopkeeper came\n * here to add.\n */\nexport function addableConnectors(list: UnifiedConnector[]): UnifiedConnector[] {\n return list.filter((c) => c.definition != null || c.direction === 'outbound')\n}\n\n/**\n * Narrow any connector-ish list to the categories a section is about.\n *\n * One function for both the installed rows and the shelf, because the bug it\n * fixes was the two disagreeing: \"Provedores de pagamento\" filtered its own\n * list by `payments` and then opened an add panel that offered the ERP and the\n * carrier. No categories means no narrowing — the hub is the whole app.\n *\n * A row with no category is dropped when a scope is given: it cannot be shown\n * to belong, and guessing is how a gateway list grows a CRM.\n */\nexport function inCategories<T extends { category?: string }>(list: T[], categories?: string[]): T[] {\n if (!categories?.length) return list\n const scope = new Set(categories)\n return list.filter((item) => !!item.category && scope.has(item.category))\n}\n\n/**\n * Everything the modules put within reach that is not already a row above.\n *\n * The source is {@link SDK_INTEGRATIONS}, generated from the plugin manifests\n * in this repo — never the platform catalogue. The catalogue is a builder\n * directory with no notion of a host plugin, and reading it here is how the\n * owner of a salon was once offered Supabase and Anthropic. What decides is the\n * module: having CRM is what makes Kommo relevant, having Financeiro is what\n * makes AbacatePay relevant. A slug reaches this list because a manifest asked\n * for it, and for no other reason — asserted, not assumed.\n *\n * The catalogue is still read, for exactly two things: the localized name and\n * the brand mark, joined by slug. It contributes no row.\n *\n * One row per slug, even though a slug can be on two modules' shelves (Stripe\n * is money-in for Loja, Financeiro and Cursos). The winner is the module this\n * app actually has, then the one that already implements it — a shopkeeper does\n * not care which module technically hosts it, only whether it is within reach.\n */\nexport function shelfIntegrations(input: {\n present: UnifiedConnector[]\n /** Plugin ids mounted in this build — what tells \"em breve\" from \"outro módulo\". */\n installedModules?: Iterable<string>\n /** The Fayz directory, for the localized name and the brand mark. */\n catalog?: CatalogConnector[]\n map?: readonly SdkIntegration[]\n}): ShelfIntegration[] {\n const here = new Set(input.present.map((c) => c.slug))\n const modules = new Set(input.installedModules ?? [])\n const catalogBySlug = new Map((input.catalog ?? []).map((c) => [c.slug, c]))\n\n const bySlug = new Map<string, ShelfIntegration>()\n for (const row of input.map ?? SDK_INTEGRATIONS) {\n if (here.has(row.slug)) continue\n // An addon ships its connector separately from the module that hosts it, so\n // the host being present is not enough for the row to be reachable.\n const installed = modules.has(row.moduleId) && modules.has(row.declaredBy.pluginId)\n const catalog = catalogBySlug.get(row.slug)\n const candidate: ShelfIntegration = {\n id: row.slug,\n slug: row.slug,\n name: row.name,\n description: row.description,\n category: row.category,\n icon: row.icon,\n logoUrl: row.logoUrl ?? catalog?.logoUrl ?? catalog?.iconUrl,\n planes: row.planes,\n direction: row.direction,\n moduleId: row.moduleId,\n moduleInstalled: installed,\n status: row.status,\n }\n const previous = bySlug.get(row.slug)\n if (!previous || rank(candidate) < rank(previous)) bySlug.set(row.slug, candidate)\n }\n\n return [...bySlug.values()].sort(\n (a, b) => a.moduleId.localeCompare(b.moduleId) || a.name.localeCompare(b.name),\n )\n}\n\n/** Closest to reach first, when the same slug sits on more than one shelf. */\nfunction rank(row: ShelfIntegration): number {\n return (row.moduleInstalled ? 0 : 2) + (row.status === 'available' ? 0 : 1)\n}\n\n/** Declared by a module this app HAS, and not built yet — informational. */\nexport function comingSoonHere(list: ShelfIntegration[]): ShelfIntegration[] {\n return list.filter((row) => row.moduleInstalled)\n}\n\n/** Implemented or promised by a module this app was not built with. */\nexport function withAnotherModule(list: ShelfIntegration[]): ShelfIntegration[] {\n return list.filter((row) => !row.moduleInstalled)\n}\n\n/** Same free-text match the installed list uses, so one query filters both. */\nexport function filterAvailable(list: ShelfIntegration[], query = ''): ShelfIntegration[] {\n const q = query.trim().toLowerCase()\n if (!q) return list\n return list.filter((c) => `${c.name} ${c.slug} ${c.description ?? ''}`.toLowerCase().includes(q))\n}\n\nexport type ConnectorFilter = 'all' | 'connected' | 'agentic' | 'sync' | 'inbound' | 'outbound'\n\nexport function filterConnectors(\n list: UnifiedConnector[],\n filter: ConnectorFilter,\n query = '',\n): UnifiedConnector[] {\n const q = query.trim().toLowerCase()\n return list.filter((c) => {\n if (q && !`${c.name} ${c.slug} ${c.description ?? ''}`.toLowerCase().includes(q)) return false\n switch (filter) {\n case 'connected':\n return isLive(c.state)\n case 'agentic':\n return c.planes.includes('agentic')\n case 'sync':\n return c.planes.includes('sync')\n case 'inbound':\n return c.direction === 'inbound'\n case 'outbound':\n return c.direction === 'outbound'\n default:\n return true\n }\n })\n}\n\n/** Deep link to where a connector is actually configured. */\nexport function connectorRoute(connector: Pick<UnifiedConnector, 'hostPluginId'>): string {\n return connector.hostPluginId\n ? `/settings/${connector.hostPluginId}/_integrations`\n : '/settings/connectors'\n}\n","import React from 'react'\nimport { Sparkles, RefreshCw, ArrowDownLeft, ArrowUpRight, ChevronRight } from 'lucide-react'\nimport { Button, Badge } from '@fayz-ai/ui'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { ConnectorMark } from './ConnectorMark'\nimport type { ConnectorPlane, ConnectorState, UnifiedConnector } from './model'\nimport { categoryLabel, isLive } from './model'\n\n/**\n * How a connector is honoured, as a badge.\n *\n * Two planes, and the difference is the whole point of merging the screens: the\n * agentic one hands tools to the assistant and copies nothing; the sync one\n * keeps a mirror inside the app. The user does not need the words \"MCP\" or\n * \"webhook\" to make that choice — they need to know whether there will be a\n * copy of their data and whether it can go stale.\n */\nexport function PlaneBadge({ plane, active }: { plane: ConnectorPlane; active?: boolean }) {\n const { t } = useTranslation()\n const Icon = plane === 'agentic' ? Sparkles : RefreshCw\n return (\n <span\n className={\n 'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[11px] ' +\n (active\n ? plane === 'agentic'\n ? 'bg-primary/10 text-primary'\n : 'bg-muted text-foreground'\n : 'border border-border text-muted-foreground')\n }\n >\n <Icon className=\"h-3 w-3\" />\n {t(`connectors.plane.${plane}`)}\n </span>\n )\n}\n\nexport function DirectionBadge({ direction }: { direction: 'inbound' | 'outbound' }) {\n const { t } = useTranslation()\n const Icon = direction === 'inbound' ? ArrowDownLeft : ArrowUpRight\n return (\n <span className=\"inline-flex items-center gap-1 rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground\">\n <Icon className=\"h-3 w-3\" />\n {t(`connectors.direction.${direction}`)}\n </span>\n )\n}\n\n// Warning and not destructive for `needs_setup`: nothing is broken, something is\n// unanswered. `ready` is neutral — \"not connected\" is not a problem.\nconst STATE_VARIANT: Record<ConnectorState, 'success' | 'warning' | 'outline'> = {\n connected: 'success',\n needs_setup: 'warning',\n ready: 'outline',\n}\n\n/**\n * A connection's state, in one badge, everywhere it is shown.\n *\n * One component and one vocabulary across the list, the assistant's drawer and\n * the connection's own header — the founder's ask, and the reason the label is\n * now short enough to sit beside a name: \"conectado · falta configurar\" was a\n * sentence pretending to be a chip.\n */\nexport function StateChip({ state, className }: { state: ConnectorState; className?: string }) {\n const { t } = useTranslation()\n return (\n <Badge variant={STATE_VARIANT[state]} className={className}>\n {t(`connectors.state.${state}`)}\n </Badge>\n )\n}\n\n/**\n * One row of the unified list — an inbound grant or an installed connector, both\n * the same shape. The row is the entry point of the journey: it says what the\n * thing is and how far along it is, and opening it is what explains the rest.\n */\nexport function ConnectorRow({\n connector,\n onOpen,\n}: {\n connector: UnifiedConnector\n onOpen: (connector: UnifiedConnector) => void\n}) {\n const { t } = useTranslation()\n const category = categoryLabel(connector.category)\n\n return (\n <li>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={() => onOpen(connector)}\n className=\"flex w-full items-start gap-4 p-4 text-left transition-colors hover:bg-muted/40 justify-start whitespace-normal text-[length:inherit] font-normal rounded-none\"\n >\n <ConnectorMark connector={connector} />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium text-foreground\">{connector.name}</span>\n {connector.builtIn && (\n <span className=\"rounded-full bg-primary/10 px-2 py-0.5 text-[11px] font-medium text-primary\">\n {t('connectors.builtIn')}\n </span>\n )}\n {/* Only the plane a LIVE connection settled on. Offering both on a\n row nobody has connected yet, next to an inbound/outbound badge\n and a module badge and a state chip, was four pieces of chrome\n around one name — and the choice is made in the detail anyway. */}\n {connector.activePlane && <PlaneBadge plane={connector.activePlane} active />}\n {/* The category, never the host plugin id. `courses` next to Stripe\n read as the shelf Stripe is filed under — and Stripe is filed\n under payments. It was also a raw plugin id, untranslated, in a\n list a shopkeeper reads. Which module offers a connector is a\n fact about how Fayz is built, so it belongs in the detail, where\n there is room to say it in words. */}\n {category && (\n <span className=\"rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground\">\n {category}\n </span>\n )}\n </div>\n {connector.description && (\n <p className=\"mt-0.5 line-clamp-1 text-xs text-muted-foreground\">{connector.description}</p>\n )}\n {isLive(connector.state) && !connector.description && connector.detail && (\n <p className=\"mt-0.5 text-xs text-muted-foreground\">{connector.detail}</p>\n )}\n </div>\n <span className=\"flex shrink-0 items-center gap-2 pt-1\">\n <StateChip state={connector.state} />\n <ChevronRight className=\"h-4 w-4 text-muted-foreground\" />\n </span>\n </Button>\n </li>\n )\n}\n","import type { ConnectorDefinition, ConnectorField, TestConnectionResult } from '@fayz-ai/core'\nimport { getConnectorCredentialSink, type ConnectorCredentialSink } from '@fayz-ai/sdk'\n\n/**\n * The split that keeps a tenant's secret out of connector-author code.\n *\n * The setup form collects one object; two very different things are in it. The\n * domain the RankLayer account publishes to is configuration — the connector\n * needs it, and it belongs in the app's own row. The API key next to it is a\n * credential, and the moment `saveConnection(values)` is called with it, where\n * it ends up is decided by code the platform does not own.\n *\n * Everything a connector is called through goes past here, so the split is not\n * something each call site has to remember: `submitConnection` and\n * `probeConnection` are the only two doors, and `NonSecretValues` is what comes\n * out of both. The contract in `@fayz-ai/core` still types the callbacks as\n * `Record<string, string>`, so the narrowing is expressed here — a plain\n * `values` object is not a `NonSecretValues` and cannot be passed as one.\n */\n\ndeclare const nonSecret: unique symbol\n\n/** Form values that have been through the split — the only shape author code is handed. */\nexport type NonSecretValues = Record<string, string> & { readonly [nonSecret]: true }\n\n/** The connection could not be saved because this app has nowhere safe to put the secret. */\nexport class CredentialSinkMissingError extends Error {\n constructor() {\n super('No connector credential sink configured')\n this.name = 'CredentialSinkMissingError'\n }\n}\n\n/** Masked, or explicitly marked — the unmasked half of a credential pair is still a credential. */\nexport function isSecretField(field: ConnectorField): boolean {\n return field.type === 'password' || field.secret === true\n}\n\n/** Whether saving this connector needs a sink at all — a connector with no secret asks nothing of the app. */\nexport function needsCredentialSink(definition: Pick<ConnectorDefinition, 'fields'>): boolean {\n return (definition.fields ?? []).some(isSecretField)\n}\n\nexport function splitConnectorValues(\n fields: ConnectorField[] | undefined,\n values: Record<string, string>,\n): { safe: NonSecretValues; secrets: Record<string, string> } {\n const safe: Record<string, string> = {}\n const secrets: Record<string, string> = {}\n // Driven by the declaration, not by the object: a key the connector never\n // asked for is dropped rather than assumed harmless.\n for (const field of fields ?? []) {\n const value = values[field.key]\n if (value === undefined) continue\n ;(isSecretField(field) ? secrets : safe)[field.key] = value\n }\n return { safe: safe as NonSecretValues, secrets }\n}\n\n/**\n * Test the connection with the non-secret half.\n *\n * The secret is discarded rather than forwarded: a pre-save test that worked\n * would have to hand the credential to author code, which is the one thing this\n * module exists to prevent. What a connector can still test this way is the\n * connection it already has — so the hub only offers the button when there is\n * no secret in the form.\n */\nexport async function probeConnection(input: {\n definition: ConnectorDefinition\n values: Record<string, string>\n}): Promise<TestConnectionResult> {\n const { safe } = splitConnectorValues(input.definition.fields, input.values)\n return input.definition.testConnection!(safe)\n}\n\n/**\n * Place the credential, then save the rest.\n *\n * Sink first: a connection saved against a credential that never landed reads\n * as \"connected\" and fails at the first sync, which is the harder failure to\n * diagnose of the two.\n */\nexport async function submitConnection(input: {\n definition: ConnectorDefinition\n /** Raw form values, secrets included — this is where they part ways. */\n values: Record<string, string>\n tenantId?: string\n /** Defaults to the app's configured sink; pass `null` to assert there is none. */\n sink?: ConnectorCredentialSink | null\n}): Promise<void> {\n const { safe, secrets } = splitConnectorValues(input.definition.fields, input.values)\n\n if (Object.keys(secrets).length > 0) {\n const sink = input.sink === undefined ? getConnectorCredentialSink() : input.sink\n // Fail closed. Falling back to `saveConnection(values)` would hand the\n // secret to author code — the exact hole this replaces.\n if (!sink) throw new CredentialSinkMissingError()\n // `authKind` comes off the declaration, not off the form: the holder records\n // how the tenant authorized, and the only place that knows is the connector.\n await sink.store({\n connectorId: input.definition.id,\n tenantId: input.tenantId,\n authKind: input.definition.authKind,\n secrets,\n })\n }\n\n await input.definition.saveConnection?.(safe)\n}\n","import React from 'react'\nimport { ChevronRight, Info } from 'lucide-react'\n\n/**\n * The two disclosure shapes the connector detail screens share.\n *\n * Both were tooltips for one afternoon and that was the wrong instrument: a\n * tooltip is invisible on touch, closes when you move to read it, and can hold\n * a phrase but not a sentence — and what is behind these is a sentence. Both\n * are `<details>` instead: it opens on click, it opens on Enter, its content is\n * in the DOM whether open or shut (so find-in-page and screen readers reach it,\n * and Chrome opens it to show a match), and it needs no state.\n */\n\n/** One identifier, its chips, and the prose one click below it. */\nexport function DisclosureRow({\n name,\n chips,\n detail,\n}: {\n name: string\n chips?: React.ReactNode\n /** Nothing to expand renders a plain row — an empty accordion is a lie. */\n detail?: React.ReactNode\n}) {\n // Plain text, not a boxed token and not bold. Boxed, every row carried a white\n // card against a tinted panel and the list read as five buttons; bold, five\n // names in a row all shouted. The dotted underline alone says \"this opens\" —\n // and only where there IS something under it.\n const line = (\n <>\n <code\n className={\n 'font-mono text-[11.5px] text-foreground' +\n (detail ? ' underline decoration-dotted decoration-foreground/40 underline-offset-4' : '')\n }\n >\n {name}\n </code>\n {chips}\n </>\n )\n if (!detail) return <div className=\"flex flex-wrap items-center gap-1.5 py-1\">{line}</div>\n return (\n <details className=\"group\">\n <summary className=\"flex cursor-pointer list-none flex-wrap items-center gap-1.5 py-1 hover:bg-foreground/5\">\n {line}\n <ChevronRight className=\"h-3.5 w-3.5 text-muted-foreground transition-transform group-open:rotate-90\" />\n </summary>\n <p className=\"mb-1 pl-1 text-xs leading-relaxed text-foreground/80\">{detail}</p>\n </details>\n )\n}\n\n/**\n * The caveats a panel owes, folded away until someone wants them — behind a\n * LABEL and not a bare ⓘ. An icon alone in a column of lists reads as\n * decoration, so nobody presses it and the sentence behind it is never read,\n * which for these particular sentences is the whole failure.\n */\nexport function DisclosureNote({ label, children }: { label: string; children: React.ReactNode }) {\n return (\n <details className=\"group\">\n <summary className=\"flex w-fit cursor-pointer list-none items-center gap-1 text-[11px] font-medium text-muted-foreground hover:text-foreground\">\n <Info className=\"h-3.5 w-3.5\" />\n {label}\n <ChevronRight className=\"h-3 w-3 transition-transform group-open:rotate-90\" />\n </summary>\n <div className=\"mt-1 border-l-2 border-border pl-2 text-[11px] leading-relaxed text-foreground/70\">\n {children}\n </div>\n </details>\n )\n}\n","import React from 'react'\nimport { Database, Radio, ShieldAlert, Zap } from 'lucide-react'\nimport type { ConnectorPermission, ConnectorPermissionAction } from '@fayz-ai/core'\nimport { groupedPermissions, invocationPlane } from '@fayz-ai/core'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { DisclosureNote, DisclosureRow } from './ConnectorDisclosure'\nimport { connectorMoments, type UnifiedConnector } from './model'\n\n/**\n * What the connector declared: the records it reaches, the facts it hears, and\n * the moments it is called. The consent view, before authorizing.\n *\n * It renders in step 1 of the journey, which is the step that exists precisely\n * so nobody is asked for a credential before they know what it buys. The grammar\n * is OAuth consent's, because that is the one a reader already has: grouped by\n * resource, one reason per row, read told apart from write, sensitive marked.\n *\n * **One panel, because it was one subject.** \"Quando ele age\" used to be a\n * second, collapsible box under this one — and it listed the same event keys\n * from the same declaration, so the reader met `agenda.booking_created` twice\n * and had to work out whether the two lists disagreed. They never could: the\n * events here ARE the subscriptions. Merged, with calls as a third group.\n *\n * **The one sentence that decides whether this screen is worth having.** Nothing\n * on this platform enforces a permission today: the token minting that would\n * (FAY-1381) landed only its browser half, and FAY-1348 §D7 — *\"a credencial\n * autoriza só as RPCs declaradas do conector\"* — is not built. A screen that says\n * \"this integration can only read your appointments\" while nothing stops it\n * writing them manufactures an assurance that does not exist, which is the exact\n * failure this epic keeps fighting.\n *\n * So the copy states what the declaration IS — what the connector says it needs,\n * shown before you authorize — and `connectors.permissions.notEnforced` says in\n * as many words that Fayz does not yet use it to block anything. When D7 lands,\n * that string is what tightens; nothing else here has to change, because the\n * list is already the list the token will carry ({@link connectorGrantScopes}).\n *\n * The same honesty governs the difference between the two lower groups, which is\n * why they are not merged in turn: a CALL happens — code in this app invokes the\n * connector at that moment. A fact it OUVE does not, yet: the generic ingress\n * that reads `subscribesTo` and dispatches does not exist (docs/integrations/\n * EVENTS.md), each connector delivers its own reaction today, and the copy must\n * survive that gap without promising it closed. \"Ouve\", never \"reage\".\n *\n * Prose sits one click below the name it belongs to. Read as paragraphs under\n * every row, the reasons were longer than the list they qualified and the panel\n * became a wall nobody finishes — and a list nobody finishes discloses nothing.\n *\n * Absence is rendered as absence: a connector that declared nothing says so,\n * rather than showing an empty box that reads as \"it touches nothing\".\n */\nexport function ConnectorPermissions({ connector }: { connector: UnifiedConnector }) {\n const { t } = useTranslation()\n const { data, events } = groupedPermissions(connector.definition ?? connector)\n const { calls, events: subscriptions } = connectorMoments(connector)\n\n // A subscription the permission list never mentioned still belongs on screen:\n // `subscribesTo` is a declaration too, and the connector that declares one\n // without the other is exactly the case a reader must be able to see.\n const declared = new Set(events.map((permission) => permission.resource))\n const extraEvents = subscriptions.filter((subscription) => !declared.has(subscription.key))\n const empty = data.length === 0 && events.length === 0 && extraEvents.length === 0 && calls.length === 0\n\n // An inbound grant has no definition and therefore nothing to have declared —\n // what it was given is the scope list `Capabilities` already renders, and that\n // one IS enforced server-side. Saying \"declarou nada\" above it would be a\n // second, contradicting answer to the same question. Nothing at all is right:\n // this section is about a declaration only an installed connector can make.\n if (empty && !connector.definition) return null\n\n return (\n // Filled, not outlined: on a white drawer an outlined box of grey type is a\n // wall with a line around it. The fill is the one step 2's card carries, so\n // step 1 reads as a panel and not as leftover page.\n <section className=\"rounded-lg border border-border bg-muted/40\">\n <p className=\"border-b border-border bg-muted/60 px-3 py-2 text-sm font-semibold text-foreground\">\n {t('connectors.permissions.title')}\n </p>\n {empty ? (\n <p className=\"p-3 text-xs text-foreground/80\">{t('connectors.permissions.undeclared')}</p>\n ) : (\n <div className=\"space-y-3 p-3\">\n {data.length > 0 && (\n <Group icon={<Database className=\"h-3.5 w-3.5 text-foreground/60\" />} title={t('connectors.permissions.data')}>\n {data.map((permission) => (\n <PermissionRow key={`data:${permission.resource}`} permission={permission} />\n ))}\n </Group>\n )}\n\n {(events.length > 0 || extraEvents.length > 0) && (\n <Group\n icon={<Radio className=\"h-3.5 w-3.5 text-foreground/60\" />}\n title={t('connectors.permissions.events')}\n >\n {events.map((permission) => (\n <PermissionRow key={`event:${permission.resource}`} permission={permission} />\n ))}\n {extraEvents.map((subscription) => (\n <li key={`sub:${subscription.key}`}>\n <DisclosureRow\n name={subscription.key}\n detail={subscription.label}\n chips={<ActionChip action=\"listen\" />}\n />\n </li>\n ))}\n </Group>\n )}\n\n {calls.length > 0 && (\n <Group\n icon={<Zap className=\"h-3.5 w-3.5 text-foreground/60\" />}\n title={t('connectors.moments.calls')}\n >\n {calls.map((moment) => (\n <li key={`call:${moment.key}`}>\n <DisclosureRow\n name={moment.key}\n detail={\n <>\n {moment.label}\n {/* The half that was missing: the section said WHEN and\n never WHAT. These are permission resources, not free\n text — the contract check refuses a moment that\n reaches something the connector never asked for. */}\n {moment.touches && moment.touches.length > 0 && (\n <span className=\"mt-0.5 block\">\n {t('connectors.moments.touches')}:{' '}\n <span className=\"font-mono\">{moment.touches.join(', ')}</span>\n </span>\n )}\n </>\n }\n chips={\n <>\n <Chip>{t(`connectors.plane.${invocationPlane(moment)}`)}</Chip>\n {moment.trigger && <Chip>{t(`connectors.trigger.${moment.trigger}`)}</Chip>}\n </>\n }\n />\n </li>\n ))}\n </Group>\n )}\n\n {/* One fold, at the bottom, with a label on it. Three lone ⓘ icons\n scattered between the groups read as decoration — the founder's\n word was \"lost\" — and the caveats they hid are the same three\n sentences every time. */}\n <DisclosureNote label={t('connectors.permissions.noteLabel')}>\n <p>{t('connectors.permissions.notEnforced')}</p>\n {calls.length > 0 && <p className=\"mt-1\">{t('connectors.moments.callsHint')}</p>}\n {(events.length > 0 || extraEvents.length > 0) && (\n <p className=\"mt-1\">{t('connectors.moments.eventsHint')}</p>\n )}\n </DisclosureNote>\n </div>\n )}\n </section>\n )\n}\n\nfunction Group({ icon, title, children }: { icon: React.ReactNode; title: string; children: React.ReactNode }) {\n return (\n <div>\n <p className=\"flex items-center gap-1.5 text-xs font-semibold text-foreground\">\n {icon}\n {title}\n </p>\n <ul className=\"mt-1 divide-y divide-border/60\">{children}</ul>\n </div>\n )\n}\n\n/**\n * One resource and its actions on one line; the reason expands under it.\n *\n * The two are read by different people for different purposes — the operator\n * matching a name against a trace, the owner deciding whether this is\n * reasonable — and only the first has to be scannable.\n */\nfunction PermissionRow({ permission }: { permission: ConnectorPermission }) {\n const { t } = useTranslation()\n return (\n <li>\n <DisclosureRow\n name={permission.resource}\n detail={permission.reason}\n chips={\n <>\n {permission.actions.map((action) => (\n <ActionChip key={action} action={action} />\n ))}\n {permission.sensitive && (\n <span className=\"inline-flex items-center gap-1 rounded-full border border-warning/40 bg-warning/10 px-1.5 py-px text-[10px] font-medium text-warning\">\n <ShieldAlert className=\"h-2.5 w-2.5\" />\n {t('connectors.permissions.sensitive')}\n </span>\n )}\n </>\n }\n />\n </li>\n )\n}\n\n/**\n * Read is not write, and the chip has to say so without being read.\n *\n * `read` and `listen` observe; `write` and `emit` change something. The second\n * pair carries the tinted border, so the rows that matter are countable at a\n * glance on a screen nobody reads word for word.\n */\nfunction ActionChip({ action }: { action: ConnectorPermissionAction }) {\n const { t } = useTranslation()\n const mutating = action === 'write' || action === 'emit'\n return (\n <span\n className={\n 'rounded-full px-1.5 py-px text-[10px] ' +\n (mutating\n ? 'border border-destructive/40 bg-destructive/5 font-medium text-destructive'\n : 'border border-border bg-background font-medium text-foreground/70')\n }\n >\n {t(`connectors.permissions.action.${action}`)}\n </span>\n )\n}\n\nfunction Chip({ children }: { children: React.ReactNode }) {\n return (\n <span className=\"rounded-full border border-border bg-background px-1.5 py-px text-[10px] font-medium text-foreground/70\">\n {children}\n </span>\n )\n}\n","import React from 'react'\nimport { ArrowDownToLine, ArrowUpFromLine, CheckCircle2, ChevronRight, Loader2 } from 'lucide-react'\nimport type { ConnectorSyncAction } from '@fayz-ai/core'\nimport { Button, ConfirmDialog, toast } from '@fayz-ai/ui'\n\n/**\n * One button row, for every connector that can be asked to do something.\n *\n * Google Calendar drew its own; Bling was about to draw a second. Everything\n * that would have been repeated lives here — running state, toast, reloading the\n * history, hiding an action with nothing to act on, confirming a write at the\n * provider. Every word on screen comes off the declaration.\n */\nexport function ConnectorSyncActions({\n actions,\n onRan,\n}: {\n actions: ConnectorSyncAction[]\n onRan?: () => void\n}) {\n const [running, setRunning] = React.useState<string | null>(null)\n const [open, setOpen] = React.useState<ConnectorSyncAction | null>(null)\n const [pending, setPending] = React.useState<ConnectorSyncAction | null>(null)\n const [hidden, setHidden] = React.useState<Set<string>>(() => new Set())\n // How many records each action still has to send. Re-read after every run, so\n // \"enviei tudo\" is what the screen shows the moment it becomes true.\n const [queued, setQueued] = React.useState<Record<string, number | null>>({})\n const [nonce, setNonce] = React.useState(0)\n // Closed: everything behind it is a first-day action or a repair.\n const [expanded, setExpanded] = React.useState(false)\n // Rendering the row and then removing a button is worse than waiting a beat.\n const [resolved, setResolved] = React.useState(false)\n\n React.useEffect(() => {\n let cancelled = false\n setResolved(false)\n void Promise.all(\n actions.map(async (action) => {\n // Offered anyway on a failure: a readable error beats a button that was\n // never there, and an unknown count beats a wrong one.\n const show = action.available ? await Promise.resolve(action.available()).catch(() => true) : true\n const waiting = action.pending ? await Promise.resolve(action.pending()).catch(() => null) : null\n return { key: action.key, show, waiting }\n }),\n ).then((rows) => {\n if (cancelled) return\n setHidden(new Set(rows.filter((r) => !r.show).map((r) => r.key)))\n setQueued(Object.fromEntries(rows.map((r) => [r.key, r.waiting])))\n setResolved(true)\n })\n return () => { cancelled = true }\n }, [actions, nonce])\n\n async function perform(action: ConnectorSyncAction) {\n setRunning(action.key)\n try {\n const outcome = await action.run()\n const message =\n (typeof outcome === 'string' ? outcome : outcome?.message) || `${action.label} — concluído`\n const status = typeof outcome === 'object' && outcome ? (outcome.status ?? 'success') : 'success'\n // A run that filed nothing answers 200 with a sentence. Reading only \"it\n // did not throw\" is what turned \"0 de 9 enviados\" into a green toast.\n if (status === 'error') toast.error(message)\n else if (status === 'partial') toast.warning(message)\n else toast.success(message)\n setNonce((n) => n + 1)\n onRan?.()\n } catch (error: any) {\n toast.error(error?.message ?? `${action.label} não foi concluído`)\n // Still reload: a failed run is a row, and the row explains why.\n setNonce((n) => n + 1)\n onRan?.()\n } finally {\n setRunning(null)\n }\n }\n\n const visible = actions.filter((a) => !hidden.has(a.key))\n\n if (open?.Component) {\n const Screen = open.Component\n return <Screen onClose={() => setOpen(null)} onRan={onRan} />\n }\n\n if (!resolved || visible.length === 0) return null\n\n function start(action: ConnectorSyncAction) {\n if (action.Component) { setOpen(action); return }\n if (action.confirm) { setPending(action); return }\n void perform(action)\n }\n\n // At most one primary; a connector that declares none gets its first promoted.\n const primary = visible.find((a) => a.primary) ?? visible[0]\n const rest = visible.filter((a) => a !== primary)\n\n return (\n <div className=\"space-y-3\">\n <ActionRow\n action={primary}\n busy={running === primary.key}\n blocked={running !== null}\n pending={queued[primary.key] ?? null}\n onStart={start}\n emphasis\n />\n\n {rest.length > 0 && (\n <div className=\"overflow-hidden rounded-lg border border-border\">\n <Button\n variant=\"bare\"\n size=\"bare\"\n type=\"button\"\n onClick={() => setExpanded(!expanded)}\n className=\"flex w-full items-center gap-2 px-3 py-2 text-left transition-colors hover:bg-muted/40 justify-start whitespace-normal text-[length:inherit] font-normal rounded-none\"\n aria-expanded={expanded}\n >\n <ChevronRight className={`h-3.5 w-3.5 shrink-0 text-muted-foreground transition-transform ${expanded ? 'rotate-90' : ''}`} />\n <span className=\"text-xs font-medium\">Outras ações</span>\n <span className=\"ml-auto text-[11px] text-muted-foreground\">{rest.length}</span>\n </Button>\n\n {expanded && (\n <ul className=\"divide-y divide-border border-t border-border\">\n {rest.map((action) => (\n <li key={action.key} className=\"px-3 py-2.5\">\n <ActionRow\n action={action}\n busy={running === action.key}\n blocked={running !== null}\n pending={queued[action.key] ?? null}\n onStart={start}\n />\n </li>\n ))}\n </ul>\n )}\n </div>\n )}\n\n {pending?.confirm && (\n <ConfirmDialog\n open\n title={pending.confirm.title}\n description={pending.confirm.body}\n confirmLabel={pending.confirm.cta}\n onCancel={() => setPending(null)}\n onConfirm={() => {\n const action = pending\n setPending(null)\n void perform(action)\n }}\n />\n )}\n </div>\n )\n}\n\n/**\n * One action: what it does, then the button that does it.\n *\n * The description sits WITH its action. Five buttons over five paragraphs made\n * the reader match one to the other by counting, and the arrows — the only thing\n * telling \"traz\" from \"manda\" — were the smallest mark on screen.\n */\nfunction ActionRow({\n action,\n busy,\n blocked,\n pending,\n onStart,\n emphasis = false,\n}: {\n action: ConnectorSyncAction\n busy: boolean\n blocked: boolean\n pending: number | null\n onStart(action: ConnectorSyncAction): void\n emphasis?: boolean\n}) {\n const inbound = action.direction === 'inbound'\n const Icon = inbound ? ArrowDownToLine : ArrowUpFromLine\n // Nothing left to send. The control is spent, not broken — pressing it would\n // open a run that files nothing, and the reader would have to read a history\n // to learn that.\n const done = pending === 0\n\n // The button carries the words; saying the label twice read as noise.\n if (emphasis) {\n return (\n <div className=\"space-y-1.5\">\n <Button size=\"sm\" disabled={blocked} onClick={() => onStart(action)}>\n {busy ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <Icon className=\"h-3.5 w-3.5\" />}\n {busy ? 'Sincronizando…' : action.label}\n </Button>\n {action.description && (\n <p className=\"text-xs leading-relaxed text-muted-foreground\">{action.description}</p>\n )}\n </div>\n )\n }\n\n return (\n <div className=\"flex items-start gap-3\">\n <div className=\"min-w-0 flex-1\">\n <p className=\"flex items-center gap-1.5 text-sm font-medium\">\n {done ? (\n <CheckCircle2 className=\"h-3.5 w-3.5 shrink-0 text-success\" aria-hidden />\n ) : (\n <Icon\n className={`h-3.5 w-3.5 shrink-0 ${inbound ? 'text-info' : 'text-muted-foreground'}`}\n aria-hidden\n />\n )}\n <span className={done ? 'text-muted-foreground' : undefined}>{action.label}</span>\n {/* An arrow is not a fact anyone can read out loud. */}\n <span className=\"sr-only\">{inbound ? '(traz dados para cá)' : '(envia dados daqui)'}</span>\n {pending !== null && pending > 0 && (\n <span className=\"rounded-full bg-muted px-1.5 text-[11px] tabular-nums text-muted-foreground\">\n {pending}\n </span>\n )}\n </p>\n <p className=\"mt-0.5 text-xs leading-relaxed text-muted-foreground\">\n {done ? 'Tudo enviado — nada pendente.' : action.description}\n </p>\n </div>\n <Button\n variant=\"outline\"\n size=\"sm\"\n className=\"shrink-0\"\n disabled={blocked || done}\n onClick={() => onStart(action)}\n >\n {busy && <Loader2 className=\"h-3.5 w-3.5 animate-spin\" />}\n {busy ? 'Executando…' : done ? 'Em dia' : inbound ? 'Trazer' : 'Enviar'}\n </Button>\n </div>\n )\n}\n","/**\n * When something happened, in the reader's language.\n *\n * Both formatters used to be private to ConnectorDetail, and the relative one\n * had \"agora\" and \"há 2 h\" written into it — correct for the only locale that\n * had a reader, and a lie in the en bundle next to it. The translator is passed\n * in rather than hooked so the same functions work inside a `.map` and inside a\n * test with no provider mounted.\n */\n\n/** Same shape core's `useTranslation` hands back. */\nexport type Translate = (key: string, params?: Record<string, string | number>) => string\n\nexport function formatDate(iso: string): string {\n return new Date(iso).toLocaleDateString(undefined, { day: '2-digit', month: 'short', year: 'numeric' })\n}\n\n/** Full stamp, for the title of something showing a relative time. */\nexport function formatDateTime(iso: string): string {\n return new Date(iso).toLocaleString()\n}\n\n/**\n * \"há 2 h\" up to a month, and a date after that.\n *\n * A month-old run is answered with the day it happened: nobody counts back 47\n * days, and \"is it working?\" stopped being the question long before then.\n */\nexport function formatRelative(iso: string, t: Translate): string {\n const diff = Date.now() - new Date(iso).getTime()\n const minutes = Math.round(diff / 60_000)\n if (minutes < 1) return t('connectors.when.now')\n if (minutes < 60) return t('connectors.when.minutes', { count: minutes })\n const hours = Math.round(minutes / 60)\n if (hours < 24) return t('connectors.when.hours', { count: hours })\n const days = Math.round(hours / 24)\n if (days < 30) return t('connectors.when.days', { count: days })\n return formatDate(iso)\n}\n","import React from 'react'\nimport {\n AlertTriangle,\n ArrowDownToLine,\n ArrowUpFromLine,\n CheckCircle2,\n ChevronRight,\n Loader2,\n XCircle,\n} from 'lucide-react'\nimport type { SyncRun } from '@fayz-ai/core'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { ConnectorSyncActions } from './ConnectorSyncActions'\nimport { formatDateTime, formatRelative, type Translate } from './when'\nimport type { UnifiedConnector } from './model'\n\n/**\n * One history, for every connector that has one.\n *\n * Google Calendar hand-rolled a run list. Bling hand-rolled a second. RankLayer\n * a third, open banking a fourth — four renderings of the same four columns of\n * `sync_runs`, each with its own empty state, its own idea of what a failure\n * looks like, and none of them reachable by a connector written next week. What\n * differs between them was never the view: it was where the rows come from, and\n * that is one declaration (`ConnectorDefinition.listRuns`).\n *\n * The reader asks two things here and they want different shapes. *\"Deu certo?\"*\n * is answered before this component renders — by the dot on the tab that brought\n * them, so it is answerable from the screen they landed on without a second\n * status line anywhere. *\"O que aconteceu no dia 3?\"* is the list below, newest\n * first, one row per run, with the run's own sentence on it.\n */\n\nexport interface ConnectorRunsState {\n runs: SyncRun[]\n loading: boolean\n reload: () => void\n /** The newest run failed — what the tab's warning dot is for. */\n failing: boolean\n}\n\n/**\n * Load a connector's history.\n *\n * Lifted out of the view because the tab STRIP needs the answer too: a warning\n * dot that only appeared once you opened the tab would be a warning nobody sees.\n * One load feeds both.\n */\nexport function useConnectorRuns(connector: UnifiedConnector): ConnectorRunsState {\n const listRuns = connector.definition?.listRuns\n const [runs, setRuns] = React.useState<SyncRun[]>([])\n const [loading, setLoading] = React.useState(!!listRuns)\n const [nonce, setNonce] = React.useState(0)\n\n React.useEffect(() => {\n if (!listRuns) {\n setRuns([])\n setLoading(false)\n return\n }\n let cancelled = false\n setLoading(true)\n void listRuns({ limit: 20 })\n .then((rows) => { if (!cancelled) setRuns(rows) })\n // An unreadable history is an empty one. It is never the reason a\n // connector's screen fails to render.\n .catch(() => { if (!cancelled) setRuns([]) })\n .finally(() => { if (!cancelled) setLoading(false) })\n return () => { cancelled = true }\n }, [connector.id, listRuns, nonce])\n\n return {\n runs,\n loading,\n reload: React.useCallback(() => setNonce((n) => n + 1), []),\n failing: isFailing(runs),\n }\n}\n\n/**\n * \"Something is wrong right now\" — the newest run, and only the newest.\n *\n * A connector that failed on Tuesday and has run cleanly since is not failing;\n * a dot that counted any failure in the last twenty would be permanent for every\n * connector that has ever had a bad night, which is a dot nobody reads.\n */\nexport function isFailing(runs: SyncRun[]): boolean {\n return runs[0]?.status === 'error'\n}\n\n/** Whether this connector has a Sincronizações tab — history, actions, or both. */\nexport function hasRunHistory(connector: UnifiedConnector): boolean {\n const def = connector.definition\n return !!def && (!!def.listRuns || !!def.RunActions || !!def.syncActions?.length)\n}\n\nconst RUN_ICON: Record<SyncRun['status'], { Icon: typeof CheckCircle2; className: string }> = {\n success: { Icon: CheckCircle2, className: 'text-success' },\n partial: { Icon: AlertTriangle, className: 'text-warning' },\n error: { Icon: XCircle, className: 'text-destructive' },\n running: { Icon: Loader2, className: 'text-muted-foreground animate-spin' },\n}\n\n/** The whole Sincronizações tab: what you can make it do, then what it has done. */\nexport function ConnectorRuns({\n connector,\n state,\n}: {\n connector: UnifiedConnector\n state: ConnectorRunsState\n}) {\n const { t } = useTranslation()\n const def = connector.definition\n const { runs, loading, reload } = state\n const firstLoad = def?.firstLoad\n const backfilling = !!firstLoad && runs.some((r) => r.status === 'running')\n\n return (\n <div className=\"space-y-4\">\n {/* The import wizard, \"sincronizar agora\" — the acts that put a row in the\n list below. They were rendered beside a settings form, which is what\n made them read as configuration nobody had finished filling in.\n Declared actions first; both seams render so a connector can move one\n action at a time. */}\n {def?.syncActions?.length ? <ConnectorSyncActions actions={def.syncActions} onRan={reload} /> : null}\n {def?.RunActions && <def.RunActions onRan={reload} />}\n\n {/* A first load is two runs by design (a sample, then a backfill), and the\n long one is invisible without this. Driven by the declaration, so it\n says nothing for a connector that does not do it. */}\n {backfilling && (\n <p className=\"flex items-start gap-2 text-xs text-muted-foreground\">\n <Loader2 className=\"mt-px h-3.5 w-3.5 shrink-0 animate-spin\" />\n <span>{t('connectors.runs.backfilling')}</span>\n </p>\n )}\n\n {loading ? (\n <p className=\"flex justify-center py-6\">\n <Loader2 className=\"h-4 w-4 animate-spin text-muted-foreground\" />\n </p>\n ) : runs.length === 0 ? (\n <div className=\"space-y-1.5 rounded-lg border border-dashed border-border p-3\">\n <p className=\"text-xs leading-relaxed text-muted-foreground\">{t('connectors.runs.empty')}</p>\n {firstLoad && (\n <p className=\"text-xs leading-relaxed text-muted-foreground\">\n {t('connectors.runs.emptyFirstLoad', { count: firstLoad.sampleSize })}\n </p>\n )}\n </div>\n ) : (\n <ul className=\"divide-y divide-border overflow-hidden rounded-lg border border-border\">\n {runs.map((run, index) => (\n <RunRow\n key={run.id ?? `${run.startedAt}-${index}`}\n run={run}\n providerName={connector.name}\n // Only under the newest failure: repeating \"nada foi perdido\"\n // against every red row turns the one useful sentence into wallpaper.\n explainFailure={index === 0}\n />\n ))}\n </ul>\n )}\n </div>\n )\n}\n\n/**\n * One run.\n *\n * A failed run used to be a red icon with the error in a `title` — invisible on\n * a phone, invisible to a screen reader, and useless to the person deciding\n * whether to call somebody. The message is text now, wrapped, in the row.\n */\nfunction RunRow({\n run,\n providerName,\n explainFailure,\n}: {\n run: SyncRun\n providerName: string\n explainFailure: boolean\n}) {\n const { t } = useTranslation()\n const { Icon, className } = RUN_ICON[run.status] ?? RUN_ICON.success\n const inbound = run.direction === 'inbound'\n const DirectionIcon = inbound ? ArrowDownToLine : ArrowUpFromLine\n const failed = run.status === 'error'\n\n return (\n <li className=\"px-3 py-2.5\">\n <div className=\"flex items-center gap-2\">\n <Icon className={`h-3.5 w-3.5 shrink-0 ${className}`} aria-hidden />\n {/* The status in words as well as in colour — a red circle is not a\n fact anyone can read out loud. */}\n <span className=\"sr-only\">{t(`connectors.runs.status.${run.status}`)}</span>\n <span\n className=\"text-xs tabular-nums text-muted-foreground\"\n title={run.startedAt ? formatDateTime(run.startedAt) : undefined}\n >\n {run.startedAt ? formatRelative(run.startedAt, t) : '—'}\n </span>\n <span className=\"text-xs text-muted-foreground/70\">· {t(`connectors.trigger.${run.triggerKind}`)}</span>\n <span className=\"ml-auto flex shrink-0 items-center gap-1 text-[11px] text-muted-foreground\">\n <DirectionIcon className=\"h-3 w-3\" aria-hidden />\n {t(inbound ? 'connectors.runs.from' : 'connectors.runs.to', { name: providerName })}\n </span>\n </div>\n\n {/* What the run has to SAY comes first: `message` exists precisely so a\n successful run can report something a counter cannot. */}\n <p className=\"mt-0.5 pl-5 text-xs leading-relaxed text-foreground\">{runLine(run, t)}</p>\n\n {failed && run.error && <RunFailure run={run} />}\n {failed && explainFailure && (\n <p className=\"mt-0.5 pl-5 text-[11px] leading-relaxed text-muted-foreground\">\n {t('connectors.runs.failedHint')}\n </p>\n )}\n </li>\n )\n}\n\n/**\n * Why a run failed, and — one click below it — what the call itself did.\n *\n * The reason was three lines of saturated red under every failed row, and a\n * connector that fails on a schedule paints the whole history that colour: the\n * merchant reads a wall of alarm and cannot tell the one failure that matters\n * from the same failure repeated twelve times. So the reason keeps its words but\n * loses its shouting — two lines, muted, in a soft strip — and the technical half\n * (which resource, when, how long, which attempt, which run) goes behind the\n * disclosure, where the person who is actually going to fix it can reach it.\n *\n * `<details>` for the same reasons ConnectorDisclosure gives: it opens on click\n * and on Enter, it needs no state, and its contents are in the DOM whether open\n * or shut, so find-in-page and a screen reader still reach the error.\n */\nfunction RunFailure({ run }: { run: SyncRun }) {\n const { t } = useTranslation()\n const facts = callFacts(run, t)\n const extra = extraStats(run)\n\n return (\n <details className=\"group mt-1 ml-5 rounded-md border border-border bg-muted/40\">\n <summary className=\"flex cursor-pointer list-none items-start gap-1.5 px-2 py-1.5 text-xs leading-relaxed text-muted-foreground hover:text-foreground\">\n <XCircle className=\"mt-px h-3.5 w-3.5 shrink-0 text-destructive/70\" aria-hidden />\n {/* Clamped shut, whole shown open: a 300-character platform error is\n worth reading once, not every time you scroll past it. */}\n <span className=\"min-w-0 flex-1 line-clamp-2 group-open:line-clamp-none\">{run.error}</span>\n <ChevronRight\n className=\"mt-px h-3.5 w-3.5 shrink-0 transition-transform group-open:rotate-90\"\n aria-hidden\n />\n <span className=\"sr-only\">{t('connectors.runs.seeDetails')}</span>\n </summary>\n {facts.length > 0 && (\n <dl className=\"grid grid-cols-[auto_1fr] gap-x-3 gap-y-0.5 border-t border-border px-2 py-2 text-[11px] leading-relaxed\">\n {facts.map(([label, value]) => (\n <React.Fragment key={label}>\n <dt className=\"text-muted-foreground\">{label}</dt>\n <dd className=\"min-w-0 break-words font-mono text-foreground/80\">{value}</dd>\n </React.Fragment>\n ))}\n </dl>\n )}\n {/* Whatever the connector chose to record and this view cannot name. Shown\n raw rather than dropped: it is the only place a per-record failure list\n survives, and guessing at its shape here would make it a connector's\n field again. */}\n {extra && (\n <div className=\"border-t border-border px-2 py-2\">\n <p className=\"text-[11px] text-muted-foreground\">{t('connectors.runs.detail.raw')}</p>\n <pre className=\"mt-1 max-h-40 overflow-auto whitespace-pre-wrap break-words text-[11px] leading-relaxed text-foreground/70\">\n {extra}\n </pre>\n </div>\n )}\n </details>\n )\n}\n\n/** The call, in the fields every connector's run already carries. */\nfunction callFacts(run: SyncRun, t: Translate): Array<[string, string]> {\n const facts: Array<[string, string]> = []\n if (run.stream) facts.push([t('connectors.runs.detail.stream'), run.stream])\n if (run.startedAt) facts.push([t('connectors.runs.detail.started'), formatDateTime(run.startedAt)])\n if (run.finishedAt) facts.push([t('connectors.runs.detail.finished'), formatDateTime(run.finishedAt)])\n const took = elapsed(run, t)\n if (took) facts.push([t('connectors.runs.detail.duration'), took])\n // Which attempt of a backing-off schedule this was — the difference between\n // \"it broke once\" and \"it has been broken for six hours\".\n const attempt = run.stats?.attempt\n if (typeof attempt === 'number') facts.push([t('connectors.runs.detail.attempt'), String(attempt)])\n if (run.id) facts.push([t('connectors.runs.detail.runId'), run.id])\n return facts\n}\n\n/** How long the call took, when both ends of it are known. */\nfunction elapsed(run: SyncRun, t: Translate): string | null {\n if (!run.startedAt || !run.finishedAt) return null\n const ms = new Date(run.finishedAt).getTime() - new Date(run.startedAt).getTime()\n if (!Number.isFinite(ms) || ms < 0) return null\n const seconds = Math.round(ms / 1000)\n if (seconds < 90) return t('connectors.runs.detail.seconds', { count: seconds })\n return t('connectors.runs.detail.minutes', { count: Math.round(seconds / 60) })\n}\n\n/** Everything in `stats` this view does not already say in words. */\nfunction extraStats(run: SyncRun): string | null {\n const stats = run.stats ?? {}\n const rest = Object.fromEntries(Object.entries(stats).filter(([key]) => key !== 'attempt'))\n if (Object.keys(rest).length === 0) return null\n try {\n return JSON.stringify(rest, null, 2)\n } catch {\n return null\n }\n}\n\n/** What a run did, in one line: its own sentence, or its counters, or neither. */\nfunction runLine(run: SyncRun, t: Translate): string {\n if (run.message) return run.message\n const fetched = run.fetched ?? 0\n const written = run.written ?? 0\n if (fetched > 0 || written > 0) return t('connectors.runs.counts', { written, fetched })\n if (run.status === 'running') return t('connectors.runs.status.running')\n // A run that moved nothing is the normal answer to \"anything new?\" — saying so\n // beats an empty line the reader has to interpret.\n return t('connectors.runs.nothingToDo')\n}\n","import React from 'react'\nimport { Button } from '@fayz-ai/ui'\nimport { Loader2, Save } from 'lucide-react'\nimport { connectorSettings, isSettingSet, missingRequiredSettings } from '@fayz-ai/core'\nimport type { ConnectorSetting, ConnectorSettingValue } from '@fayz-ai/core'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { toast } from '../notifications/ToastProvider'\nimport { MultiSelectRow, SelectRow, SettingsGroup, TextRow, ToggleRow } from '../../plugins/SettingsGroup'\nimport type { UnifiedConnector } from './model'\n\n/**\n * How a live integration behaves — the second half of the split.\n *\n * It renders through the same rows a plugin's own Settings tab uses\n * (`SettingsGroup` + `ToggleRow`/`SelectRow`, plus the two this case needed),\n * because the founder's ask was literally that: *assim como nosso generic plugin\n * > Settings carrega os settings no menu de forma dinâmica*. Those rows are\n * presentational and hand-composed today; a connector cannot hand-write React\n * from a published package that the host app renders, so what is declarative\n * here is the SCHEMA — `ConnectorDefinition.settings` — and this is the one\n * renderer for it. Not a third settings system: the same components, driven by a\n * declaration instead of by JSX.\n *\n * It appears only once the connection exists. That is the whole defect being\n * fixed — a merchant could not connect AppMax without first deciding which\n * payment methods they accept.\n */\nexport function ConnectorSettingsPanel({\n connector,\n onSaved,\n bare,\n}: {\n connector: UnifiedConnector\n onSaved?: () => void\n /** Drop the group heading: the surface hosting it already says \"Configurações\". */\n bare?: boolean\n}) {\n const { t } = useTranslation()\n const def = connector.definition\n const settings = def ? connectorSettings(def) : []\n\n // Seeded from the DECLARATION and refined by what is stored. The form's shape\n // is known before its contents are, and a spinner where a settings screen goes\n // reads as \"this integration has no settings\" — the opposite of the truth. The\n // controls are inert until the stored values land, so nothing can be saved\n // over a value that had not arrived yet.\n const [values, setValues] = React.useState<Record<string, ConnectorSettingValue>>(() =>\n initialValues(settings, {}),\n )\n const [loaded, setLoaded] = React.useState(false)\n const [saving, setSaving] = React.useState(false)\n const [dirty, setDirty] = React.useState(false)\n\n React.useEffect(() => {\n if (settings.length === 0 || !def?.getSettings) return\n let cancelled = false\n setLoaded(false)\n void def\n .getSettings()\n .catch(() => ({}) as Record<string, unknown>)\n .then((stored) => {\n if (cancelled) return\n setValues(initialValues(settings, stored))\n setDirty(false)\n setLoaded(true)\n })\n return () => {\n cancelled = true\n }\n }, [connector.id, settings.length])\n\n if (settings.length === 0 || !def?.saveSettings) return null\n\n const invalid = settings.filter((s) => !matchesPattern(s, values[s.key]))\n const missing = missingRequiredSettings(settings, values)\n\n function set(key: string, value: ConnectorSettingValue) {\n setValues((current) => ({ ...current, [key]: value }))\n setDirty(true)\n }\n\n async function save() {\n setSaving(true)\n try {\n await def!.saveSettings!(values)\n setDirty(false)\n toast.success(t('connectors.settings.saved'))\n onSaved?.()\n } catch (e: any) {\n toast.error(e?.message ?? t('common.error'))\n } finally {\n setSaving(false)\n }\n }\n\n return (\n <div className=\"space-y-2\">\n <SettingsGroup\n title={bare ? undefined : t('connectors.settings.title')}\n description={bare ? undefined : t('connectors.settings.subtitle')}\n >\n {settings.map((setting) => (\n <SettingRow\n key={setting.key}\n setting={setting}\n value={values[setting.key]}\n disabled={!loaded}\n onChange={set}\n />\n ))}\n </SettingsGroup>\n {/* Just the button. What is still missing is said once, by the status line\n above the tabs — repeating it beside Save made a two-field form read\n like a form with an error in it. */}\n <Button size=\"sm\" disabled={saving || !loaded || !dirty || invalid.length > 0} onClick={() => void save()}>\n {saving ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <Save className=\"h-3.5 w-3.5\" />}\n {t('connectors.settings.save')}\n </Button>\n </div>\n )\n}\n\nfunction SettingRow({\n setting,\n value,\n disabled,\n onChange,\n}: {\n setting: ConnectorSetting\n value: ConnectorSettingValue | undefined\n disabled?: boolean\n onChange: (key: string, value: ConnectorSettingValue) => void\n}) {\n const { t } = useTranslation()\n // Required-to-operate is said in the description rather than with an asterisk:\n // an asterisk on a screen you reached AFTER connecting reads as \"you cannot\n // leave\", which is exactly the coercion this split removed.\n const description = [setting.description, setting.requiredToOperate ? t('connectors.settings.required') : null]\n .filter(Boolean)\n .join(' ')\n\n switch (setting.type) {\n case 'toggle':\n return (\n <ToggleRow\n label={setting.label}\n description={description || undefined}\n checked={value === true}\n disabled={disabled}\n onChange={(next) => onChange(setting.key, next)}\n />\n )\n case 'select':\n return (\n <SelectRow\n label={setting.label}\n description={description || undefined}\n value={typeof value === 'string' ? value : ''}\n options={setting.options ?? []}\n disabled={disabled}\n onChange={(next) => onChange(setting.key, next)}\n />\n )\n case 'multi-select':\n return (\n <MultiSelectRow\n label={setting.label}\n description={description || undefined}\n value={Array.isArray(value) ? value : []}\n options={setting.options ?? []}\n disabled={disabled}\n onChange={(next) => onChange(setting.key, next)}\n />\n )\n default: {\n const text = typeof value === 'string' ? value : ''\n const bad = !matchesPattern(setting, text)\n return (\n <TextRow\n label={setting.label}\n description={description || undefined}\n value={text}\n placeholder={setting.placeholder}\n hint={setting.patternHint}\n invalid={bad}\n disabled={disabled}\n onChange={(next) => onChange(setting.key, next)}\n />\n )\n }\n }\n}\n\n/** Empty passes: \"not filled in yet\" is `requiredToOperate`'s business, not the pattern's. */\nexport function matchesPattern(setting: ConnectorSetting, value: unknown): boolean {\n if (!setting.pattern || setting.type !== 'text') return true\n if (!isSettingSet(value)) return true\n try {\n return new RegExp(setting.pattern).test(String(value).trim())\n } catch {\n return true\n }\n}\n\n/** Stored value, else the declared default, else the type's empty. */\nfunction initialValues(\n settings: ConnectorSetting[],\n stored: Record<string, unknown>,\n): Record<string, ConnectorSettingValue> {\n const out: Record<string, ConnectorSettingValue> = {}\n for (const setting of settings) {\n const value = stored[setting.key]\n if (isSettingSet(value) || typeof value === 'boolean') {\n out[setting.key] = value as ConnectorSettingValue\n } else if (setting.defaultValue !== undefined) {\n out[setting.key] = setting.defaultValue\n } else {\n out[setting.key] = setting.type === 'multi-select' ? [] : setting.type === 'toggle' ? false : ''\n }\n }\n return out\n}\n","import React from 'react'\nimport {\n SheetBody,\n Button,\n Tabs,\n TabsList,\n TabsTrigger,\n TabsContent,\n Input,\n} from '@fayz-ai/ui'\nimport { Sparkles, RefreshCw, Plug, Loader2, CheckCircle2, Power, ExternalLink, Info, AlertTriangle } from 'lucide-react'\nimport { RightRailPage } from '../RightRailPage'\nimport { connectorSettings, type ConnectorDefinition, type ConnectorPlane } from '@fayz-ai/core'\nimport { ConnectorOAuthStarterMissingError, getConnectorCredentialSink } from '@fayz-ai/sdk'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { useTenantOptional } from '../../org/context'\nimport { toast } from '../notifications/ToastProvider'\nimport { ConnectorMark } from './ConnectorMark'\nimport { StateChip } from './ConnectorRow'\nimport {\n CredentialSinkMissingError,\n isSecretField,\n needsCredentialSink,\n probeConnection,\n submitConnection,\n} from './credentials'\nimport { ConnectorPermissions } from './ConnectorPermissions'\nimport { ConnectorRuns, hasRunHistory, useConnectorRuns } from './ConnectorRuns'\nimport { ConnectorSettingsPanel } from './ConnectorSettings'\nimport { isLive, type UnifiedConnector } from './model'\nimport { formatDate, formatRelative } from './when'\n\n/**\n * A connector has two lives, and this file is the seam between them.\n *\n * INSTALLING is a journey with an end: what it does, how it will be resolved,\n * connect the account. Three steps, and the third one FINISHES — the accounts\n * are linked and the install is over. Steps 1 and 2 come before 3 deliberately;\n * asking for a credential before the person knows what the thing will be allowed\n * to do is how consent screens become a formality.\n *\n * OPERATING has no end. Which postcode the parcels leave from, which payment\n * methods the gateway may offer, which Google calendars map to which\n * professional — none of that is installation. It changes on a Tuesday in\n * March, long after the account was connected, and it is not a step anyone\n * \"completes\". So it is not a fourth step: it is the connector's Settings tab,\n * reached the same way a plugin's settings are, and it stays reachable forever.\n *\n * Operating asks THREE questions, not one, which is why there are three tabs.\n * *O que é isso e o que ele alcança?* — Visão geral. *O que ele fez, e posso\n * mandar ele fazer agora?* — Sincronizações. *O que eu posso mudar?* —\n * Configurações. The middle one is the founder's ask (*um lugar pra ver\n * histórico de últimas syncs*) and it is a tab rather than a block of the\n * overview because a list of twenty rows is not glanceable and an import wizard\n * is not a fact about the connection. What lands on the tab strip instead is one\n * dot: the newest run failed.\n *\n * Collapsing the two is what produced the defect this split fixes — a merchant\n * who clicked Conectar, was asked nothing, and landed on \"Conectado — falta\n * configurar\" with no door out of it. Connecting now concludes as connecting,\n * and what is left to configure is a tab with the thing to configure in it.\n *\n * It shows in the shell's right column, and falls back to a sheet where there\n * is no column — see RightRailPage.\n */\n\nfunction Step({\n n,\n title,\n children,\n muted,\n}: {\n n: number\n title: string\n children: React.ReactNode\n muted?: boolean\n}) {\n return (\n <section className={muted ? 'opacity-60' : undefined}>\n <div className=\"flex items-center gap-2\">\n <span className=\"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-[11px] font-semibold text-muted-foreground\">\n {n}\n </span>\n <h3 className=\"text-sm font-semibold text-foreground\">{title}</h3>\n </div>\n <div className=\"mt-2 pl-7\">{children}</div>\n </section>\n )\n}\n\n/**\n * The plane choice.\n *\n * Agentic is preselected whenever the connector supports it — that is the house\n * rule, and the card says why rather than leaving it as a silent default. When\n * a connector supports only one plane, the card still shows the reason: \"esse\n * provedor precisa de espelho\" is information, an invisible constraint is not.\n */\nfunction PlanePicker({\n planes,\n value,\n onChange,\n}: {\n planes: ConnectorPlane[]\n value?: ConnectorPlane\n onChange?: (plane: ConnectorPlane) => void\n}) {\n const { t } = useTranslation()\n if (planes.length === 0) {\n return (\n <p className=\"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground\">\n {t('connectors.plane.undecided')}\n </p>\n )\n }\n return (\n <div className=\"grid gap-2 sm:grid-cols-2\">\n {planes.map((plane) => {\n const Icon = plane === 'agentic' ? Sparkles : RefreshCw\n const selected = value === plane\n const only = planes.length === 1\n return (\n <Button\n variant=\"bare\"\n size=\"bare\"\n key={plane}\n type=\"button\"\n disabled={only}\n onClick={() => onChange?.(plane)}\n className={\n 'rounded-lg border p-3 text-left transition-colors inline-block whitespace-normal text-[length:inherit] font-normal' +\n (selected ? 'border-primary bg-primary/5' : 'border-border hover:bg-muted/40') +\n (only ? ' cursor-default' : '')\n }\n >\n <span className=\"flex items-center gap-1.5 text-sm font-medium text-foreground\">\n <Icon className=\"h-3.5 w-3.5\" />\n {t(`connectors.plane.${plane}`)}\n {plane === 'agentic' && !only && (\n <span className=\"rounded-full bg-primary/10 px-1.5 py-px text-[10px] font-normal text-primary\">\n {t('connectors.plane.recommended')}\n </span>\n )}\n </span>\n <span className=\"mt-1 block text-xs text-muted-foreground\">\n {t(`connectors.plane.${plane}.desc`)}\n </span>\n </Button>\n )\n })}\n </div>\n )\n}\n\n/**\n * Who this is, and how it stands — the same badge the list uses.\n *\n * The header used to carry a state chip AND a direction badge AND a plane\n * badge, with the state repeated in a line under it and a third time as a dot\n * on the Settings tab. One fact, four renderings, in a 380px column. Now the\n * state sits once, right of the name, in the component the list rows use; how\n * it resolves is said in words on the tab where someone is reading about it.\n */\nexport function ConnectorHeading({ connector }: { connector: UnifiedConnector }) {\n return (\n <div className=\"flex items-start gap-3\">\n <ConnectorMark connector={connector} />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex items-start justify-between gap-2\">\n <p className=\"min-w-0 font-semibold leading-tight text-foreground\">{connector.name}</p>\n <StateChip state={connector.state} className=\"shrink-0\" />\n </div>\n {connector.description && (\n <p className=\"mt-1 text-xs leading-relaxed text-muted-foreground\">{connector.description}</p>\n )}\n </div>\n </div>\n )\n}\n\n/** A labelled block. The one rhythm both tabs are built out of. */\nfunction Section({ title, children }: { title: string; children: React.ReactNode }) {\n return (\n <section className=\"space-y-1.5\">\n <h4 className=\"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/60\">{title}</h4>\n {children}\n </section>\n )\n}\n\n/** Whether this connector has anything to operate — the Settings tab's reason to exist. */\nexport function hasOperatingSettings(connector: UnifiedConnector): boolean {\n const def = connector.definition\n if (!def) return false\n // Campos de credencial contam. Sem isto, um conector que só pede uma chave\n // não tem aba nenhuma depois de conectado — e aí não existe lugar no produto\n // onde trocar a chave, o que é onde este parágrafo começou: a Vindi passou a\n // pedir mais três credenciais e não havia onde digitá-las.\n return connectorSettings(def).length > 0\n || (def.fields ?? []).length > 0\n || !!def.ExtraPanel\n || !!def.setPlane\n}\n\n/**\n * What is missing, in the words the settings screen uses.\n *\n * `missingSettings` carries keys, and a key is what the code calls the thing.\n * Naming them turns \"falta configurar\" — a label the person already read on the\n * tab next to it — into the one sentence that tells them what to go and do.\n */\nexport function missingSettingLabels(connector: UnifiedConnector): string[] {\n const def = connector.definition\n if (!def || !connector.missingSettings?.length) return []\n const declared = new Map(connectorSettings(def).map((s) => [s.key, s.label]))\n return connector.missingSettings.map((key) => declared.get(key) ?? key)\n}\n\n/** The provider's own documentation, in the one place both lives can reach it. */\nfunction DocsLink({ connector }: { connector: UnifiedConnector }) {\n const { t } = useTranslation()\n if (!connector.docsUrl) return null\n return (\n <a\n href={connector.docsUrl}\n target=\"_blank\"\n rel=\"noreferrer\"\n className=\"inline-flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground\"\n >\n <ExternalLink className=\"h-3 w-3\" /> {t('connectors.docs')}\n </a>\n )\n}\n\n/** Installing, or operating. Which one is not a mode anyone picks — it is whether the accounts are linked. */\nexport function ConnectorJourney({\n connector,\n onChanged,\n onRevoke,\n}: {\n connector: UnifiedConnector\n /** Something was connected/disconnected — the list should reload. */\n onChanged?: () => void\n /** Revoking an inbound grant goes through the screen that owns the API. */\n onRevoke?: (connector: UnifiedConnector) => Promise<void> | void\n}) {\n return isLive(connector.state) ? (\n <ConnectorHome connector={connector} onChanged={onChanged} onRevoke={onRevoke} />\n ) : (\n <ConnectorInstall connector={connector} onChanged={onChanged} />\n )\n}\n\n/**\n * The install, and only the install.\n *\n * Three steps that end. Nothing here outlives the connection being made — the\n * moment it is, this component is replaced by `ConnectorHome` and the numbers\n * disappear, because a numbered list you can never finish is the thing that made\n * \"Conectado — falta configurar\" read as a failure.\n */\nfunction ConnectorInstall({\n connector,\n onChanged,\n}: {\n connector: UnifiedConnector\n onChanged?: () => void\n}) {\n const { t } = useTranslation()\n const def = connector.definition\n const [plane, setPlane] = React.useState<ConnectorPlane | undefined>(\n connector.planes.includes('agentic') ? 'agentic' : connector.planes[0],\n )\n const [values, setValues] = React.useState<Record<string, string>>({})\n // Secrets live in a ref, never in state: state is what re-renders read, what\n // devtools show and what a future draft-restore would be tempted to persist.\n const secrets = React.useRef<Record<string, string>>({})\n const [busy, setBusy] = React.useState<'test' | 'save' | 'oauth' | null>(null)\n\n React.useEffect(() => {\n setValues({})\n secrets.current = {}\n setBusy(null)\n setPlane(connector.planes.includes('agentic') ? 'agentic' : connector.planes[0])\n }, [connector.id])\n\n const run = useRunner(setBusy, onChanged)\n\n return (\n <div className=\"space-y-6\">\n {/* 1 — what it can do, stated before anything is asked for */}\n <Step n={1} title={t('connectors.journey.what')}>\n <div className=\"space-y-2\">\n <Capabilities connector={connector} />\n {/* The consent view, and it is in step 1 rather than beside the\n credential form on purpose: the whole reason steps 1 and 2 come\n before step 3 is that nobody should be asked to authorize\n something before they have been told what it reaches. */}\n {/* Records, facts and calls in one panel — \"quando ele age\" was a\n second box listing the same event keys from the same declaration. */}\n <ConnectorPermissions connector={connector} />\n </div>\n </Step>\n\n {/* 2 — how it will be honoured */}\n <Step n={2} title={t('connectors.journey.how')}>\n <PlanePicker planes={connector.planes} value={plane} onChange={setPlane} />\n </Step>\n\n {/* 3 — link the account. The last step, and it finishes. */}\n <Step n={3} title={t('connectors.journey.connectAccount')}>\n {def ? (\n <ConnectPanel\n connector={connector}\n values={values}\n setValues={setValues}\n secrets={secrets}\n busy={busy}\n run={run}\n />\n ) : (\n <p className=\"text-xs text-muted-foreground\">{t('connectors.authorize.elsewhere')}</p>\n )}\n </Step>\n\n {/* Not a step. What comes AFTER the install is over, said once so nobody\n is surprised by a Settings tab appearing where step 4 used to be. */}\n <p className=\"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground\">\n {t(plane === 'agentic' ? 'connectors.after.willAgentic' : 'connectors.after.willSync')}\n {hasOperatingSettings(connector) ? ` ${t('connectors.after.settingsLater')}` : ''}\n </p>\n\n <DocsLink connector={connector} />\n </div>\n )\n}\n\ntype HomeTab = 'overview' | 'operate' | 'runs' | 'settings'\n\n/**\n * A live connector: what it is doing, and the knobs it left you.\n *\n * The tabs are the founder's ask in one sentence — *o restante das operações\n * devem ser feitas dentro de integrações > google_calendar > settings, não como\n * step 4 da instalação*. Visão geral is what the connection IS; Configurações is\n * what you may change about it, whenever, without touching the connection.\n *\n * A connection that authorized but cannot operate yet opens ON that tab rather\n * than announcing the problem and leaving the person to find the fix.\n */\nfunction ConnectorHome({\n connector,\n onChanged,\n onRevoke,\n}: {\n connector: UnifiedConnector\n onChanged?: () => void\n onRevoke?: (connector: UnifiedConnector) => Promise<void> | void\n}) {\n const { t } = useTranslation()\n const def = connector.definition\n const needsSetup = connector.state === 'needs_setup'\n const settingsAvailable = hasOperatingSettings(connector)\n const runsAvailable = hasRunHistory(connector)\n const [tab, setTab] = React.useState<HomeTab>(\n needsSetup && settingsAvailable ? 'settings' : 'overview',\n )\n const [busy, setBusy] = React.useState<'off' | 'plane' | 'test' | 'save' | 'oauth' | null>(null)\n const run = useRunner(setBusy, onChanged)\n // O mesmo estado que a instalação usa. Vive aqui porque a aba Configurações\n // passou a mostrar o mesmo formulário: um segredo se TROCA, e até agora o\n // único jeito de trocar um era desconectar e refazer a instalação inteira.\n const [values, setValues] = React.useState<Record<string, string>>({})\n const secrets = React.useRef<Record<string, string>>({})\n // Loaded here rather than inside the tab: the dot that says the last run\n // failed has to be visible from the tab someone lands on.\n const runs = useConnectorRuns(connector)\n\n // A connector that arrives already needing setup should still land on its\n // settings — switching connectors inside the drawer keeps this honest.\n React.useEffect(() => {\n setTab(needsSetup && settingsAvailable ? 'settings' : 'overview')\n setBusy(null)\n // Trocar de conector no drawer não pode deixar o que foi digitado para trás.\n setValues({})\n secrets.current = {}\n }, [connector.id])\n\n /**\n * What is missing, said where it is fixed.\n *\n * There is no status line above the tabs any more — the badge beside the name\n * carries the state. What a line can add that a badge cannot is WHICH setting\n * is missing, and that belongs on the settings tab, next to the field, not\n * above a tab strip the person then has to act on.\n */\n const missing = missingSettingLabels(connector)\n\n if (!def) {\n // An inbound grant — someone else reaching this organization. Nothing to\n // operate, so no tabs; the same skeleton otherwise, because a connection is\n // a connection and two of them should not look like two products.\n return (\n <div className=\"space-y-5\">\n {/* The badge upstairs says it is connected; this says since when and\n whether anyone has used it. */}\n <GrantFacts connector={connector} />\n <Section title={t('connectors.overview.reaches')}>\n <Capabilities connector={connector} />\n </Section>\n <div className=\"space-y-3 border-t border-border pt-3\">\n <DocsLink connector={connector} />\n <GrantRevoke connector={connector} onRevoke={onRevoke} />\n </div>\n </div>\n )\n }\n\n return (\n <div className=\"space-y-4\">\n <Tabs value={tab} onValueChange={(next) => setTab(next as HomeTab)}>\n <TabsList>\n <TabsTrigger value=\"overview\">{t('connectors.tab.overview')}</TabsTrigger>\n {def.OperatePanel && (\n <TabsTrigger value=\"operate\">{def.operateLabel ?? t('connectors.tab.operate')}</TabsTrigger>\n )}\n {runsAvailable && (\n <TabsTrigger value=\"runs\">\n {t('connectors.tab.runs')}\n {/* The whole \"deu certo?\" answer, from the screen they land on.\n Same dot the settings tab uses, because it means the same\n thing: there is something on this tab worth opening. */}\n {runs.failing && (\n <span className=\"ml-1.5 h-1.5 w-1.5 rounded-full bg-destructive\" aria-hidden />\n )}\n </TabsTrigger>\n )}\n {settingsAvailable && (\n <TabsTrigger value=\"settings\">\n {t('connectors.tab.settings')}\n {needsSetup && <span className=\"ml-1.5 h-1.5 w-1.5 rounded-full bg-warning\" aria-hidden />}\n </TabsTrigger>\n )}\n </TabsList>\n\n <TabsContent value=\"overview\" className=\"space-y-5 pt-4\">\n {/* What the connection reports about ITSELF. `issues` is the list when\n a connector has more than one thing to say, `detail` the single\n line when it has one — never both, and never rendered from the\n connector's own panel on the settings tab, which is where a health\n warning became something that looked like a form to fill in. */}\n <ConnectionReport connector={connector} />\n\n {/* The badges that used to sit in the header, as the sentence they\n always were: \"saída\" and \"Sob demanda\" are jargon on their own. */}\n <Section title={t('connectors.overview.resolves')}>\n <p className=\"text-xs leading-relaxed text-muted-foreground\">\n {t(`connectors.plane.${connector.activePlane ?? connector.planes[0] ?? 'sync'}.desc`)}\n </p>\n </Section>\n\n {/* Quando sincroniza. A cadência mora numa tabela, o gatilho de escrita\n num trigger e a execução manual num botão — o lojista não tem como\n montar essa frase, e é a primeira que ele quer. */}\n {def.howItSyncs && def.howItSyncs.length > 0 && (\n <Section title={t('connectors.overview.whenItSyncs')}>\n <ul className=\"space-y-1\">\n {def.howItSyncs.map((line, index) => (\n <li key={index} className=\"flex gap-1.5 text-xs leading-relaxed text-muted-foreground\">\n <span aria-hidden>·</span>\n <span>{line}</span>\n </li>\n ))}\n </ul>\n </Section>\n )}\n\n <Section title={t('connectors.overview.reaches')}>\n <Capabilities connector={connector} />\n </Section>\n\n {/* The same declaration step 1 showed before authorizing. What a\n connector may reach is not a fact that stops mattering once it is\n connected — it is the answer to \"what did I agree to?\". */}\n <ConnectorPermissions connector={connector} />\n\n {/* Everything that leads OUT of the connector, kept together at the\n bottom and away from anything someone taps by habit. */}\n <div className=\"space-y-3 border-t border-border pt-3\">\n <DocsLink connector={connector} />\n {def.disconnect && (\n <div className=\"space-y-1.5\">\n <Button\n variant=\"bare\"\n size=\"bare\"\n type=\"button\"\n disabled={busy === 'off'}\n onClick={() => run('off', () => def.disconnect!(), t('connectors.disconnect'))}\n className=\"flex items-center gap-1.5 text-xs text-destructive transition-colors hover:text-destructive/80 disabled:opacity-50 font-normal\"\n >\n {busy === 'off' ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <Power className=\"h-3.5 w-3.5\" />}\n {t('connectors.disconnect')}\n </Button>\n {/* \"Congela o espelho, não apaga nada\" is the answer to the only\n question this button ever raises, and it is the connector's\n to give — a shopkeeper who cannot tell a frozen mirror from a\n deleted catalogue never presses it. */}\n {def.disconnectNote && (\n <p className=\"text-[11px] leading-relaxed text-muted-foreground\">{def.disconnectNote}</p>\n )}\n </div>\n )}\n </div>\n </TabsContent>\n\n {def.OperatePanel && (\n <TabsContent value=\"operate\" className=\"pt-4\">\n <def.OperatePanel />\n </TabsContent>\n )}\n\n {runsAvailable && (\n <TabsContent value=\"runs\" className=\"pt-4\">\n <ConnectorRuns connector={connector} state={runs} />\n </TabsContent>\n )}\n\n {settingsAvailable && (\n <TabsContent value=\"settings\" className=\"space-y-5 pt-4\">\n {/* Named, and next to the field it names. The badge upstairs says\n \"Falta configurar\"; only this can say what is missing. */}\n {needsSetup && missing.length > 0 && (\n <p className=\"flex items-start gap-1.5 text-xs text-warning\">\n <AlertTriangle className=\"mt-px h-3.5 w-3.5 shrink-0\" />\n <span>{t('connectors.missingNamed', { list: missing.join(', ') })}</span>\n </p>\n )}\n\n {/* As credenciais, onde elas se TROCAM.\n \n Antes disto o formulário só existia no passo 3 da instalação, e\n depois de conectado sumia: a única forma de corrigir uma chave\n era desconectar e refazer tudo. Um conector que passa a pedir uma\n credencial nova — foi o que aconteceu com a Vindi — não tinha\n onde recebê-la. */}\n {(def.fields ?? []).length > 0 && (\n <Section title={t('connectors.credentials.section')}>\n <ConnectPanel\n connector={connector}\n values={values}\n setValues={setValues}\n secrets={secrets}\n busy={busy}\n run={run}\n />\n </Section>\n )}\n\n {/* No group heading: the tab is the heading. A \"Como funciona\"\n title under a tab labelled Configurações is a line of chrome. */}\n <ConnectorSettingsPanel connector={connector} onSaved={onChanged} bare />\n\n {/* How it resolves is a live setting when the connector can change\n it, and nothing at all when it cannot — never a locked control. */}\n {def.setPlane && connector.planes.length > 1 && (\n <Section title={t('connectors.overview.resolves')}>\n <PlanePicker\n planes={connector.planes}\n value={connector.activePlane}\n onChange={(next) =>\n run('plane', () => def.setPlane!(next), t('connectors.plane.switched'))\n }\n />\n </Section>\n )}\n\n {/* The connector's own CONFIGURATION — the calendar mapping, and\n nothing else any more. What used to ride along in here left for\n the places those things are: the import wizard and the history to\n Sincronizações, the health warnings to Visão geral. Rendered\n whatever the plane: which plane answers a request has nothing to\n do with what a merchant may configure. */}\n {def.ExtraPanel && (\n <Section title={t('connectors.overview.provider', { name: connector.name })}>\n <def.ExtraPanel />\n </Section>\n )}\n </TabsContent>\n )}\n </Tabs>\n </div>\n )\n}\n\n/**\n * Run one connector call: busy flag, toast, reload.\n *\n * Shared by both lives so that a failure reads the same whether it happened\n * while connecting or while changing a setting — and so that the one sentence\n * that must never carry a typed value stays in one place.\n */\nfunction useRunner<K extends string>(\n setBusy: React.Dispatch<React.SetStateAction<K | null>>,\n onChanged?: () => void,\n) {\n const { t } = useTranslation()\n return React.useCallback(\n async (kind: K, fn: () => Promise<unknown>, okMessage?: string) => {\n setBusy(kind)\n try {\n await fn()\n if (okMessage) toast.success(okMessage)\n onChanged?.()\n } catch (e: any) {\n // Only the app's own misconfiguration is translated here — nowhere to\n // put the key, nowhere to send the person to authorize. A connector's\n // message is its own, and none of them ever carries what was typed.\n toast.error(\n e instanceof CredentialSinkMissingError\n ? t('connectors.credentials.noSink')\n : e instanceof ConnectorOAuthStarterMissingError\n ? t('connectors.oauth.noStarter')\n : (e?.message ?? t('common.error')),\n )\n } finally {\n setBusy(null)\n }\n },\n [onChanged, t],\n )\n}\n\n/**\n * The journey as a right-hand sheet — the fallback surface.\n *\n * Apps with an assistant show this inside the rail instead, next to the chat:\n * a connector is a capability of the agent, so it belongs in the agent's own\n * column rather than in a panel that floats over the page. This wrapper is what\n * an app without that rail falls back to, so the journey is never unreachable.\n */\nexport function ConnectorDetail({\n connector,\n open,\n onOpenChange,\n onChanged,\n onRevoke,\n}: {\n connector: UnifiedConnector | null\n open: boolean\n onOpenChange: (open: boolean) => void\n onChanged?: () => void\n onRevoke?: (connector: UnifiedConnector) => Promise<void> | void\n}) {\n if (!connector) return null\n return (\n <RightRailPage\n title={connector.name}\n open={open}\n onClose={() => onOpenChange(false)}\n width=\"max-w-lg\"\n >\n <div className=\"shrink-0 px-5 pt-4\">\n <ConnectorHeading connector={connector} />\n </div>\n <SheetBody>\n <ConnectorJourney connector={connector} onChanged={onChanged} onRevoke={onRevoke} />\n </SheetBody>\n </RightRailPage>\n )\n}\n\n/**\n * What the connection says about itself, said once.\n *\n * `issues` and `detail` are the same fact at two lengths — a connector that\n * enumerates what is wrong has `detail` carrying the first of them, and\n * rendering both put the same sentence on screen twice. So the list wins when\n * there is one, and `detail` is what a connector with one thing to say uses.\n */\nfunction ConnectionReport({ connector }: { connector: UnifiedConnector }) {\n const issues = connector.issues ?? []\n if (issues.length > 0) {\n return (\n <ul className=\"space-y-1\">\n {issues.map((issue) => (\n <li key={issue} className=\"flex items-start gap-1.5 text-xs leading-relaxed text-warning\">\n <AlertTriangle className=\"mt-px h-3.5 w-3.5 shrink-0\" />\n <span>{issue}</span>\n </li>\n ))}\n </ul>\n )\n }\n if (!connector.detail) return null\n return <p className=\"text-xs leading-relaxed text-muted-foreground\">{connector.detail}</p>\n}\n\nfunction Note({ children }: { children: React.ReactNode }) {\n return (\n <p className=\"flex items-start gap-2 rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground\">\n <Info className=\"mt-px h-3.5 w-3.5 shrink-0\" />\n <span>{children}</span>\n </p>\n )\n}\n\n/** What the connector reaches — entities, tools, scopes. */\nfunction Capabilities({ connector }: { connector: UnifiedConnector }) {\n const { t } = useTranslation()\n const entityCount = connector.entityCount ?? connector.entities?.length\n const tools = connector.agentTools ?? []\n\n return (\n <div className=\"space-y-2 text-xs text-muted-foreground\">\n {connector.direction === 'inbound' && (\n <p>\n {connector.readOnly ? t('connectors.readOnly') : t('connectors.readWrite')}\n {typeof entityCount === 'number' && entityCount > 0\n ? ` · ${t('connectors.entitiesCount', { count: entityCount })}`\n : ''}\n {connector.agentConfig?.model ? ` · ${connector.agentConfig.model}` : ''}\n </p>\n )}\n\n {/* Chips rather than \"Registros: order, payment\": a comma-joined list of\n machine keys reads as a debug line, and it was the only thing on the\n overview tab. Suppressed once permissions exist: the consent view says\n the same names WITH read or write against each. */}\n {connector.direction === 'outbound' && !connector.permissions?.length && connector.entities?.length ? (\n <div className=\"flex flex-wrap gap-1\">\n {connector.entities.map((entity) => (\n <span key={entity} className=\"rounded-full border border-border px-2 py-0.5 text-[11px]\">\n {entityLabel(t, entity)}\n </span>\n ))}\n </div>\n ) : null}\n\n {tools.length > 0 && (\n <div>\n <p className=\"mb-1\">{t('connectors.tools')}</p>\n <div className=\"flex flex-wrap gap-1\">\n {tools.map((tool) => (\n <span\n key={tool.name}\n title={tool.description}\n className=\"rounded border border-border px-1.5 py-0.5 font-mono text-[10px]\"\n >\n {tool.name}\n </span>\n ))}\n </div>\n </div>\n )}\n\n {connector.scopes && connector.scopes.length > 0 && (\n <div className=\"flex flex-wrap gap-1\">\n {connector.scopes.map((s) => (\n <span key={s} className=\"rounded bg-muted px-1.5 py-0.5 font-mono text-[10px]\">\n {s}\n </span>\n ))}\n </div>\n )}\n\n {/* Only when NOTHING was published. It used to ignore scopes and the\n read/write line, so a grant that had just said \"somente leitura · read\"\n followed it with \"ainda não publicou o que ele alcança\". */}\n {tools.length === 0 &&\n !connector.entities?.length &&\n !connector.scopes?.length &&\n typeof entityCount !== 'number' &&\n connector.direction !== 'inbound' && <p>{t('connectors.capabilitiesUnknown')}</p>}\n </div>\n )\n}\n\n/**\n * An entity key in the reader's language, falling back to the key.\n *\n * The fallback is the point: a connector may name an entity this app has never\n * heard of, and a missing translation should read as an unfamiliar word rather\n * than as a blank chip.\n */\nfunction entityLabel(t: (key: string) => string, entity: string): string {\n const key = `connectors.entity.${entity}`\n const translated = t(key)\n return translated && translated !== key ? translated : entity\n}\n\n/**\n * \"Go install it there first, then come back and paste what it showed you.\"\n *\n * The honest shape for a provider that issues its keys at INSTALL time rather\n * than handing a code back on a redirect. It is not a fifth kind of auth and not\n * a special case for one gateway: the panel reads\n * {@link ConnectorDefinition.providerInstall}, the copy is generic over the\n * connector's own name, and the address is the connector's to declare — so the\n * second provider that works this way is a URL, not a component.\n */\nfunction ProviderInstallStep({ connector }: { connector: ConnectorDefinition }) {\n const { t } = useTranslation()\n const install = connector.providerInstall\n if (!install) return null\n return (\n <div className=\"space-y-2\">\n <Note>{t('connectors.authorize.installFirst', { name: connector.name })}</Note>\n <Button asChild variant=\"outline\" size=\"sm\">\n <a href={install.url} target=\"_blank\" rel=\"noreferrer\">\n <ExternalLink className=\"h-3.5 w-3.5\" />\n {t('connectors.authorize.installAt', { name: connector.name })}\n </a>\n </Button>\n </div>\n )\n}\n\n/**\n * What AUTHORIZES the connection, and nothing else.\n *\n * This panel used to render whatever `fields` held, and `fields` held two\n * unrelated things — the key that authorizes, and the policy that configures. So\n * connecting AppMax asked for \"Formas de pagamento (pix, boleto, credit_card)\"\n * in a free-text box before the merchant was allowed to plug the gateway in.\n * Operational configuration moved to `settings`, rendered in step 4.\n *\n * What is left can still be EMPTY: an OAuth connector authorizes by consent,\n * and a connector with no declared fields (PlugBank) has nothing to type at\n * all. Empty is the honest answer — it just has to be said rather than drawn\n * as a blank grid. (AppMax and Melhor Envio are no longer this case: they\n * declare `type: 'password'` fields, which route to the credential sink.)\n *\n * The secret half still leaves by its own door: what the connector declared as\n * configuration is passed to its own code, and what it declared as a secret goes\n * to the platform's credential sink. See `./credentials`.\n */\nfunction ConnectPanel({\n connector,\n values,\n setValues,\n secrets,\n busy,\n run,\n}: {\n connector: UnifiedConnector\n values: Record<string, string>\n setValues: React.Dispatch<React.SetStateAction<Record<string, string>>>\n secrets: React.MutableRefObject<Record<string, string>>\n busy: string | null\n run: (kind: any, fn: () => Promise<unknown>, ok?: string) => Promise<void>\n}) {\n const { t } = useTranslation()\n const def = connector.definition!\n const tenantId = useTenantOptional()?.org?.id\n const needsSink = needsCredentialSink(def)\n const sinkMissing = needsSink && !getConnectorCredentialSink()\n const secretFieldCount = (def.fields ?? []).filter(isSecretField).length\n // `needs_setup` conta: a credencial ESTÁ guardada, o que falta é um ajuste.\n const hasStoredCredential = connector.state === 'connected' || connector.state === 'needs_setup'\n // Bumped after a save so the secret inputs remount empty — the ref is cleared\n // with them, and neither keeps the value once it has been placed.\n const [formKey, setFormKey] = React.useState(0)\n\n const fields = def.fields ?? []\n\n // An OAuth connector may ALSO take a pasted key (Stripe: the grant and the\n // secret key are the same credential from two sources). The consent button\n // stays the first door; the fields below it are the second, and both land\n // in the vault under the same connector.\n const oauthDoor = def.authKind === 'oauth' ? (\n <div className=\"space-y-3\">\n <Note>{t(fields.length > 0 ? 'connectors.authorize.oauthOrKey' : 'connectors.authorize.oauthOnly')}</Note>\n <Button\n disabled={busy === 'oauth' || !def.startOAuth}\n onClick={() =>\n run('oauth', async () => {\n // The tenant is a selector the platform re-checks against proven\n // memberships; a merchant in two organizations is otherwise\n // indistinguishable from one in none. See ConnectorConnectContext.\n const url = await def.startOAuth!(window.location.href, { tenantId })\n window.location.href = url\n })\n }\n >\n {busy === 'oauth' ? <Loader2 className=\"h-4 w-4 animate-spin\" /> : <Plug className=\"h-4 w-4\" />}\n {`${t('connectors.connect')} ${def.name}`}\n </Button>\n </div>\n ) : null\n\n if (oauthDoor && fields.length === 0) return oauthDoor\n\n // A connector whose setup is its own panel (Evolution: URL, key, instance,\n // QR pairing) and no save of its own: the panel IS the connect step.\n if (!oauthDoor && fields.length === 0 && !def.saveConnection && def.ExtraPanel) return <def.ExtraPanel />\n\n return (\n <div className=\"space-y-3\">\n {oauthDoor}\n {/* The door at the provider, when the keys are only issued there. Driven\n entirely by the declaration, so the next connector with the same\n gesture needs a URL and no change here. */}\n <ProviderInstallStep connector={def} />\n {needsSink && (\n <Note>{sinkMissing ? t('connectors.credentials.noSink') : t('connectors.credentials.held')}</Note>\n )}\n {/* Só quando há mais de um segredo E já existe conexão. A plataforma\n guarda as credenciais como UM bloco cifrado e um save o substitui\n inteiro — quem voltar aqui para acrescentar um campo e não redigitar os\n outros apaga os outros. Com um segredo só não há o que perder, e numa\n conexão nova não há nada guardado; nos dois casos o aviso seria ruído. */}\n {needsSink && !sinkMissing && secretFieldCount > 1 && hasStoredCredential && (\n <Note>{t('connectors.credentials.replaces')}</Note>\n )}\n {fields.length === 0 && !def.providerInstall && !oauthDoor && <Note>{t('connectors.authorize.nothingToFill')}</Note>}\n <div className=\"grid gap-3 sm:grid-cols-2\">\n {fields.map((f) =>\n isSecretField(f) ? (\n <label key={`${f.key}:${formKey}`} className=\"block\">\n <span className=\"text-xs font-medium text-muted-foreground\">{f.label}</span>\n <Input\n type={f.type}\n defaultValue=\"\"\n onChange={(e) => { secrets.current[f.key] = e.target.value }}\n placeholder={f.placeholder}\n autoComplete=\"off\"\n className=\"mt-1\"\n />\n </label>\n ) : (\n <label key={f.key} className=\"block\">\n <span className=\"text-xs font-medium text-muted-foreground\">{f.label}</span>\n <Input\n type={f.type}\n value={values[f.key] ?? ''}\n onChange={(e) => setValues((v) => ({ ...v, [f.key]: e.target.value }))}\n placeholder={f.placeholder}\n className=\"mt-1\"\n />\n </label>\n ),\n )}\n </div>\n <div className=\"flex gap-2\">\n {/* Testing before saving would need the secret in author code's hands.\n Once there is one in the form, the connection is tested by being made. */}\n {def.testConnection && !needsSink && (\n <Button\n variant=\"outline\"\n size=\"sm\"\n disabled={busy === 'test'}\n onClick={() =>\n run('test', async () => {\n const res = await probeConnection({ definition: def, values })\n if (!res.ok) throw new Error(res.message ?? t('common.error'))\n toast.success(res.message ?? t('connectors.connected'))\n })\n }\n >\n {busy === 'test' ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <Plug className=\"h-3.5 w-3.5\" />}\n {t('connectors.test')}\n </Button>\n )}\n {def.saveConnection && (\n <Button\n size=\"sm\"\n disabled={busy === 'save' || sinkMissing}\n onClick={() =>\n run('save', async () => {\n try {\n await submitConnection({\n definition: def,\n values: { ...values, ...secrets.current },\n tenantId,\n })\n } finally {\n secrets.current = {}\n setFormKey((k) => k + 1)\n }\n }, t('connectors.save'))\n }\n >\n {busy === 'save' ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <CheckCircle2 className=\"h-3.5 w-3.5\" />}\n {/* With nothing to fill in, \"Salvar conexão\" describes no act the\n person just performed. Connecting is the act. */}\n {fields.length === 0 ? `${t('connectors.connect')} ${def.name}` : t('connectors.save')}\n </Button>\n )}\n </div>\n </div>\n )\n}\n\n/**\n * Unplugging, everywhere it appears.\n *\n * One component because there is one act. It was an outlined red button on a\n * grant and a plain outlined button on a provider, which read as two different\n * things on two screens that are the same screen. Quiet by construction — this\n * is never the thing someone came here to do (`destructive-emphasis`), and it\n * sits below a divider, away from anything tapped by habit.\n */\nfunction DisconnectAction({\n onDisconnect,\n busy,\n}: {\n onDisconnect: () => void\n busy?: boolean\n}) {\n const { t } = useTranslation()\n return (\n <Button\n variant=\"bare\"\n size=\"bare\"\n type=\"button\"\n disabled={busy}\n onClick={onDisconnect}\n className=\"flex items-center gap-1.5 text-xs text-destructive transition-colors hover:text-destructive/80 disabled:opacity-50 font-normal\"\n >\n {busy ? <Loader2 className=\"h-3.5 w-3.5 animate-spin\" /> : <Power className=\"h-3.5 w-3.5\" />}\n {t('connectors.disconnect')}\n </Button>\n )\n}\n\n/** An inbound grant, in facts a badge cannot hold: since when, last used, by whom. */\nfunction GrantFacts({ connector }: { connector: UnifiedConnector }) {\n const { t } = useTranslation()\n const facts = [\n connector.createdAt ? t('connectors.connectedOn', { date: formatDate(connector.createdAt) }) : null,\n connector.lastUsedAt\n ? t('connectors.lastUsed', { when: formatRelative(connector.lastUsedAt, t) })\n : t('connectors.neverUsed'),\n connector.grantedByMe === false ? t('connectors.grantedByOther') : null,\n ].filter(Boolean)\n\n return <p className=\"text-xs text-muted-foreground\">{facts.join(' · ')}</p>\n}\n\n/** The way back out of a grant — or why there isn't one. */\nfunction GrantRevoke({\n connector,\n onRevoke,\n}: {\n connector: UnifiedConnector\n onRevoke?: (connector: UnifiedConnector) => Promise<void> | void\n}) {\n const { t } = useTranslation()\n const [revoking, setRevoking] = React.useState(false)\n\n // No button rather than a disabled one: the assistant is part of the product,\n // and turning it off is a project setting. A greyed \"Desconectar\" would read\n // as something the user could fix.\n if (connector.revocable === false) {\n return <p className=\"text-xs text-muted-foreground\">{t('connectors.partOfApp')}</p>\n }\n\n return (\n <DisconnectAction\n busy={revoking}\n onDisconnect={async () => {\n setRevoking(true)\n try {\n await onRevoke?.(connector)\n } finally {\n setRevoking(false)\n }\n }}\n />\n )\n}\n","import { connectionKey, listConnections } from '@fayz-ai/core'\nimport type { ConnectionConfig, ConnectorDefinition, ConnectorStatus } from '@fayz-ai/core'\nimport type { InstalledConnector } from './model'\n\n/** One shape out of both doors, so the batched path cannot report less than the single one. */\nfunction toInstalled(definition: ConnectorDefinition, status: ConnectorStatus): InstalledConnector {\n return {\n definition,\n connected: status.connected,\n detail: status.detail,\n issues: status.issues,\n plane: status.plane,\n needsSetup: status.needsSetup,\n missingSettings: status.missingSettings,\n }\n}\n\n/**\n * How many requests the connectors screen costs.\n *\n * It used to cost one per connector: every `getStatus()` opened its own\n * `connections?connector_id=eq.<X>` read, so four installed connectors were\n * four round trips before the list could render once. They all share one table,\n * so `connector_id=in.(a,b,c,d)` answers all of them — that is what\n * `statusFromConnection` on the definition is for.\n *\n * A connector whose truth is not in that table (Stripe Connect derives from the\n * provider and stores no row) declares no `statusFromConnection` and is still\n * asked one-by-one, which is correct: there is nothing to batch it with.\n *\n * Its own module so the request count is assertable without a DOM.\n */\n\n// One in-flight batch per tenant. A caller wanting a subset of what is already\n// in flight (a plugin's Integrações tab, against the full Settings list) joins\n// it instead of opening a second read.\n//\n// The tenant is in the key AND in the query. It has to be in both: a flight\n// keyed only by connector ids would hand a freshly switched tenant the previous\n// tenant's rows.\nlet connectionsFlight:\n | { tenantId: string; ids: Set<string>; promise: Promise<Map<string, ConnectionConfig>> }\n | null = null\n\n// Same reasoning for the connectors the batch cannot answer: concurrent mounts\n// join the flight in progress.\n//\n// Nothing outlives the flight, deliberately — unlike the grants cache next door,\n// there is no TTL here. A grant only changes through `revokeGrant`/`reload`,\n// which invalidate it; a connector's status changes on this very screen and also\n// from its own ExtraPanel, which has no way to tell a cache. A 30s TTL would\n// show \"not connected\" for half a minute after a successful connect, and what it\n// would save is now one batched read rather than N.\nconst statusFlights = new Map<string, Promise<InstalledConnector>>()\n\n/** Test seam — drops in-flight bookkeeping. */\nexport function resetConnectorStatusFlights(): void {\n connectionsFlight = null\n statusFlights.clear()\n}\n\nfunction loadConnections(tenantId: string, ids: string[], client?: unknown): Promise<Map<string, ConnectionConfig>> {\n const flight = connectionsFlight\n if (flight && flight.tenantId === tenantId && ids.every((id) => flight.ids.has(id))) return flight.promise\n\n // An unreadable table is \"nothing connected\", never a broken list.\n const promise = listConnections(ids, { tenantId, client }).catch(() => new Map<string, ConnectionConfig>())\n const entry = { tenantId, ids: new Set(ids), promise }\n connectionsFlight = entry\n void promise.finally(() => {\n if (connectionsFlight === entry) connectionsFlight = null\n })\n return promise\n}\n\nfunction batchable(definition: ConnectorDefinition): boolean {\n return typeof definition.statusFromConnection === 'function'\n}\n\nfunction loadStatus(definition: ConnectorDefinition, tenantId: string | undefined): Promise<InstalledConnector> {\n const key = `${tenantId ?? ''} ${definition.id}`\n let flight = statusFlights.get(key)\n if (!flight) {\n flight = definition\n .getStatus()\n .then((status): InstalledConnector => toInstalled(definition, status))\n .catch((): InstalledConnector => ({ definition, connected: false }))\n statusFlights.set(key, flight)\n void flight.finally(() => statusFlights.delete(key))\n }\n return flight\n}\n\n/**\n * Every installed connector's status. One read for all those that share\n * `connections`, plus one each for those that do not.\n *\n * `tenantId` is required for batching — without an active tenant there is no\n * row to scope, and each connector falls back to reporting for itself.\n */\nexport function loadConnectorStatuses(\n definitions: ConnectorDefinition[],\n tenantId: string | undefined,\n options: { client?: unknown } = {},\n): Promise<InstalledConnector[]> {\n const batched = tenantId ? definitions.filter(batchable) : []\n const shared =\n batched.length > 0 ? loadConnections(tenantId!, batched.map((d) => d.id), options.client) : null\n\n return Promise.all(\n definitions.map(async (definition): Promise<InstalledConnector> => {\n if (!shared || !batchable(definition)) return loadStatus(definition, tenantId)\n const rows = await shared\n try {\n return toInstalled(\n definition,\n definition.statusFromConnection!(\n rows.get(connectionKey(definition.id, definition.instanceKey ?? '')) ?? null,\n ),\n )\n } catch {\n return { definition, connected: false }\n }\n }),\n )\n}\n","import React from 'react'\nimport { usePluginRuntimeOptional } from '@fayz-ai/core'\nimport type { ConnectorDefinition } from '@fayz-ai/core'\nimport { getFayzSupabaseClientOptional } from '../../data/client'\nimport { loadConnectorStatuses } from './connector-status'\nimport { resolveFayzAgentConnection } from '../../lib/fayz-agent'\nimport { useTenantOptional } from '../../org/context'\nimport {\n buildConnectorList,\n type AgentGrant,\n type CatalogConnector,\n type InstalledConnector,\n type UnifiedConnector,\n} from './model'\n\n/**\n * One loader for both surfaces.\n *\n * Settings → Conectores and a plugin's Integrações tab are the same list seen\n * from two distances, so they must read the same rows — same id, same brand\n * mark, same journey. Two loaders would be two answers to \"o Google Calendar\n * está ligado?\", and the one the user happened to open would decide which is\n * true.\n */\n\n// The catalogue is global and immutable per session; fetching it once keeps a\n// plugin tab from re-hitting the platform every time it mounts.\nlet catalogPromise: Promise<CatalogConnector[]> | null = null\n\nexport function loadCatalog(): Promise<CatalogConnector[]> {\n if (catalogPromise) return catalogPromise\n const connection = resolveFayzAgentConnection()\n if (!connection) return Promise.resolve([])\n catalogPromise = fetch(`${connection.apiBaseUrl}/connectors?locale=pt-BR`)\n .then(async (response) => {\n // A 503 answers with a JSON error body, so `.json()` SUCCEEDS and the\n // shape check below quietly reads it as \"no connectors\". Without this\n // line one blip on the platform pins an empty catalogue to the session\n // and \"Adicionar conector\" stays empty until the tab is reloaded.\n if (!response.ok) throw new Error(`catalog HTTP ${response.status}`)\n const body = (await response.json()) as CatalogConnector[] | { connectors?: CatalogConnector[] }\n return Array.isArray(body) ? body : (body.connectors ?? [])\n })\n .catch(() => {\n catalogPromise = null // a network blip shouldn't poison the session\n return []\n })\n return catalogPromise\n}\n\nexport function useConnectorCatalog(): CatalogConnector[] | null {\n const [catalog, setCatalog] = React.useState<CatalogConnector[] | null>(null)\n React.useEffect(() => {\n let cancelled = false\n void loadCatalog().then((list) => {\n if (!cancelled) setCatalog(list)\n })\n return () => {\n cancelled = true\n }\n }, [])\n return catalog\n}\n\n// Grants are read by up to three surfaces at once (Conectores tab, assistant\n// drawer, plugin hub) and dev StrictMode mounts each twice — without sharing,\n// opening one screen costs 6+ identical GETs. One flight per (project, tenant),\n// reused for a short window; reload() and revoke invalidate.\nconst GRANTS_TTL_MS = 30_000\nconst grantsCache = new Map<string, { at: number; promise: Promise<AgentGrant[]> }>()\n\nfunction invalidateGrants(): void {\n grantsCache.clear()\n}\n\n/**\n * One revision for every list on screen.\n *\n * Connecting happens in the assistant's drawer while Settings → Conectores is\n * open behind it, and the two were separate `useState` counters: the drawer\n * reloaded, the list under it kept saying \"Não conectado\" until something else\n * remounted it. A module-level revision with subscribers means \"something\n * changed\" reaches every mounted list, which is the only way two views of one\n * fact can stay in agreement.\n */\nlet _revision = 0\nconst _revisionListeners = new Set<() => void>()\n\n/** Every connector list on screen re-reads. Safe to call from anywhere. */\nexport function refreshConnectors(): void {\n invalidateGrants()\n _revision += 1\n _revisionListeners.forEach((listener) => listener())\n}\n\nfunction useConnectorsRevision(): number {\n return React.useSyncExternalStore(\n (listener) => {\n _revisionListeners.add(listener)\n return () => _revisionListeners.delete(listener)\n },\n () => _revision,\n () => _revision,\n )\n}\n\nfunction loadGrants(key: string, fetcher: () => Promise<AgentGrant[]>): Promise<AgentGrant[]> {\n const hit = grantsCache.get(key)\n if (hit && Date.now() - hit.at < GRANTS_TTL_MS) return hit.promise\n const promise = fetcher()\n promise.catch(() => grantsCache.delete(key)) // a failure must not be served for 30s\n grantsCache.set(key, { at: Date.now(), promise })\n return promise\n}\n\n/**\n * Plugin ids mounted in this build.\n *\n * What tells \"não dá pra ligar ainda\" from \"não tem esse módulo\": both are inert\n * rows on the same shelf, and only the module the app actually has decides which\n * sentence is true. Inactive plugins count — a module switched off for a tenant\n * is still in the app, and offering it as something a new build would bring is a\n * lie the tenant can disprove from the settings screen.\n */\nexport function useInstalledModuleIds(): string[] {\n const runtime = usePluginRuntimeOptional()\n return React.useMemo(() => (runtime?.plugins ?? []).map((p) => p.id), [runtime])\n}\n\n/** Connector definitions this app has installed, optionally scoped to one host plugin. */\nfunction useInstalledDefinitions(hostPluginId?: string): ConnectorDefinition[] {\n const runtime = usePluginRuntimeOptional()\n return React.useMemo(() => {\n const byHost = runtime?.connectorsByHost\n if (!byHost) return []\n if (hostPluginId) return byHost.get(hostPluginId) ?? []\n return [...byHost.values()].flat()\n }, [runtime, hostPluginId])\n}\n\nexport interface ConnectorsView {\n connectors: UnifiedConnector[] | null\n error: string | null\n reload: () => void\n /** Withdraw an inbound grant. Resolves once the row is gone. */\n revokeGrant: (connector: UnifiedConnector) => Promise<void>\n /** No Fayz project behind this app — the inbound half simply doesn't exist. */\n agentAvailable: boolean\n tenantReady: boolean\n}\n\n/**\n * Builds the unified list: inbound grants (what reaches this org) + installed\n * connectors (what this app reaches). The catalogue contributes no row — it only\n * lends the connectors that ARE installed their localized copy and brand mark.\n */\nexport function useConnectors(options: {\n hostPluginId?: string\n /** Include the inbound grants — the plugin-scoped view leaves them out. */\n includeGrants?: boolean\n /** Enrich installed connectors with the catalogue's localized copy and mark. */\n includeCatalog?: boolean\n} = {}): ConnectorsView {\n const { hostPluginId, includeGrants = true, includeCatalog = true } = options\n const definitions = useInstalledDefinitions(hostPluginId)\n const catalog = useConnectorCatalog()\n const tenant = useTenantOptional()\n const tenantId = tenant?.org?.id\n const connection = React.useMemo(() => resolveFayzAgentConnection(), [])\n\n const [installed, setInstalled] = React.useState<InstalledConnector[] | null>(null)\n const [grants, setGrants] = React.useState<AgentGrant[] | null>(null)\n const [error, setError] = React.useState<string | null>(null)\n const nonce = useConnectorsRevision()\n\n const call = React.useCallback(\n async (path: string, init?: RequestInit): Promise<Response> => {\n if (!connection) throw new Error('Este app não está ligado a um projeto Fayz.')\n const supabase = getFayzSupabaseClientOptional()\n const session = (await supabase?.auth.getSession())?.data.session\n if (!session?.access_token) throw new Error('Sessão expirada — entre de novo.')\n return fetch(\n `${connection.apiBaseUrl}/public/projects/${connection.projectId}/agents/connections${path}`,\n {\n ...init,\n headers: {\n ...(init?.headers ?? {}),\n Authorization: `Bearer ${session.access_token}`,\n 'Content-Type': 'application/json',\n },\n },\n )\n },\n [connection],\n )\n\n // Each connector reports its own status; one that throws is \"not connected\"\n // rather than a broken list. Re-runs on a tenant switch, and the answer is\n // scoped to the tenant that asked — never carried over from the previous one.\n React.useEffect(() => {\n let cancelled = false\n void loadConnectorStatuses(definitions, tenantId).then((list) => {\n if (!cancelled) setInstalled(list)\n })\n return () => {\n cancelled = true\n }\n }, [definitions, tenantId, nonce])\n\n React.useEffect(() => {\n if (!includeGrants || !connection || !tenantId) {\n setGrants(includeGrants ? null : [])\n return\n }\n let cancelled = false\n void loadGrants(`${connection.projectId}:${tenantId}`, async () => {\n const response = await call(`?tenantId=${encodeURIComponent(tenantId)}`)\n const body = (await response.json()) as { connections?: AgentGrant[]; message?: string }\n if (!response.ok) throw new Error(body.message ?? 'Não foi possível carregar as conexões.')\n return body.connections ?? []\n })\n .then((list) => {\n if (cancelled) return\n setGrants(list)\n setError(null)\n })\n .catch((e) => {\n if (cancelled) return\n setError((e as Error).message)\n setGrants([])\n })\n return () => {\n cancelled = true\n }\n }, [call, tenantId, includeGrants, connection, nonce])\n\n const revokeGrant = React.useCallback(\n async (connector: UnifiedConnector) => {\n // Named, like the list is: the vault refuses to guess for someone who\n // belongs to more than one account, and this is the account on screen.\n if (!tenantId) throw new Error('Nenhuma conta selecionada.')\n const response = await call(`/${connector.id}?tenantId=${encodeURIComponent(tenantId)}`, { method: 'DELETE' })\n if (!response.ok) {\n const body = (await response.json().catch(() => ({}))) as { message?: string }\n throw new Error(body.message ?? 'Não foi possível desconectar.')\n }\n invalidateGrants()\n setGrants((current) => (current ?? []).filter((g) => g.id !== connector.id))\n },\n [call, tenantId],\n )\n\n const waitingGrants = includeGrants && !!connection && !!tenantId && grants === null\n const connectors = React.useMemo(() => {\n if (installed === null || waitingGrants) return null\n return buildConnectorList({\n installed,\n grants: includeGrants ? (grants ?? []) : [],\n catalog: includeCatalog ? (catalog ?? []) : [],\n })\n }, [installed, grants, catalog, includeGrants, includeCatalog, waitingGrants])\n\n return {\n connectors,\n error,\n reload: refreshConnectors,\n revokeGrant,\n agentAvailable: !!connection,\n tenantReady: !!tenantId,\n }\n}\n","import React from 'react'\nimport { create } from 'zustand'\nimport { ChevronLeft, Search } from 'lucide-react'\nimport { Button, Skeleton, Input } from '@fayz-ai/ui'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { useRightRailStore, useRightRailDrill, useRightRailHosted } from '../right-rail'\nimport { useChatStore } from '../../stores/chat.store'\nimport { ConnectorMark } from './ConnectorMark'\nimport { StateChip } from './ConnectorRow'\nimport { ConfirmDialog } from '@fayz-ai/ui'\nimport { ConnectorHeading, ConnectorJourney } from './ConnectorDetail'\nimport { useConnectors } from './useConnectors'\nimport { filterConnectors, type UnifiedConnector } from './model'\n\n/**\n * Conectores, inside the assistant.\n *\n * A connector is not a settings chore that happens elsewhere — it is what the\n * assistant can reach. So it lives where the assistant's own capabilities\n * already live: the chat panel, one button after the tools drawer. Settings →\n * Conectores keeps the inventory (the list you audit and revoke from) and\n * opening a row raises the assistant with this drawer already on that\n * connector.\n *\n * Two views in the drawer:\n * - the list: what this organization has\n * - the journey: what a connector does, how it resolves, and how to authorize\n */\n\ninterface ConnectorsSurfaceState {\n /** Connector being shown; null means the list. */\n selected: string | null\n /**\n * A screen asked for this drawer and the chat hasn't opened it yet. A flag\n * rather than a counter because the request usually lands BEFORE the chat\n * panel mounts — the rail has to open first — so the chat has to find the\n * request waiting for it, not miss an edge it wasn't around for.\n */\n pending: boolean\n select: (id: string | null) => void\n open: (id: string | null) => void\n consume: () => void\n}\n\nexport const useConnectorsSurface = create<ConnectorsSurfaceState>((set) => ({\n selected: null,\n pending: false,\n select: (selected) => set({ selected }),\n open: (selected) => set({ selected, pending: true }),\n consume: () => set({ pending: false }),\n}))\n\n/** Raise the assistant with the connectors drawer open, on a connector or the\n * list. The id is all it takes — the panel resolves the row from its own list,\n * so a caller holding only a reference (an assistant card) can open it too. */\nexport function openConnectorsPanel(connector?: Pick<UnifiedConnector, 'id'> | null): void {\n useConnectorsSurface.getState().open(connector?.id ?? null)\n // Both doors to the same panel: the rail owns it on desktop, the chat store on\n // the mobile/dock surface. Opening both is idempotent and covers either shell.\n useRightRailStore.getState().openPanel('chat')\n useChatStore.getState().setOpen(true)\n}\n\n/** Whether the assistant is mounted and can host the journey. */\nexport function useConnectorsPanelAvailable(): boolean {\n return useRightRailStore((s) => s.mounted && s.panels.some((p) => p.id === 'chat'))\n}\n\nexport function ConnectorsPanel({ onClose }: { onClose: () => void }) {\n const { t } = useTranslation()\n // Everything loads, but only outbound connectors are LISTED: inside the\n // assistant, a connector is something IT reaches — an inbound grant is\n // someone else reaching this organization, which is a consent decision and\n // belongs on the settings screen. Grants still load because Settings can send\n // one straight here, and a journey that couldn't resolve what it was asked to\n // show would silently bounce the user back to the list.\n const { connectors, reload, revokeGrant, agentAvailable, tenantReady } = useConnectors()\n const selectedId = useConnectorsSurface((s) => s.selected)\n const select = useConnectorsSurface((s) => s.select)\n const [query, setQuery] = React.useState('')\n const [failure, setFailure] = React.useState<string | null>(null)\n const [revoking, setRevoking] = React.useState<null | Parameters<typeof revokeGrant>[0]>(null)\n\n const selected = React.useMemo(\n () => (connectors ?? []).find((c) => c.id === selectedId) ?? null,\n [connectors, selectedId],\n )\n\n const filtered = React.useMemo(\n () => filterConnectors(connectors ?? [], 'outbound', query),\n [connectors, query],\n )\n\n // Hosted in the rail, this journey's header IS the rail's header — one bar,\n // naming where you are and how to leave. Both levels ride it: a chosen\n // connector goes back to the list, the list goes back to the conversation.\n // Hosted in the rail this is ONE connector, never the catalogue: the list\n // already has a screen of its own (Configurações → Conectores), and a second\n // copy of it in a 380px column is a place to get lost in rather than a step\n // in the journey. So there is nothing to go \"up\" to — back leaves for the\n // chat, which is what the rail was showing before this arrived.\n const hosted = useRightRailHosted()\n useRightRailDrill(\n hosted\n ? {\n title: selected?.name ?? t('settings.connectors'),\n back: onClose,\n }\n : null,\n )\n\n // Nothing asked for → nothing for the rail to show. (Keyed on the REQUEST,\n // not on the resolved connector: while the list loads the request is set and\n // `selected` is still null.)\n const closeRef = React.useRef(onClose)\n closeRef.current = onClose\n React.useEffect(() => {\n if (hosted && !selectedId) closeRef.current()\n }, [hosted, selectedId])\n\n return (\n <div className=\"min-h-0 flex-1 overflow-y-auto\">\n {/* Standalone mount (no rail to host it) keeps the panel's own bar. */}\n {!hosted && (\n <div className=\"sticky top-0 z-10 flex items-center justify-between gap-2 border-b border-border/40 bg-card/95 px-3 py-2 backdrop-blur\">\n {selected ? (\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={() => select(null)}\n className=\"inline-flex min-w-0 items-center gap-1 rounded-md px-1 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground justify-start whitespace-normal font-normal\"\n >\n <ChevronLeft className=\"h-3.5 w-3.5 shrink-0\" />\n <span className=\"truncate\">{t('settings.connectors')}</span>\n </Button>\n ) : (\n <span className=\"text-[11px] font-semibold text-foreground\">{t('settings.connectors')}</span>\n )}\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={onClose}\n className=\"rounded-md px-1.5 py-0.5 text-[11px] text-muted-foreground transition-colors hover:bg-muted hover:text-foreground font-normal\"\n >\n {t('common.done')}\n </Button>\n </div>\n )}\n\n {!agentAvailable || !tenantReady ? (\n <p className=\"p-4 text-sm text-muted-foreground\">\n {t(agentAvailable ? 'connectors.noOrgBody' : 'connectors.noProjectBody')}\n </p>\n ) : selected ? (\n <div className=\"space-y-4 p-3\">\n <ConnectorHeading connector={selected} />\n {failure && <p className=\"text-xs text-destructive\">{failure}</p>}\n <ConnectorJourney\n connector={selected}\n onChanged={reload}\n // Held until the dialog answers. `window.confirm` is the browser's,\n // not the product's: unthemed, and it freezes the tab while it is up.\n onRevoke={(connector) => setRevoking(connector)}\n />\n <ConfirmDialog\n open={!!revoking}\n title={t('connectors.revoke')}\n description={revoking ? t('connectors.revokeConfirm', { name: revoking.name }) : undefined}\n variant=\"destructive\"\n confirmLabel={t('connectors.revoke')}\n onConfirm={async () => {\n const connector = revoking\n setRevoking(null)\n if (!connector) return\n try {\n await revokeGrant(connector)\n select(null)\n } catch (e) {\n setFailure((e as Error).message)\n }\n }}\n onCancel={() => setRevoking(null)}\n />\n </div>\n ) : hosted ? (\n // Requested but not resolved yet — holding the slot, not offering the\n // catalogue as a consolation.\n <div className=\"space-y-3 p-3\" aria-hidden>\n <div className=\"flex items-center gap-2\">\n <Skeleton className=\"h-9 w-9 shrink-0 rounded-lg\" />\n <div className=\"flex-1 space-y-1.5\">\n <Skeleton className=\"h-3.5 w-28\" />\n <Skeleton className=\"h-3 w-40\" />\n </div>\n </div>\n <Skeleton className=\"h-20 w-full rounded-xl\" />\n </div>\n ) : (\n <>\n <div className=\"p-3 pb-2\">\n <div className=\"relative\">\n <Search className=\"pointer-events-none absolute left-2.5 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-muted-foreground\" />\n <Input\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={t('connectors.search')}\n className=\"h-8 rounded-lg border-border pl-8 pr-2.5 text-[13px]\"\n />\n </div>\n </div>\n\n {connectors === null ? (\n <div className=\"space-y-3 p-3\" aria-hidden>\n {[0, 1, 2].map((i) => (\n <div key={i} className=\"flex items-center gap-2\">\n <Skeleton className=\"h-9 w-9 shrink-0 rounded-lg\" />\n <div className=\"flex-1 space-y-1.5\">\n <Skeleton className=\"h-3.5 w-28\" />\n <Skeleton className=\"h-3 w-40\" />\n </div>\n </div>\n ))}\n </div>\n ) : (\n <>\n <Section title={t('connectors.groupMine')} items={filtered} onSelect={(c) => select(c.id)} />\n {filtered.length === 0 && (\n <p className=\"p-4 text-sm text-muted-foreground\">{t('connectors.emptyBody')}</p>\n )}\n </>\n )}\n </>\n )}\n </div>\n )\n}\n\nfunction Section({\n title,\n items,\n onSelect,\n}: {\n title: string\n items: UnifiedConnector[]\n onSelect: (connector: UnifiedConnector) => void\n}) {\n if (items.length === 0) return null\n return (\n <section className=\"pb-2\">\n <h3 className=\"px-3 pb-1 pt-1 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground/50\">\n {title}\n </h3>\n <ul>\n {items.map((c) => (\n <li key={c.id}>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={() => onSelect(c)}\n className=\"flex w-full items-center gap-2.5 px-3 py-1.5 text-left transition-colors hover:bg-muted/50 justify-start whitespace-normal text-[length:inherit] font-normal rounded-none\"\n >\n <ConnectorMark connector={c} size=\"sm\" />\n {/* Name and state. The plane badges that used to sit here are the\n same fact the detail explains in words, and in a 380px column\n they pushed every name to an ellipsis. */}\n <span className=\"min-w-0 flex-1\">\n <span className=\"block truncate text-[13px] font-medium text-foreground\">{c.name}</span>\n <span className=\"mt-0.5 block\">\n <StateChip state={c.state} />\n </span>\n </span>\n </Button>\n </li>\n ))}\n </ul>\n </section>\n )\n}\n","import React from 'react'\nimport { Plus, Search, Sparkles } from 'lucide-react'\nimport {\n Button, Modal,\n ModalContent,\n ModalHeader,\n ModalTitle,\n ModalDescription,\n Skeleton,\n Input,\n} from '@fayz-ai/ui'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { useChatStore } from '../../stores/chat.store'\nimport { useRightRailStore } from '../right-rail'\nimport { ConnectorMark } from './ConnectorMark'\nimport { PlaneBadge, StateChip } from './ConnectorRow'\nimport { useConnectorsPanelAvailable } from './ConnectorsPanel'\nimport {\n addableConnectors,\n categoryLabel,\n comingSoonHere,\n filterAvailable,\n filterConnectors,\n inCategories,\n shelfIntegrations,\n withAnotherModule,\n type ShelfIntegration,\n type UnifiedConnector,\n} from './model'\nimport { useConnectorCatalog, useInstalledModuleIds } from './useConnectors'\n\n/**\n * What this app can be connected to, as an \"add\" panel.\n *\n * It lists the very same rows the hub does — same id, same mark, same badges —\n * because \"Google Calendar\" browsed here and \"Google Calendar\" configured in\n * Agenda → Integrações are one connector, not two screens that happen to share\n * a name. Picking one opens the same journey panel; nothing is duplicated here,\n * so nothing can drift.\n *\n * Three sections, and the lines between them are what the app can actually do:\n *\n * - **Instalados** — a plugin in this build contributes the connector, so it\n * can be connected now. One click, same journey as the hub.\n * - **Em breve** — a module this app HAS put the provider on its shelf, and\n * the integration is not built yet. Informational: it is the honest answer\n * to \"o Kommo dá pra ligar?\" from someone who has CRM.\n * - **Disponíveis com outro módulo** — the provider belongs to a module this\n * app was not built with.\n *\n * The last two are inert rows: they say why and stop. Not a disabled button,\n * because a disabled control reads as something the user could fix, and a\n * tenant admin cannot — modules are chosen when the app is built, there is no\n * install path, no plan that unlocks one, and no route to link to (see\n * ConnectorDetail's Note pattern, and #89's two-state ConnectorState).\n *\n * Both come from `SDK_INTEGRATIONS`, generated from the plugin manifests in\n * this repo — never from the platform catalogue, whose `enabled` flag is\n * addressed to a builder org and is how a salon owner was once offered Supabase\n * and Anthropic. The catalogue is read only for a row's brand mark and its\n * localized name; a provider no module declared appears in no list at all.\n *\n * The way to ask for more is the assistant — never a link into the builder\n * directory, which is the same audience confusion wearing a politer hat.\n *\n * **`categories` scopes it to the section that opened it.** Opened from\n * \"Provedores de pagamento\", the panel offered Bling and Melhor Envio — an ERP\n * and a carrier, under a button whose only promise was a gateway. The section\n * already knows which categories it is about (it filters its own list by them),\n * so it says so here and the panel narrows: the same rows, the same journey,\n * minus everything that could not have answered the question that was asked.\n */\nexport function AddConnectorPanel({\n open,\n onOpenChange,\n connectors,\n categories,\n onSelect,\n}: {\n open: boolean\n onOpenChange: (open: boolean) => void\n /** The unified list; `null` while it loads. */\n connectors: UnifiedConnector[] | null\n /**\n * Limit the panel to these connector categories — pass what the surrounding\n * section lists. Omitted, the panel is the whole app, which is what the\n * Integrações hub wants.\n */\n categories?: string[]\n onSelect: (connector: UnifiedConnector) => void\n}) {\n const { t } = useTranslation()\n const [query, setQuery] = React.useState('')\n\n const modules = useInstalledModuleIds()\n const catalog = useConnectorCatalog()\n\n const scoped = !!categories?.length\n const addable = React.useMemo(\n () => inCategories(addableConnectors(connectors ?? []), categories),\n [connectors, categories],\n )\n // Empty while the installed list loads: the shelf is \"everything the modules\n // declare MINUS what is here\", and before the first half is known that reads\n // as offering something the app may well already have.\n const shelf = React.useMemo(() => {\n if (connectors === null) return []\n return inCategories(\n shelfIntegrations({ present: connectors, installedModules: modules, catalog: catalog ?? [] }),\n categories,\n )\n }, [connectors, modules, catalog, categories])\n const filtered = React.useMemo(() => filterConnectors(addable, 'all', query), [addable, query])\n const filteredShelf = React.useMemo(() => filterAvailable(shelf, query), [shelf, query])\n const soon = React.useMemo(() => comingSoonHere(filteredShelf), [filteredShelf])\n const elsewhere = React.useMemo(() => withAnotherModule(filteredShelf), [filteredShelf])\n // Search earns its place from a screenful up; below that it is a control that\n // filters a list you can already see whole.\n const searchable = addable.length + shelf.length > 6\n\n return (\n <Modal open={open} onOpenChange={onOpenChange}>\n <ModalContent size=\"2xl\">\n <ModalHeader>\n <ModalTitle>{t('connectors.add')}</ModalTitle>\n <ModalDescription>\n {t(scoped ? 'connectors.addSubtitleScoped' : 'connectors.addSubtitle')}\n </ModalDescription>\n </ModalHeader>\n\n {searchable && (\n <div className=\"relative\">\n <Search className=\"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground\" />\n <Input\n value={query}\n onChange={(e) => setQuery(e.target.value)}\n placeholder={t('connectors.search')}\n className=\"rounded-lg border-border bg-background pl-9\"\n />\n </div>\n )}\n\n <div className=\"-mx-1 max-h-[55vh] overflow-y-auto px-1\">\n {connectors === null && (\n <ul className=\"divide-y divide-border\" aria-hidden>\n {[0, 1, 2, 3, 4].map((i) => (\n <li key={i} className=\"flex items-center gap-3 py-3\">\n <Skeleton className=\"h-9 w-9 shrink-0 rounded-lg\" />\n <div className=\"flex-1 space-y-2\">\n <Skeleton className=\"h-4 w-32\" />\n <Skeleton className=\"h-3 w-56\" />\n </div>\n <Skeleton className=\"h-8 w-24 rounded-lg\" />\n </li>\n ))}\n </ul>\n )}\n\n {connectors !== null && filtered.length === 0 && filteredShelf.length === 0 && (\n <div className=\"py-8 text-center\">\n <p className=\"text-sm font-medium text-foreground\">\n {t(query ? 'connectors.noneFoundTitle' : 'connectors.addEmptyTitle')}\n </p>\n <p className=\"mx-auto mt-1 max-w-sm text-sm text-muted-foreground\">\n {query ? t('connectors.noneFound', { query }) : t('connectors.addEmptyBody')}\n </p>\n </div>\n )}\n\n {filtered.length > 0 && (\n <>\n {/* The heading earns its place only once there is a second list\n to tell this one apart from. */}\n {filteredShelf.length > 0 && <SectionHeading>{t('connectors.sectionInstalled')}</SectionHeading>}\n <ul className=\"divide-y divide-border\">\n {filtered.map((c) => (\n <CatalogRow key={c.id} connector={c} onSelect={onSelect} />\n ))}\n </ul>\n </>\n )}\n\n <ComingSoonSection integrations={soon} />\n <AvailableSection connectors={elsewhere} />\n </div>\n\n {connectors !== null && <AskForMore onAsked={() => onOpenChange(false)} />}\n </ModalContent>\n </Modal>\n )\n}\n\n/**\n * \"Não encontrou o que precisa?\" — routed through the app's own assistant.\n *\n * A draft rather than a sent message: only the person asking knows which\n * provider they mean, and the composer opens with the caret after the sentence.\n * With no assistant mounted this renders nothing, because the alternative is a\n * link to somewhere that cannot answer.\n */\nfunction AskForMore({ onAsked }: { onAsked: () => void }) {\n const { t } = useTranslation()\n const available = useConnectorsPanelAvailable()\n const setDraft = useChatStore((s) => s.setDraft)\n const setOpen = useChatStore((s) => s.setOpen)\n const openPanel = useRightRailStore((s) => s.openPanel)\n if (!available) return null\n\n return (\n <div className=\"flex flex-wrap items-center gap-2 border-t border-border pt-3 text-sm text-muted-foreground\">\n <span>{t('connectors.askMore')}</span>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={() => {\n setDraft(t('connectors.askMoreDraft'))\n openPanel('chat')\n setOpen(true)\n onAsked()\n }}\n className=\"inline-flex items-center gap-1.5 rounded-lg border border-border px-2.5 py-1 font-medium text-foreground transition-colors hover:bg-muted/50 text-[length:inherit]\"\n >\n <Sparkles className=\"h-3.5 w-3.5\" />\n {t('connectors.askMoreCta')}\n </Button>\n </div>\n )\n}\n\nfunction CatalogRow({\n connector,\n onSelect,\n}: {\n connector: UnifiedConnector\n onSelect: (connector: UnifiedConnector) => void\n}) {\n const category = categoryLabel(connector.category)\n\n return (\n <li>\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={() => onSelect(connector)}\n className=\"flex w-full items-center gap-3 py-3 text-left transition-colors hover:bg-muted/40 justify-start whitespace-normal text-[length:inherit] font-normal rounded-none\"\n >\n <ConnectorMark connector={connector} size=\"sm\" />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium text-foreground\">{connector.name}</span>\n {category && (\n <span className=\"rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground\">\n {category}\n </span>\n )}\n {connector.planes.map((p) => (\n <PlaneBadge key={p} plane={p} active={connector.activePlane === p} />\n ))}\n </div>\n {connector.description && (\n <p className=\"mt-0.5 line-clamp-1 text-xs text-muted-foreground\">{connector.description}</p>\n )}\n </div>\n <span className=\"shrink-0\">\n <StateChip state={connector.state} />\n </span>\n </Button>\n </li>\n )\n}\n\nfunction SectionHeading({ children }: { children: React.ReactNode }) {\n return (\n <h3 className=\"mt-4 pb-1 pt-3 text-[11px] font-semibold uppercase tracking-wide text-muted-foreground first:mt-0 first:pt-0\">\n {children}\n </h3>\n )\n}\n\n/**\n * \"Em breve\" — put on the shelf by a module this app HAS, and not built yet.\n *\n * The distinction earns its own section rather than a chip in the one below:\n * someone who has CRM and reads \"Kommo · requer o módulo CRM\" concludes the\n * screen is broken. What is missing here is the integration, not the module,\n * and only this list can say so.\n */\nexport function ComingSoonSection({ integrations }: { integrations: ShelfIntegration[] }) {\n const { t } = useTranslation()\n if (integrations.length === 0) return null\n\n return (\n <>\n <SectionHeading>{t('connectors.sectionSoon')}</SectionHeading>\n <p className=\"mb-1 text-xs text-muted-foreground\">{t('connectors.soonBody')}</p>\n <ul className=\"divide-y divide-border\">\n {integrations.map((row) => (\n <ShelfRow key={row.id} integration={row} note={t('connectors.soonNote')} />\n ))}\n </ul>\n </>\n )\n}\n\n/**\n * \"Disponíveis com outro módulo\" — what belongs to a module this build left out.\n *\n * Exported so it can be rendered on its own: the panel around it is a Radix\n * dialog, which renders into a portal and therefore into nothing at all under\n * `renderToStaticMarkup` — a test of the whole modal would pass by asserting\n * against an empty string.\n */\nexport function AvailableSection({ connectors }: { connectors: ShelfIntegration[] }) {\n const { t } = useTranslation()\n if (connectors.length === 0) return null\n\n return (\n <>\n <SectionHeading>{t('connectors.sectionOtherModule')}</SectionHeading>\n {/* Said once, above the rows, rather than repeated as a tooltip on a\n control that does not exist. */}\n <p className=\"mb-1 text-xs text-muted-foreground\">{t('connectors.otherModuleBody')}</p>\n <ul className=\"divide-y divide-border\">\n {connectors.map((c) => (\n <ShelfRow\n key={c.id}\n integration={c}\n note={t('connectors.requiresModule', { module: moduleLabel(t, c.moduleId) })}\n />\n ))}\n </ul>\n </>\n )\n}\n\n/**\n * A row on the shelf that cannot be connected from here.\n *\n * A `<li>` and not a `<button>`, on purpose: there is nothing behind it. The\n * module comes with a new version of the app — a tenant admin cannot install\n * one, no plan unlocks one, and there is no route to send them to. So the row\n * says why, in a sentence, and the way to ask is the assistant at the foot of\n * the panel.\n */\nfunction ShelfRow({ integration, note }: { integration: ShelfIntegration; note: string }) {\n const { t } = useTranslation()\n const category = categoryLabel(integration.category)\n\n return (\n <li className=\"flex items-center gap-3 py-3\">\n <ConnectorMark connector={integration} size=\"sm\" />\n <div className=\"min-w-0 flex-1\">\n <div className=\"flex flex-wrap items-center gap-2\">\n <span className=\"font-medium text-foreground\">{integration.name}</span>\n {category && (\n <span className=\"rounded-full border border-border px-2 py-0.5 text-[11px] text-muted-foreground\">\n {category}\n </span>\n )}\n {/* Only where it adds something: inside \"Em breve\" every row is, and\n a chip repeating the heading is noise. */}\n {integration.status === 'soon' && !integration.moduleInstalled && (\n <span className=\"rounded-full border border-dashed border-border px-2 py-0.5 text-[11px] text-muted-foreground\">\n {t('connectors.soonChip')}\n </span>\n )}\n </div>\n <p className=\"mt-0.5 text-xs text-muted-foreground\">{note}</p>\n </div>\n </li>\n )\n}\n\n/**\n * A module's name in the reader's language.\n *\n * The generated map carries the plugin id, not a label: a manifest's `name` is\n * usually built from the app's own config at runtime (`config.labels.pageTitle`)\n * and there is no pt-BR string to extract. Falling back to the id keeps a module\n * added tomorrow readable rather than blank; the admin suite asserts every id in\n * the map has a real label in both locales.\n */\nfunction moduleLabel(t: (key: string) => string, moduleId: string): string {\n const key = `modules.${moduleId}`\n const label = t(key)\n return label === key ? moduleId : label\n}\n\n/** Small trigger a screen can render next to its heading. */\nexport function AddConnectorButton({ onClick }: { onClick: () => void }) {\n const { t } = useTranslation()\n return (\n <Button\n variant=\"bare\"\n size=\"bare\"\n onClick={onClick}\n className=\"inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-primary px-3 py-1.5 text-sm font-medium text-primary-foreground hover:opacity-90\"\n >\n <Plus className=\"h-4 w-4\" />\n {t('connectors.add')}\n </Button>\n )\n}\n","import React from 'react'\nimport { Button, ConfirmDialog, PageHeaderActions, Skeleton } from '@fayz-ai/ui'\nimport { PageActions } from '../../plugins/PageActions'\nimport { Plus } from 'lucide-react'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { AddConnectorPanel } from './AddConnectorPanel'\nimport { ConnectorRow } from './ConnectorRow'\nimport { ConnectorDetail } from './ConnectorDetail'\nimport { openConnectorsPanel, useConnectorsPanelAvailable } from './ConnectorsPanel'\nimport { useConnectors } from './useConnectors'\nimport { filterConnectors, groupConnectors, type ConnectorFilter, type UnifiedConnector } from './model'\n\n/**\n * Settings → Conectores — the whole surface, in one list.\n *\n * Two things used to live apart: what an outside assistant had been granted\n * over this organization, and what the app itself reached out to. To the person\n * running the salon \"o Claude lê minha agenda\" and \"minha agenda vai pro Google\"\n * are the same kind of decision, so they are the same list. `direction` tells\n * them apart; a second screen would only hide half the answer.\n *\n * It is also the other half of consent: an approval you cannot find is an\n * approval you cannot withdraw. Everything granted is listed, and everything\n * listed can be revoked — from the same panel that explains what it does.\n */\nexport function ConnectorsTab() {\n const { t } = useTranslation()\n const { connectors, error, reload, revokeGrant, tenantReady } = useConnectors()\n const [adding, setAdding] = React.useState(false)\n const [selected, setSelected] = React.useState<UnifiedConnector | null>(null)\n const [filter, setFilter] = React.useState<ConnectorFilter>('all')\n const [failure, setFailure] = React.useState<string | null>(null)\n const [revoking, setRevoking] = React.useState<null | Parameters<typeof revokeGrant>[0]>(null)\n const assistantAvailable = useConnectorsPanelAvailable()\n\n // Connecting happens in the assistant's own drawer — the connector is a\n // capability of the agent, so the journey belongs next to it. This screen\n // stays the inventory: what is granted, and how to take it back. Apps with no\n // assistant mounted fall back to the sheet so the journey is never stranded.\n const openJourney = React.useCallback(\n (connector: UnifiedConnector) => {\n if (assistantAvailable) openConnectorsPanel(connector)\n else setSelected(connector)\n },\n [assistantAvailable],\n )\n\n const visible = React.useMemo(() => filterConnectors(connectors ?? [], filter), [connectors, filter])\n const groups = React.useMemo(() => groupConnectors(visible), [visible])\n\n // Keep the open panel in step with a reload — a connector that just connected\n // should say so without being reopened.\n React.useEffect(() => {\n if (!selected || !connectors) return\n const fresh = connectors.find((c) => c.id === selected.id)\n if (fresh && fresh !== selected) setSelected(fresh)\n if (!fresh) setSelected(null)\n }, [connectors])\n\n // No gate on the agent connection: the list and every connector's own screen\n // talk to the integration service; only the agent's tool grants need it.\n if (!tenantReady) {\n return <Empty title={t('connectors.noOrg')} body={t('connectors.noOrgBody')} />\n }\n\n return (\n <div className=\"space-y-4\">\n {/* Sem título próprio: a barra da shell já escreve \"Conectores\" — este\n <h2> era a mesma palavra uma linha abaixo. Fica a frase que explica a\n tela, e o botão sobe para a direita da barra, como em toda página. */}\n {/* PageHeaderActions is the PORTAL into the shell's header slot; PageActions\n decides what the controls look like. They compose — dropping the portal\n leaves the button rendered inline in the page body. */}\n <PageHeaderActions>\n <PageActions\n actions={[{ id: 'add-connector', label: t('connectors.add'), icon: Plus, intent: 'primary', onSelect: () => setAdding(true) }]}\n />\n </PageHeaderActions>\n\n <AddConnectorPanel\n open={adding}\n onOpenChange={setAdding}\n connectors={connectors}\n onSelect={(connector) => {\n setAdding(false)\n openJourney(connector)\n }}\n />\n\n {(error || failure) && (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/10 p-3 text-sm text-destructive\">\n {failure ?? error}\n </div>\n )}\n\n {(connectors?.length ?? 0) > 4 && <Filters value={filter} onChange={setFilter} />}\n\n {/* Skeleton rather than a spinner: the list's shape is known before its\n contents are, so showing that shape keeps the layout from jumping. */}\n {connectors === null && <ConnectionsSkeleton />}\n\n {connectors !== null && visible.length === 0 && (\n <Empty title={t('connectors.emptyTitle')} body={t('connectors.emptyBody')} />\n )}\n\n {/* Card surface, like every other panel: an outlined box with no fill was\n the page showing through its own list, and the rows had nothing to sit\n on once the page stopped being white. */}\n {visible.length > 0 && (\n <ul className=\"fayz-glass-surface divide-y divide-border overflow-hidden rounded-card border bg-card text-card-foreground shadow-sm\">\n {groups.map((group) => (\n <React.Fragment key={group.key}>\n {/* Only when there is more than one: a single heading over the\n whole list names nothing, it just adds a line to read. */}\n {groups.length > 1 && (\n <li\n className=\"bg-muted/30 px-4 py-1.5 text-[0.7rem] font-medium uppercase tracking-wider text-muted-foreground\"\n // A label, not an item: read as a list entry it would announce\n // one more connector than there are.\n role=\"presentation\"\n >\n {group.label}\n </li>\n )}\n {group.connectors.map((c) => (\n <ConnectorRow key={c.id} connector={c} onOpen={openJourney} />\n ))}\n </React.Fragment>\n ))}\n </ul>\n )}\n\n <ConnectorDetail\n connector={selected}\n open={!!selected}\n onOpenChange={(open) => !open && setSelected(null)}\n onChanged={reload}\n // Irreversible from the user's side, and it disconnects something that\n // may be in use right now — so it asks, and it names what it will cut.\n // In the product's dialog, not the browser's.\n onRevoke={(connector) => setRevoking(connector)}\n />\n <ConfirmDialog\n open={!!revoking}\n title={t('connectors.revoke')}\n description={revoking ? t('connectors.revokeConfirm', { name: revoking.name }) : undefined}\n variant=\"destructive\"\n confirmLabel={t('connectors.revoke')}\n onConfirm={async () => {\n const connector = revoking\n setRevoking(null)\n if (!connector) return\n try {\n await revokeGrant(connector)\n setSelected(null)\n } catch (e) {\n setFailure((e as Error).message)\n }\n }}\n onCancel={() => setRevoking(null)}\n />\n </div>\n )\n}\n\nconst FILTERS: ConnectorFilter[] = ['all', 'connected', 'agentic', 'sync']\n\nfunction Filters({ value, onChange }: { value: ConnectorFilter; onChange: (f: ConnectorFilter) => void }) {\n const { t } = useTranslation()\n return (\n <div className=\"flex flex-wrap gap-1.5\">\n {FILTERS.map((f) => (\n <Button\n variant=\"bare\"\n size=\"bare\"\n key={f}\n onClick={() => onChange(f)}\n className={\n 'rounded-full px-3 py-1 text-xs font-medium transition-colors ' +\n (f === value ? 'bg-primary text-primary-foreground' : 'bg-muted text-muted-foreground hover:bg-muted/70')\n }\n >\n {t(`connectors.filter.${f}`)}\n </Button>\n ))}\n </div>\n )\n}\n\nfunction ConnectionsSkeleton() {\n return (\n <ul className=\"fayz-glass-surface divide-y divide-border overflow-hidden rounded-card border bg-card text-card-foreground shadow-sm\" aria-hidden>\n {[0, 1].map((i) => (\n <li key={i} className=\"flex items-start gap-4 p-4\">\n <Skeleton className=\"h-10 w-10 shrink-0 rounded-lg\" />\n <div className=\"min-w-0 flex-1 space-y-2 py-0.5\">\n <Skeleton className=\"h-4 w-40\" />\n <Skeleton className=\"h-3 w-64\" />\n </div>\n <Skeleton className=\"h-8 w-28 shrink-0 rounded-lg\" />\n </li>\n ))}\n </ul>\n )\n}\n\nfunction Empty({ title, body }: { title: string; body: string }) {\n return (\n <div className=\"rounded-xl border border-dashed border-border p-8 text-center\">\n <p className=\"font-medium text-foreground\">{title}</p>\n <p className=\"mt-1 text-sm text-muted-foreground\">{body}</p>\n </div>\n )\n}\n","import React from 'react'\nimport { toast } from '../notifications/ToastProvider'\nimport { useTranslation } from '../../hooks/useTranslation'\nimport { usePluginRuntimeOptional } from '@fayz-ai/core'\nimport { openConnectorsPanel } from './ConnectorsPanel'\nimport { refreshConnectors } from './useConnectors'\n\n/**\n * Coming back from a provider's consent screen.\n *\n * The callback redirects to the app's ORIGIN with a marker in the query string\n * and whatever route the person left from in the hash:\n *\n * http://localhost:5301/?googleCalendar=connected#/settings/connectors\n *\n * Nothing read that marker, so the return was indistinguishable from a cold page\n * load. Someone authorized Google, waited, and arrived at a list — with no\n * confirmation that it worked and no sign of where the calendars are mapped.\n *\n * Reading it is the whole fix: raise the assistant on that connector, say\n * whether the grant landed, and clean the marker out of the URL so a refresh\n * does not replay it.\n *\n * The marker is per-connector because the callbacks are: `google-calendar`'s\n * function has always written `googleCalendar=connected|error`, and it is a\n * deployed edge function serving a live clinic (FAY-1379), so the app reads the\n * convention that exists rather than asking the function to change. New\n * connectors should use the generic pair below instead.\n */\n\n/** The generic form, for callbacks that have no legacy to keep. */\nconst CONNECTOR_PARAM = 'fayzConnector'\nconst STATUS_PARAM = 'fayzConnectorStatus'\n\n/**\n * Per-connector markers. An allow-list rather than a rule that de-camelises any\n * `?x=connected`: this hook runs on every page load of every app, and a stray\n * query param from anywhere must not be able to throw the assistant open.\n */\nconst LEGACY_PARAMS: Record<string, string> = {\n googleCalendar: 'google-calendar',\n}\n\n/**\n * Every reason the platform's redirect route can give for a failure.\n *\n * A closed set, and an allow-list rather than a formatting rule: the value\n * arrives in a query string anyone can type, and it is about to select a\n * sentence shown to a shop owner. A slug that is not on this list is not\n * rendered at all — `token_exchange_failed` on a merchant's screen is noise\n * either way, and an arbitrary string from the URL bar would be worse.\n */\nexport const OAUTH_FAILURE_REASONS = [\n 'config_missing',\n 'invalid_state',\n 'expired_state',\n 'not_a_member',\n 'provider_denied',\n 'missing_code',\n 'token_exchange_failed',\n 'token_incomplete',\n 'store_failed',\n 'unexpected',\n] as const\n\nexport type ConnectorOAuthFailureReason = (typeof OAUTH_FAILURE_REASONS)[number]\n\nconst REASON_SET: ReadonlySet<string> = new Set<string>(OAUTH_FAILURE_REASONS)\n\nexport interface ConnectorOAuthReturn {\n connectorId: string\n status: 'connected' | 'error'\n /**\n * The platform's own verdict, from {@link OAUTH_FAILURE_REASONS}. Generic\n * callbacks only, and never rendered as-is — see {@link oauthFailureMessage}.\n */\n reason?: ConnectorOAuthFailureReason\n /**\n * The provider's own words, when a legacy per-connector callback passed any.\n *\n * Kept apart from `reason` because they are different kinds of thing: the\n * calendar function has always written prose a person can read (\"acesso\n * negado\"), and collapsing the two would either print a slug or throw away a\n * sentence that was already in the reader's language.\n */\n message?: string\n}\n\n/** What the callback said, or null when this is an ordinary page load. */\nexport function readConnectorOAuthReturn(search: string): ConnectorOAuthReturn | null {\n let params: URLSearchParams\n try {\n params = new URLSearchParams(search)\n } catch {\n return null\n }\n\n const generic = params.get(CONNECTOR_PARAM)\n if (generic) {\n const status = params.get(STATUS_PARAM)\n if (status !== 'connected' && status !== 'error') return null\n const raw = params.get(`${CONNECTOR_PARAM}Message`) ?? ''\n return {\n connectorId: generic,\n status,\n reason: REASON_SET.has(raw) ? (raw as ConnectorOAuthFailureReason) : undefined,\n }\n }\n\n for (const [param, connectorId] of Object.entries(LEGACY_PARAMS)) {\n const status = params.get(param)\n if (status !== 'connected' && status !== 'error') continue\n return { connectorId, status, message: params.get(`${param}Message`) ?? undefined }\n }\n\n return null\n}\n\n/** Every query key this module owns — what has to leave the URL once it is read. */\nexport function oauthReturnParams(): string[] {\n const keys = [CONNECTOR_PARAM, STATUS_PARAM, `${CONNECTOR_PARAM}Message`]\n for (const param of Object.keys(LEGACY_PARAMS)) keys.push(param, `${param}Message`)\n return keys\n}\n\n/**\n * The same URL with the markers gone.\n *\n * The hash is preserved untouched — it is the route the person was on before\n * they left for Google, and losing it would land them somewhere else after a\n * successful grant.\n */\nexport function urlWithoutOAuthReturn(href: string): string {\n const url = new URL(href)\n for (const key of oauthReturnParams()) url.searchParams.delete(key)\n return url.toString()\n}\n\n/**\n * What to tell the person, in their language.\n *\n * Three sources, in order of how much they know: the platform's slug becomes a\n * translated sentence; a legacy callback's prose is already a sentence and is\n * passed through; anything else is the honest generic failure. The second\n * `t(key) !== key` guard is belt and braces — a slug that reached the closed set\n * before someone wrote its copy must still not print as `store_failed`.\n */\nexport function oauthFailureMessage(\n t: (key: string) => string,\n result: Pick<ConnectorOAuthReturn, 'reason' | 'message'>,\n): string {\n if (result.reason) {\n const key = `connectors.oauth.error.${result.reason}`\n const translated = t(key)\n if (translated && translated !== key) return translated\n }\n return result.message || t('connectors.oauth.failed')\n}\n\n/**\n * Mounted once, in the shell: a consent screen can return to any route.\n *\n * The marker is consumed exactly once — `replaceState` strips it before the\n * panel opens, so a refresh is a refresh and not a second \"conectado\".\n */\nexport function useConnectorOAuthReturn(): void {\n const { t } = useTranslation()\n const runtime = usePluginRuntimeOptional()\n React.useEffect(() => {\n if (typeof window === 'undefined') return\n const result = readConnectorOAuthReturn(window.location.search)\n if (!result) return\n\n window.history.replaceState(null, '', urlWithoutOAuthReturn(window.location.href))\n\n if (result.status === 'connected') {\n toast.success(t('connectors.oauth.returned'))\n // The credential landed in the platform; the pool row is the app's half\n // of the same fact, and nothing else writes it. Without this the\n // connector keeps reporting \"not connected\" — the person authorizes at\n // the provider, comes back, sees the button again, and clicks forever.\n void completeConnection(runtime, result.connectorId)\n } else {\n toast.error(oauthFailureMessage(t, result))\n }\n\n // Open it either way. A grant that failed is exactly when someone needs the\n // connector's own screen, with the Conectar button on it.\n openConnectorsPanel({ id: result.connectorId })\n }, [])\n}\n\n/**\n * Mark the connection live on this side of the line.\n *\n * `saveConnection` with no values is the connector's own \"the authorization is\n * done\" — the same call the credential path makes after the sink accepts a key,\n * which is why this needs no new hook in the contract.\n *\n * It trusts the marker in the URL, and that is a known weakness rather than an\n * oversight: a crafted link could flip a row to active with no grant behind it.\n * The blast radius is a status that lies until the first sync fails, not access\n * to anything — but the honest fix is for the app to ask the platform whether a\n * credential exists instead of believing a query string. FAY-1402.\n */\nasync function completeConnection(\n runtime: ReturnType<typeof usePluginRuntimeOptional>,\n connectorId: string,\n): Promise<void> {\n const definitions = [...(runtime?.connectorsByHost?.values() ?? [])].flat()\n const definition = definitions.find((d) => d.id === connectorId)\n if (!definition?.saveConnection) return\n try {\n await definition.saveConnection({} as never)\n } finally {\n // Even a failure should re-read: the row may have been written and the\n // error be about something else entirely.\n refreshConnectors()\n }\n}\n","import React from 'react'\nimport { CheckCircle2, Clock, Loader2, XCircle } from 'lucide-react'\nimport type { ConnectorDelivery } from '@fayz-ai/core'\nimport { formatRelative } from './when'\nimport { useTranslation } from '../../hooks/useTranslation'\n\n/**\n * Record by record: what reached the provider and what did not.\n *\n * A run says \"12 de 20 enviados\", which is the number that cannot answer the\n * question actually being asked — *cadastrei este pedido, foi?*. Same rows, read\n * from the link table the push writes.\n */\nconst ICON: Record<ConnectorDelivery['status'], { Icon: typeof CheckCircle2; className: string; label: string }> = {\n delivered: { Icon: CheckCircle2, className: 'text-success', label: 'Enviado' },\n pending: { Icon: Clock, className: 'text-muted-foreground', label: 'Na fila' },\n failed: { Icon: XCircle, className: 'text-destructive', label: 'Não foi' },\n}\n\nexport function ConnectorDeliveries({\n load,\n providerName,\n limit = 10,\n}: {\n load(options?: { limit?: number }): Promise<ConnectorDelivery[]>\n providerName: string\n limit?: number\n}) {\n const { t } = useTranslation()\n const [rows, setRows] = React.useState<ConnectorDelivery[] | null>(null)\n\n React.useEffect(() => {\n let cancelled = false\n void load({ limit })\n .then((r) => { if (!cancelled) setRows(r) })\n .catch(() => { if (!cancelled) setRows([]) })\n return () => { cancelled = true }\n }, [load, limit])\n\n if (rows === null) {\n return (\n <p className=\"flex justify-center py-4\">\n <Loader2 className=\"h-4 w-4 animate-spin text-muted-foreground\" />\n </p>\n )\n }\n\n if (rows.length === 0) {\n return (\n <p className=\"rounded-lg border border-dashed border-border p-3 text-xs text-muted-foreground\">\n Nada foi enviado ainda para o {providerName}.\n </p>\n )\n }\n\n return (\n <ul className=\"divide-y divide-border overflow-hidden rounded-lg border border-border\">\n {rows.map((row, index) => {\n const { Icon, className, label } = ICON[row.status] ?? ICON.pending\n return (\n <li key={row.subjectId ?? `${row.subject}-${index}`} className=\"flex items-start gap-2 px-3 py-2\">\n <Icon className={`mt-0.5 h-3.5 w-3.5 shrink-0 ${className}`} aria-hidden />\n <span className=\"sr-only\">{label}</span>\n <div className=\"min-w-0 flex-1\">\n <p className=\"text-xs font-medium\">\n {row.subject}\n {row.externalId && (\n <span className=\"ml-1.5 font-normal text-muted-foreground\">\n → {providerName} #{row.externalId}\n </span>\n )}\n </p>\n {row.detail && <p className=\"text-[11px] leading-relaxed text-muted-foreground\">{row.detail}</p>}\n </div>\n {row.at && (\n <span className=\"shrink-0 text-[11px] tabular-nums text-muted-foreground\">\n {formatRelative(row.at, t)}\n </span>\n )}\n </li>\n )\n })}\n </ul>\n )\n}\n","import { getActiveTenantId } from '@fayz-ai/core'\nimport type { ConnectorDefinition } from '@fayz-ai/core'\nimport { loadConnectorStatuses } from './connector-status'\nimport { loadCatalog } from './useConnectors'\nimport { buildConnectorList, shelfIntegrations } from './model'\nimport type { ShelfIntegration, UnifiedConnector } from './model'\n\n/**\n * The connectors list, resolved outside React.\n *\n * `useConnectors` is the hook the screens render from; this is the same three\n * sources through the same two builders, for a caller with no component to\n * mount — the assistant's `findConnectors` executor. Sharing the builders is\n * what keeps the tool and the screen from ever disagreeing: if this returned a\n * list of its own the whole feature would be the bug it was written to fix.\n *\n * Both underlying loads are already shared — the catalogue is one flight per\n * session, the statuses one batched read per tenant — so a tool call made while\n * the screen is open costs nothing extra.\n *\n * Inbound grants are left out, deliberately. A granted external assistant is\n * something the org approved, not an integration someone is shopping for, and\n * fetching them needs an authenticated round trip this path has no reason to\n * make.\n */\nexport interface ConnectorIndex {\n connectors: UnifiedConnector[]\n shelf: ShelfIntegration[]\n}\n\nexport async function loadConnectorIndex(input: {\n definitions: ConnectorDefinition[]\n /** Plugin ids mounted in this build — what tells \"em breve\" from \"outro módulo\". */\n installedModules: string[]\n /** Defaults to the active tenant — the same id the screen's statuses key on. */\n tenantId?: string\n}): Promise<ConnectorIndex> {\n const [installed, catalog] = await Promise.all([\n loadConnectorStatuses(input.definitions, input.tenantId ?? getActiveTenantId()),\n loadCatalog(),\n ])\n const connectors = buildConnectorList({ installed, catalog })\n const shelf = shelfIntegrations({\n present: connectors,\n installedModules: input.installedModules,\n catalog,\n })\n return { connectors, shelf }\n}\n","import { CATEGORY_LABELS, connectorRoute } from './model'\nimport type { ConnectorPlane, ConnectorState, ShelfIntegration, UnifiedConnector } from './model'\n\n/**\n * \"Queria que tivesse pagamento com a appmax.\"\n *\n * The assistant answered that it could not help integrate specific payment\n * providers — while AppMax sat on the other half of the screen marked *pronto\n * para conectar*. It was not wrong about its own tools; it had no way to read\n * the list. This module is that way, and it is the SAME list: the inputs are\n * whatever `buildConnectorList` and `shelfIntegrations` already produced for the\n * screen, so a second answer is impossible by construction. Nothing here fetches\n * anything, and nothing here holds a provider name of its own.\n *\n * What it adds is the reading: a person asks for a *need* (\"quero receber por\n * Pix\", \"preciso emitir nota fiscal\") far more often than for a slug, and the\n * data already carries the category that answers it.\n */\n\n/**\n * The honest answers, and the difference between them is what the person can do\n * next:\n *\n * - `connected` / `needs_setup` / `ready` — every {@link ConnectorState}: there\n * is a screen to go to. Only these.\n * - `soon` — a module this app HAS declared it; no implementation exists.\n * - `needs_module` — it belongs to a module this app was not built with, and a\n * tenant admin cannot install one (`useTenantPlugins` reads, it never\n * activates). Offering a button here would be a promise nobody can keep.\n *\n * DERIVED from `ConnectorState`, not re-typed alongside it. The two vocabularies\n * met when the assistant learned to read this list, and the meeting has to be a\n * fact about the types: `fromConnector` assigns the screen's state straight\n * across, and \"the tool's answer and the connectors screen never disagree\" stops\n * being something a test hopes for. The `+ 2` is the whole difference — the\n * shelf holds rows the screen expresses as absence, and those are the two the\n * assistant must not offer a door to.\n *\n * The forcing function is {@link STATE_RANK}: the next member `ConnectorState`\n * grows is a compile error here, where somebody has to decide whether the\n * assistant may offer it. `needs_setup` arrived exactly that way.\n */\nexport type ConnectorSuggestionState = ConnectorState | 'soon' | 'needs_module'\n\nexport interface ConnectorSuggestion {\n slug: string\n /** Row key for the journey panel — the connector id, when one backs it. */\n id?: string\n name: string\n description?: string\n /** Raw `ConnectorCategory`; the reader-facing label is resolved through i18n. */\n category?: string\n icon?: string\n logoUrl?: string\n state: ConnectorSuggestionState\n /** Plugin that hosts (or would host) it — what \"requer o módulo X\" names. */\n moduleId?: string\n planes?: ConnectorPlane[]\n /** The screen a human finishes it on. Present exactly when {@link hasDestination}, and NOWHERE else. */\n route?: string\n score: number\n}\n\n/**\n * Rank a state when two rows score the same: **what needs a decision first**,\n * then closest to done.\n *\n * `needs_setup` leads, and it is the same order the connectors list sorts by\n * (`model.ts` STATE_RANK) — deliberately, because a person who asks \"quero\n * receber por Pix\" about a gateway that is connected with no method chosen is\n * looking at the one row that will not work, and answering \"já está conectado\"\n * there is the failure this whole area exists to stop.\n */\nconst STATE_RANK: Record<ConnectorSuggestionState, number> = {\n needs_setup: 0,\n connected: 1,\n ready: 2,\n soon: 3,\n needs_module: 4,\n}\n\n/**\n * Words that carry a NEED, mapped to the category that answers it.\n *\n * Not a provider list — that would be the second hardcoded list this whole\n * design exists to avoid. It maps the user's vocabulary onto the taxonomy the\n * connectors already declare, so a provider added tomorrow is found by \"quero\n * receber por Pix\" without anyone touching this file.\n */\nconst NEED_CATEGORIES: Record<string, string[]> = {\n payments: [\n 'pagamento', 'pagamentos', 'pagar', 'pagto', 'receber', 'recebimento', 'recebe',\n 'cobranca', 'cobrar', 'checkout', 'pix', 'cartao', 'credito', 'debito', 'boleto',\n 'parcelado', 'parcelamento', 'gateway', 'payment', 'payments', 'pay', 'card', 'billing',\n ],\n logistics: [\n 'frete', 'fretes', 'entrega', 'entregas', 'envio', 'envios', 'transportadora',\n 'correios', 'logistica', 'rastreio', 'shipping', 'delivery', 'logistics',\n ],\n erp: ['nota', 'notas', 'fiscal', 'nfe', 'nfse', 'nfce', 'danfe', 'erp', 'faturamento', 'invoice'],\n banking: ['banco', 'bancaria', 'bancario', 'conta', 'extrato', 'conciliacao', 'openbanking', 'banking'],\n crm: ['crm', 'lead', 'leads', 'funil', 'pipeline', 'prospect'],\n scheduling: ['agenda', 'agendamento', 'calendario', 'calendar', 'scheduling', 'horario'],\n messaging: ['whatsapp', 'mensagem', 'mensagens', 'sms', 'messaging', 'zap'],\n marketplace: ['marketplace', 'marketplaces'],\n ecommerce: ['loja', 'ecommerce', 'carrinho', 'vitrine', 'storefront'],\n analytics: ['analytics', 'analise', 'metricas', 'metrica', 'dados'],\n local: ['mapa', 'mapas', 'local', 'maps'],\n ai: ['inteligencia'],\n automation: ['automacao', 'automacoes', 'webhook', 'automation', 'zapier'],\n courses: ['curso', 'cursos', 'aluno', 'alunos'],\n database: ['database'],\n}\n\n/** Filler a request is made of; keeping them would match every description. */\nconst STOPWORDS = new Set([\n 'que', 'com', 'para', 'pra', 'por', 'uma', 'uns', 'umas', 'dos', 'das', 'nos', 'nas',\n 'quero', 'queria', 'gostaria', 'preciso', 'precisa', 'tivesse', 'tem', 'ter', 'tenho',\n 'como', 'onde', 'qual', 'quais', 'sobre', 'meu', 'minha', 'meus', 'minhas', 'aqui',\n 'the', 'and', 'for', 'with', 'want', 'need', 'have', 'can', 'app', 'usar', 'fazer',\n 'integrar', 'integracao', 'integracoes', 'conectar', 'conexao', 'ligar', 'instalar',\n])\n\n/** Lowercase, accent-free — \"cartão\" and \"cartao\" are the same request. */\nfunction fold(value: string): string {\n return value\n .normalize('NFD')\n .replace(/[\\u0300-\\u036f]/g, '')\n .toLowerCase()\n .trim()\n}\n\ninterface ParsedQuery {\n raw: string\n terms: string[]\n categories: Set<string>\n}\n\nexport function parseConnectorQuery(query: string): ParsedQuery {\n const raw = fold(query)\n const terms = raw\n .split(/[^a-z0-9]+/)\n .filter((term) => term.length >= 3 && !STOPWORDS.has(term))\n const categories = new Set<string>()\n for (const [category, words] of Object.entries(NEED_CATEGORIES)) {\n // Whole words only. A substring test read \"contador\" as \"conta\" and offered\n // a bank connector to someone talking about their accountant.\n if (words.some((word) => terms.includes(word))) categories.add(category)\n }\n // \"nota fiscal\" is two ordinary words; only together do they mean ERP.\n if (raw.includes('nota fiscal')) categories.add('erp')\n return { raw, terms, categories }\n}\n\n/** What a row offers the matcher, whether it is a connection or a shelf row. */\ninterface Matchable {\n slug: string\n name: string\n description?: string\n category?: string\n}\n\nfunction score(row: Matchable, query: ParsedQuery): number {\n if (!query.raw) return 0\n const name = fold(row.name)\n const slug = fold(row.slug)\n const description = fold(row.description ?? '')\n const category = row.category ?? ''\n // The category's reader-facing word (\"Pagamentos\") is a term people type.\n const categoryWord = fold(CATEGORY_LABELS[category as keyof typeof CATEGORY_LABELS] ?? category)\n\n let total = 0\n // Asked for by name — the strongest signal there is, and the founder's case.\n if (name === query.raw || slug === query.raw) total += 120\n else if (query.raw.includes(name) || name.includes(query.raw)) total += 80\n else if (query.terms.some((term) => term === name || term === slug)) total += 70\n else if (query.terms.some((term) => term.length >= 4 && (name.includes(term) || slug.includes(term)))) total += 50\n\n // Asked for by need. The category is what makes \"quero receber por Pix\" reach\n // a gateway whose description never says \"receber\".\n if (category && query.categories.has(category)) total += 45\n if (categoryWord && query.terms.includes(categoryWord)) total += 30\n if (description && query.terms.some((term) => description.includes(term))) total += 25\n\n return total\n}\n\n/** Everything the two screens render, projected onto one shape. */\nfunction fromConnector(connector: UnifiedConnector): ConnectorSuggestion {\n return {\n slug: connector.slug,\n id: connector.id,\n name: connector.name,\n description: connector.description,\n category: connector.category,\n icon: connector.icon,\n logoUrl: connector.logoUrl,\n state: connector.state,\n moduleId: connector.hostPluginId,\n planes: connector.planes,\n // The one place a path is built, and it is the screen's own helper.\n route: connectorRoute(connector),\n score: 0,\n }\n}\n\nfunction fromShelf(row: ShelfIntegration): ConnectorSuggestion {\n return {\n slug: row.slug,\n name: row.name,\n description: row.description,\n category: row.category,\n icon: row.icon,\n logoUrl: row.logoUrl,\n // Same split the panel renders: `moduleInstalled` is what tells \"em breve\"\n // from \"requer outro módulo\", not `status`.\n state: row.moduleInstalled ? 'soon' : 'needs_module',\n moduleId: row.moduleId,\n planes: row.planes,\n score: 0,\n }\n}\n\n/**\n * What this app can be connected to, for a need stated in the user's words.\n *\n * `connectors` and `shelf` come straight from the screen's own builders. A row\n * the screen would not show cannot appear here, and — the point of #89 — a\n * provider that exists only as a platform catalogue entry appears in neither.\n */\nexport function searchConnectors(input: {\n connectors: UnifiedConnector[]\n shelf: ShelfIntegration[]\n query: string\n limit?: number\n}): ConnectorSuggestion[] {\n const query = parseConnectorQuery(input.query)\n if (!query.raw) return []\n\n const rows = [\n ...input.connectors.map(fromConnector),\n ...input.shelf.map(fromShelf),\n ]\n\n return rows\n .map((row) => ({ ...row, score: score(row, query) }))\n .filter((row) => row.score > 0)\n .sort(\n (a, b) =>\n b.score - a.score ||\n STATE_RANK[a.state] - STATE_RANK[b.state] ||\n a.name.localeCompare(b.name),\n )\n .slice(0, input.limit ?? 4)\n}\n\n/**\n * Whether this answer is one the connectors screen itself holds — and therefore\n * one with a screen to go to.\n *\n * A type guard and not a boolean, because the narrowing is the statement: the\n * suggestion states that have a destination are **exactly** `ConnectorState`,\n * and the two that do not are exactly the shelf's. Everything downstream that\n * needs a real `ConnectorState` (the `StateChip` on the card) gets it from here\n * instead of casting, so a state added to either side cannot slip through as a\n * widened union that happens to compile.\n *\n * `switch` and not a list, so that addition is a compile error rather than a\n * silent `false`.\n */\nexport function isConnectorState(state: ConnectorSuggestionState): state is ConnectorState {\n switch (state) {\n case 'connected':\n case 'needs_setup':\n case 'ready':\n return true\n case 'soon':\n case 'needs_module':\n return false\n }\n}\n\n/**\n * Only a real destination gets a button. Asserted, not assumed.\n *\n * Renamed from `canConnectNow` when `needs_setup` arrived: that row is one a\n * person should absolutely be sent to, and \"can connect now\" is precisely what\n * is NOT true of it — it is connected, and what is missing is the\n * configuration. This boolean goes on the wire and is read by a model, so the\n * name is not decoration.\n */\nexport function hasDestination(suggestion: Pick<ConnectorSuggestion, 'state'>): boolean {\n return isConnectorState(suggestion.state)\n}\n"]}
|