loopable / web /src /connectors /ConnectorModal.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
3e19b1e verified
Raw History Blame Contribute Delete
65.2 kB
// --------------------------------------------------------------------------- // connectors/ConnectorModal.tsx β€” W49-T12, ruling R26, contract C4. // // ⭐⭐ R26, verbatim: *"The connector popup is a centered MODAL with tabs Overview, // Keychain, Databases, Relationships, opened from the card. The Keychain moves // INTO it and Settings > Keychains becomes a link to the modal (one door). Field // enablement moves into the Databases tab."* // // Overview and Setup are the only tabs. Retired keys open Setup. // The C7 status reader stays mounted independently of the paged detail read. // // β›” NO REUSABLE MODAL COMPONENT EXISTS IN THIS REPO. `CustomerGrid.tsx`'s // `LinkGridModal` owns the portal-plus-focus-trap pattern and is NOT exported, so // it is READ as the model and never imported. What IS shared is the layer // contract underneath it, `customer-grid/OverlaySurface`, which already carries // the four behaviours the done-when names: focus trap, Escape, outside-pointer // dismiss, and focus restored to whatever was focused when the overlay mounted. // Re-implementing those here would be a second answer to one question. // // β›”β›” TWO TRAPS, BOTH PAID FOR ALREADY, BOTH RESOLVED IN `styles/wave49/connectors.css`: // (a) a portalled overlay paints its OWN background, or it renders transparent // over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]); // (b) z-order is a THREE-WAY order, so the modal sits on the DIALOG step // (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it // ([[z-layering-is-a-three-way-order]]). Tokens, never a number. // // ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law, and this directory's // own header). `status` and `scope` arrive as STRINGS: a state the server adds // later renders in the neutral tone instead of dropping the panel. // --------------------------------------------------------------------------- import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT } from "../apiContract"; import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface"; import { ConfirmDialog } from "../ui/ConfirmDialog"; import { brandForConnector } from "./brandMarks"; import DatabasesTab, { parseDatabaseSyncHealth, useSyncNow } from "./DatabasesTab"; import type { SyncNowReceipt } from "./DatabasesTab"; import type { MaterializationCapability } from "./materializationJobs"; import "../styles/wave58/connectors.css"; import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab"; import KeychainTab, { amazonRotationNotice, RotationNotice, useRotationClock } from "./KeychainTab"; import MonidRunDialog from "./MonidRunDialog"; import AmazonDeletionNotice from "./AmazonDeletionNotice"; import AmazonWritesSwitch from "./AmazonWritesSwitch"; import { OdooSyncEvery } from "./OdooConfig"; import { AmazonSyncOverview, ConnectorSyncStatusLine, useConnectorSyncStatus, tileText } from "./ConnectorsPage"; import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage"; import { parseRelationshipGraph } from "./ConnectorsPage"; import "../styles/wave49/connectors.css"; import "../styles/wave52/connectors.css"; import "../styles/wave55/connectors.css"; import "../styles/wave59/connectors.css"; import "../styles/sdlc74/connectors.css"; import "../styles/sdlc80/connector-setup.css"; import "../styles/sdlc81/connectors-type.css"; /** Retired tab keys remain aliases for existing deep links to Setup. */ export type ConnectorTab = "overview" | "setup" | "keychain" | "databases" | "relationships" | "cadence"; export function connectorTab(tab: ConnectorTab): "overview" | "setup" { return tab === "overview" ? "overview" : "setup"; } /** Every connector keeps the same two tabs. */ export function connectorTabs( _row: ConnectorRow ): ReadonlyArray<{ key: ConnectorTab; label: string }> { return [ { key: "overview", label: "Overview" }, { key: "setup", label: "Setup" }, ]; } interface ConnectorSyncCapability { provider: string; supported: boolean; syncNow: ConnectorDetail["syncNow"]; } /** Discover sync support without reading database pages or duplicating the provider registry. */ function useConnectorSyncCapability(connectorKey: string, refreshKey: number, directoryRow: ConnectorRow) { const identity = JSON.stringify([connectorKey, refreshKey]); const [reading, setReading] = useState<{ identity: string; capability: ConnectorSyncCapability | null; problem: string; } | null>(null); useEffect(() => { const controller = new AbortController(); void (async () => { try { const response = await fetch(`${API_V1}/connectors/${encodeURIComponent(connectorKey)}/sync-capability`, { credentials: CREDENTIALS, signal: controller.signal, }); const body = obj(await response.json().catch(() => null)); if (controller.signal.aborted) return; if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); if (!response.ok || body.provider !== connectorKey || typeof body.supported !== "boolean") { throw new Error("Sync status unavailable."); } const now = obj(body.syncNow); setReading({ identity, problem: "", capability: { provider: connectorKey, supported: body.supported, syncNow: body.supported && now.provider === connectorKey && now.path === `/connectors/${connectorKey}/sync/now` ? { provider: connectorKey, path: now.path } : null } }); } catch { if (!controller.signal.aborted) setReading({ identity, capability: null, problem: "Sync status unavailable." }); } })(); return () => controller.abort(); }, [connectorKey, identity, refreshKey]); const current = reading?.identity === identity ? reading : null; const declaredSupport = obj(directoryRow).syncSupported; // Directory support starts a fresh read. Only this open's capability response grants Sync now. const declaredCapability: ConnectorSyncCapability | null = directoryRow.key === connectorKey && typeof declaredSupport === "boolean" ? { provider: connectorKey, supported: declaredSupport, syncNow: null } : null; return { capability: current ? current.capability : declaredCapability, problem: current?.problem ?? "" }; } /** Only a server-declared sync provider mounts the C7 reader. */ function ConnectorOverviewSyncStatus({ connectorKey, refreshKey, onReady }: { connectorKey: string; refreshKey: number; onReady?: (connectorKey: string, refreshKey: number) => void; }) { const sync = useConnectorSyncStatus(connectorKey, undefined, refreshKey); useEffect(() => { if (sync.status || sync.problem) onReady?.(connectorKey, refreshKey); }, [connectorKey, refreshKey, onReady, sync.status, sync.problem]); return <ConnectorSyncStatusLine status={sync.status} problem={sync.problem} />; } export interface ConnectorOverview { key: string; label: string; /** The server's own word for the state. Read as a string, never a union. */ status: string; account: string; source: string; creates: string[]; /** Connection health is independent of the current database cursor page. */ syncHealth?: unknown; } export interface ConnectorKeychainEntry { id: string; connectionId?: string; type?: string; slot?: number; status?: string; label: string; /** The masked preview, or "" when this reader is not allowed one (R4). */ masked: string; scope: string; testable: boolean; /** Server-owned admin permission for the write-only replacement flow. */ replaceable: boolean; /** Public Amazon-issued timestamp, empty or absent when unknown. Never a credential field. */ client_secret_rotation_deadline?: string; } /** * What the Connect form must ask for, and what the server will accept. * * ⭐ AN ADDITION TO C4's `keychain` HALF, and the alternative is worse: the contract pins * `entries`, `canConnect` and `canDisconnect` but says nothing about where a form gets its * fields, and the only other answer is a client-side `type -> fields` map β€” a second copy of a * credential shape that already lives in the connector layer. */ export interface ConnectorConnectField { key: string; label: string; /** Renders as a password box, and is never echoed back. */ secret: boolean; default?: string; } export interface ConnectorConnectSpec { /** The keychain entry type this connector stores, in the server's own word. */ type: string; fields: ConnectorConnectField[]; /** The scopes THIS reader may choose, already narrowed by R4 and by `TENANT_WIDE_TYPES`. */ scopes: string[]; tenantWide: boolean; defaultLabel?: string; } export interface ConnectorKeychainHalf { entries: ConnectorKeychainEntry[]; canConnect: boolean; canDisconnect: boolean; migrationPending?: boolean; /** `null` when this connector has no credential door at all (Webhooks, the Scraper, OAuth). */ connect: ConnectorConnectSpec | null; } export interface ConnectorDatabaseField { key: string; label: string; type: string; /** C4 spells this `source_field` on the wire; the client speaks camelCase. */ sourceField: string; enabled: boolean; } export interface ConnectorDatabaseExclusion { sourceField: string; reason: string; } export interface ScraperRecipe { kind: string; source: string; seed: string | { search: string; geography: string }; limits: { posts?: number; postType?: string; records?: number }; schedule: { mode: string }; } export interface ScraperRunReceipt { id: string; state: string; provider: string; rows: number; startedAt: string; finishedAt: string; estimatedUsd: number; costCapUsd: number; note: string; } export interface ConnectorDatabase { key: string; identity?: { provider: string; connectionId: string; databaseKey: string; model: string }; /** * What this database is CALLED today: the tenant's override when there is one, our shipped * default otherwise. Resolved on the server (`core/schema_overlay.database_label`), never here. */ label: string; /** * ⭐⭐ W53-T27 Β· R9 / C2 β€” THREE NAMES, THREE DIFFERENT FACTS, AND THE TAB SHOWS ALL THREE. * * `native` is the VENDOR's own identifier for the table (`res.partner`, or an Amazon report * type). It is never editable by anybody: it is how the source names its own thing, and a * workspace that could rewrite it would be describing a table that does not exist over there. */ native: string; /** OUR shipped default name (C2's `label`). It survives an override rather than being replaced, * which is what lets the tab offer a way back to it. */ defaultLabel: string; /** This tenant's own name, or `""` when none is set. Absent means inherit the default, and it * is the SAME override the navigation rail's rename writes (R9), not a second one. */ override: string; /** May THIS reader rename it? The server's own `may_open` answer, per row, because a control * the write door would refuse is a button that always fails. */ canRename: boolean; /** Does the governed database exist yet? This is separate from the reader's permission. */ exists: boolean; enabled: boolean; /** Exact rows in the Odoo source model, or null until that model was counted successfully. */ sourceRows: number | null; /** Tri-state on purpose: a model nobody counted is unknown, never empty. */ populated: boolean | null; fields: ConnectorDatabaseField[]; excluded: ConnectorDatabaseExclusion[]; /** * S66-T39 / D-723: true on a `fields=summary` page. The empty `fields` and `excluded` then mean * NOT READ YET, never "this database has no fields"; the Databases tab reads them on expansion * from `GET /connectors/{key}/databases/{database_key}/fields`. */ fieldsDeferred?: boolean; /** The row's raw `syncHealth`, parsed by the Databases tab (`parseDatabaseSyncHealth`). */ syncHealth?: unknown; /** Provider sync facts retain the connection's C1 history notice. */ sync?: unknown; /** * ⭐⭐ W49-T14 β€” THE OTHER DATABASES READING THE SAME SOURCE MODEL, by key. * * β›” MEASURED, AND THE DATABASES TAB WOULD LIE WITHOUT IT: `ut_odoo_invoices` and * `ut_odoo_bills` are both `account.move`; `ut_odoo_agents` and `ut_odoo_vendors` are both * `res.partner`. The enablement flag is keyed `"<model>.<rawName>"`, so one field switch flips * the field under both names, and a screen that printed the same rows twice in silence would be * offering a per-database control that is not per-database. */ sharesFieldsWith: string[]; /** Present only on databases created by the Scraper connector. Credentials never ride here. */ scraperRecipe?: ScraperRecipe; scraperRuns?: ScraperRunReceipt[]; runPath?: string; canRun?: boolean; } /** * ⭐ W49-T14 Β· R24 β€” MAY THE DATABASES TAB DISCLOSE ANYTHING, AND TO THIS READER? * * β›” AN ADDITION TO C4, DECLARED, exactly as `keychain.connect` is. Without it an empty * `databases` list means "this connector has no schema" and "this connector's schema could not be * read" at the same time, and the tab has to pick one. The server knows which; it says so. */ export interface ConnectorIntrospection { introspectable: boolean; /** Why not, in a sentence the tab prints. Empty when it is. */ reason: string; fieldsVisible: boolean; canToggleFields: boolean; canToggleTables: boolean; catalogueComplete: boolean; capturedAt: string; censusAt: string; censusComplete: boolean; censusDurationMs: number; censusModelsCounted: number; censusModelsWithRows: number; /** What an EMPTY `excluded` list actually means, composed where the diff is computed. */ excludedBasis: string; } /** W55-T19 / R7 β€” one provider's own database-enablement door. */ export interface ConnectorEnablement { /** Must match the connector detail envelope that carried it. */ provider: string; /** Read as a string so a future provider mode fails closed instead of widening this UI. */ mode: string; canManage: boolean; updatePath: string; /** The Amazon route changes only config; stored database rows remain in place. */ preservesData: boolean; available: boolean; } /** S66-T39 / D-723: the server's `databasesPage`; `next` is null on the last page. */ export interface ConnectorDatabasesPage { offset: number; limit: number; returned?: number; total: number; hasMore?: boolean; next: number | null; } export interface ConnectorDetail { overview: ConnectorOverview; keychain: ConnectorKeychainHalf; /** Every database read SO FAR. On a paged read `databasesPage.total` is the true count. */ databases: ConnectorDatabase[]; /** C1 is parsed by the Amazon consumer, including every report detail. */ firstLoad?: unknown; /** Summary pages from the preceding release use this connection-level name. */ amazonFirstLoad?: unknown; /** Present only on a paged read. Absent means `databases` is the whole list. */ databasesPage?: ConnectorDatabasesPage | null; /** The graph's own read, `GET /api/v1` + this path, when a summary read deferred it. */ relationshipsPath?: string; /** True when `relationships` is a placeholder the summary read did not fill. */ relationshipsDeferred?: boolean; enablement: ConnectorEnablement | null; materialization?: MaterializationCapability | null; /** Present only when the server says this administrator can request a provider sync. */ syncNow?: { provider: string; path: string } | null; introspection: ConnectorIntrospection; relationships: ConnectorRelationshipGraph; } const str = (v: unknown): string => (typeof v === "string" ? v : ""); const obj = (v: unknown): Record<string, unknown> => v && typeof v === "object" ? (v as Record<string, unknown>) : {}; function parseStrings(raw: unknown): string[] { if (!Array.isArray(raw)) return []; return raw.map((item) => str(item).trim()).filter((item) => item.length > 0); } function parseKeychainHalf(raw: unknown): ConnectorKeychainHalf { const source = obj(raw); const entries: ConnectorKeychainEntry[] = []; for (const item of Array.isArray(source.entries) ? source.entries : []) { const entry = obj(item); const id = str(entry.id).trim(); // A credential row with no id has nothing a later tab could act on, so it is dropped // rather than rendered as a row that refuses every control. if (!id) continue; entries.push({ id, connectionId: str(entry.connectionId).trim() || id, type: str(entry.type).trim(), slot: typeof entry.slot === "number" ? entry.slot : undefined, status: str(entry.status).trim(), label: str(entry.label).trim() || id, masked: str(entry.masked), scope: str(entry.scope).trim(), testable: entry.testable === true, replaceable: entry.replaceable === true, client_secret_rotation_deadline: str(entry.client_secret_rotation_deadline).trim(), }); } return { entries, canConnect: source.canConnect === true, canDisconnect: source.canDisconnect === true, migrationPending: source.migrationPending === true, connect: parseConnectSpec(source.connect), }; } /** * The Connect descriptor, or `null`. * * β›” A SPEC WITH NO FIELDS IS `null`, NOT AN EMPTY FORM. A form that asks for nothing and then * POSTs an empty `fields` object is refused by `keychain.add_entry` ("fields must be a non-empty * object"), so it would be a Connect button that always fails β€” R7's banned shape, arrived at by * degrading gracefully instead of honestly. */ export function parseConnectSpec(raw: unknown): ConnectorConnectSpec | null { const source = obj(raw); const type = str(source.type).trim(); if (!type) return null; const fields: ConnectorConnectField[] = []; for (const item of Array.isArray(source.fields) ? source.fields : []) { const field = obj(item); const key = str(field.key).trim(); if (!key) continue; const parsed: ConnectorConnectField = { key, label: str(field.label).trim() || key, secret: field.secret === true }; if (typeof field.default === "string" && field.default.trim()) parsed.default = field.default; fields.push(parsed); } if (!fields.length) return null; const scopes = parseStrings(source.scopes); return { type, fields, // An empty list would render a picker with no options; `business` is what every connection // stored before this wave actually is, which is the same read default the scope bucket uses. scopes: scopes.length ? scopes : ["business"], tenantWide: source.tenantWide === true, defaultLabel: str(source.defaultLabel).trim() || undefined, }; } /** * One database's field list. Shared by the detail read and the per-database fields read * (S66-T39), so a deferred row loaded on expansion is parsed by the same rule as a full one. */ export function parseDatabaseFields(raw: unknown): ConnectorDatabaseField[] { const fields: ConnectorDatabaseField[] = []; for (const rawField of Array.isArray(raw) ? raw : []) { const field = obj(rawField); const fieldKey = str(field.key).trim(); if (!fieldKey) continue; fields.push({ key: fieldKey, label: str(field.label).trim() || fieldKey, type: str(field.type).trim(), sourceField: str(field.source_field).trim(), enabled: field.enabled === true, }); } return fields; } /** One database's exclusions, shared the same way as `parseDatabaseFields`. */ export function parseDatabaseExclusions(raw: unknown): ConnectorDatabaseExclusion[] { const excluded: ConnectorDatabaseExclusion[] = []; for (const rawItem of Array.isArray(raw) ? raw : []) { const item2 = obj(rawItem); const reason = str(item2.reason).trim(); if (!reason) continue; excluded.push({ sourceField: str(item2.source_field).trim(), reason }); } return excluded; } function parseDatabases(raw: unknown): ConnectorDatabase[] { if (!Array.isArray(raw)) return []; const out: ConnectorDatabase[] = []; for (const item of raw) { const row = obj(item); const key = str(row.key).trim(); // ⭐ W53-T27 β€” THE DEFAULT AND THE EFFECTIVE NAME EACH FALL BACK TO THE OTHER, and neither // falls back to the KEY. A payload from a server that predates this ticket carries `label` // alone, and the tab must then show that name in both columns rather than an empty cell or an // internal identifier. const defaultLabel = str(row.defaultLabel).trim() || str(row.label).trim(); const label = str(row.label).trim() || defaultLabel; // Same rule as `parseDirectory`: a database with no name is never rendered from its key, // which would put an internal identifier on screen. if (!key || !label) continue; const fields = parseDatabaseFields(row.fields); const excluded = parseDatabaseExclusions(row.excluded); const recipeRaw = obj(row.scraperRecipe); const recipeSeed = recipeRaw.seed; const recipeLimits = obj(recipeRaw.limits); const recipeSchedule = obj(recipeRaw.schedule); const recipe: ScraperRecipe | undefined = str(recipeRaw.kind).trim() && str(recipeRaw.source).trim() && str(recipeSchedule.mode).trim() && (typeof recipeSeed === "string" || (str(obj(recipeSeed).search).trim() && str(obj(recipeSeed).geography).trim())) ? { kind: str(recipeRaw.kind).trim(), source: str(recipeRaw.source).trim(), seed: typeof recipeSeed === "string" ? recipeSeed : { search: str(obj(recipeSeed).search).trim(), geography: str(obj(recipeSeed).geography).trim(), }, limits: { ...(typeof recipeLimits.posts === "number" ? { posts: recipeLimits.posts } : {}), ...(str(recipeLimits.postType).trim() ? { postType: str(recipeLimits.postType).trim() } : {}), ...(typeof recipeLimits.records === "number" ? { records: recipeLimits.records } : {}), }, schedule: { mode: str(recipeSchedule.mode).trim() }, } : undefined; const scraperRuns: ScraperRunReceipt[] = []; for (const rawRun of Array.isArray(row.scraperRuns) ? row.scraperRuns : []) { const run = obj(rawRun); const id = str(run.id).trim(); if (!id) continue; scraperRuns.push({ id, state: str(run.state).trim(), provider: str(run.provider).trim(), rows: typeof run.rows === "number" && Number.isFinite(run.rows) ? Math.max(0, Math.trunc(run.rows)) : 0, startedAt: str(run.startedAt).trim(), finishedAt: str(run.finishedAt).trim(), estimatedUsd: typeof run.estimatedUsd === "number" ? run.estimatedUsd : 0, costCapUsd: typeof run.costCapUsd === "number" ? run.costCapUsd : 0, note: str(run.note).trim(), }); } out.push({ key, label, identity: str(obj(row.identity).databaseKey) === key ? { provider: str(obj(row.identity).provider), connectionId: str(obj(row.identity).connectionId), databaseKey: key, model: str(obj(row.identity).model), } : undefined, // β›” `native` IS NOT DEFAULTED TO ANYTHING. An absent one means the server could not name // the source's own identifier for this table, and the tab says so; inventing the key or the // label here would put OUR word on screen under the vendor's heading. native: str(row.native).trim(), defaultLabel, override: str(row.override).trim(), canRename: row.canRename === true, exists: row.exists === true, enabled: row.enabled === true, sourceRows: typeof row.sourceRows === "number" && Number.isFinite(row.sourceRows) && row.sourceRows >= 0 ? Math.trunc(row.sourceRows) : null, populated: row.populated === true ? true : row.populated === false ? false : null, fields, excluded, ...(row.fieldsDeferred === true ? { fieldsDeferred: true } : {}), ...(row.syncHealth !== undefined ? { syncHealth: row.syncHealth } : {}), ...(row.sync !== undefined ? { sync: row.sync } : {}), sharesFieldsWith: parseStrings(row.sharesFieldsWith), ...(recipe ? { scraperRecipe: recipe } : {}), ...(recipe ? { scraperRuns } : {}), ...(str(row.runPath).startsWith("/connectors/scraper/databases/") && str(row.runPath).endsWith("/run") ? { runPath: str(row.runPath), canRun: row.canRun === true } : {}), }); } return out; } /** * R24's answer, read defensively. * * β›” THE DEFAULT IS "NOT INTROSPECTABLE", NOT "INTROSPECTABLE WITH NOTHING IN IT". A payload * missing this half is a server that predates it, and the fail-closed direction shows the card's * own content rather than a disclosure screen with empty lists and live toggles on it. */ function parseIntrospection(raw: unknown): ConnectorIntrospection { const source = obj(raw); return { introspectable: source.introspectable === true, reason: str(source.reason).trim(), fieldsVisible: source.fieldsVisible === true, canToggleFields: source.canToggleFields === true, canToggleTables: source.canToggleTables === true, catalogueComplete: source.catalogueComplete === true, capturedAt: str(source.capturedAt).trim(), censusAt: str(source.censusAt).trim(), censusComplete: source.censusComplete === true, censusDurationMs: typeof source.censusDurationMs === "number" && Number.isFinite(source.censusDurationMs) ? Math.max(0, Math.trunc(source.censusDurationMs)) : 0, censusModelsCounted: typeof source.censusModelsCounted === "number" && Number.isFinite(source.censusModelsCounted) ? Math.max(0, Math.trunc(source.censusModelsCounted)) : 0, censusModelsWithRows: typeof source.censusModelsWithRows === "number" && Number.isFinite(source.censusModelsWithRows) ? Math.max(0, Math.trunc(source.censusModelsWithRows)) : 0, excludedBasis: str(source.excludedBasis).trim(), }; } /** * Parse a provider capability bound to the selected connector, or refuse it. * * A path is actionable only when it stays under this provider and carries the one database-key * slot the server declared. Missing, cross-provider and unknown modes render no control; the API * remains the permission boundary, but the modal never paints a button it knows cannot work. */ export function parseConnectorEnablement( raw: unknown, selectedKey: string ): ConnectorEnablement | null { const source = obj(raw); const provider = str(source.provider).trim(); const mode = str(source.mode).trim(); if (provider !== selectedKey || mode !== "database" || source.preservesData !== true) return null; const updatePath = str(source.updatePath).trim(); const expectedPrefix = `/connectors/${encodeURIComponent(provider)}/databases/`; const validPath = updatePath.startsWith(expectedPrefix) && updatePath.endsWith("/enablement") && updatePath.includes("{databaseKey}"); const canManage = source.canManage === true && source.available === true && validPath; return { provider, mode, canManage, updatePath: canManage ? updatePath : "", preservesData: true, available: source.available === true, }; } /** * Read the detail payload for the card that was actually clicked. * * β›” THE SELECTED KEY IS A SECOND GUARD, exactly as it is for the relationship graph: a stale * response that arrives after the reader opened a different connector is REFUSED rather than * painted under the new title. `parseRelationshipGraph` already applies that rule to its own * half; this applies it to the envelope. */ /** * S66-T39 / D-723: the server's page cursor, or `null`. * * β›” A CURSOR THAT DOES NOT MOVE FORWARD IS REFUSED, because the modal follows `next` in a loop * and a `next` at or behind `offset` would read the same page forever. */ export function parseDatabasesPage(raw: unknown): ConnectorDatabasesPage | null { const page = obj(raw); const whole = (v: unknown): v is number => typeof v === "number" && Number.isSafeInteger(v) && v >= 0; if (!whole(page.offset) || !whole(page.limit) || page.limit < 1 || !whole(page.total)) return null; if (page.next !== null && !(whole(page.next) && page.next > page.offset)) return null; const returned = Math.min(page.limit, Math.max(0, page.total - page.offset)); const hasMore = page.offset + returned < page.total; if (page.returned !== undefined && (!whole(page.returned) || page.returned !== returned)) return null; if (page.hasMore !== undefined && (typeof page.hasMore !== "boolean" || page.hasMore !== hasMore)) return null; if ((page.returned !== undefined || page.hasMore !== undefined) && page.next !== (hasMore ? page.offset + page.limit : null)) return null; return { offset: page.offset, limit: page.limit, total: page.total, next: page.next, ...(whole(page.returned) ? { returned: page.returned } : {}), ...(typeof page.hasMore === "boolean" ? { hasMore: page.hasMore } : {}) }; } export function parseConnectorDetail(body: unknown, selectedKey: string): ConnectorDetail | null { const source = obj(body); const overview = obj(source.overview); const key = str(overview.key).trim(); if (!key || key !== selectedKey) return null; // Same bound-to-the-selected-key rule as `syncNow` below: a path naming another connector is // not followed. const relationshipsPath = str(source.relationshipsPath) === `/connectors/${encodeURIComponent(selectedKey)}/relationships` ? str(source.relationshipsPath) : ""; return { ...("databasesPage" in source ? { databasesPage: parseDatabasesPage(source.databasesPage) } : {}), ...(relationshipsPath ? { relationshipsPath, relationshipsDeferred: source.relationships === null || source.relationships === undefined, } : {}), overview: { key, label: str(overview.label).trim(), status: str(overview.status).trim(), account: str(overview.account).trim(), source: str(overview.source).trim(), creates: parseStrings(overview.creates), syncHealth: overview.syncHealth, }, keychain: parseKeychainHalf(source.keychain), databases: parseDatabases(source.databases), ...(source.firstLoad !== undefined ? { firstLoad: source.firstLoad } : {}), ...(source.amazonFirstLoad !== undefined ? { amazonFirstLoad: source.amazonFirstLoad } : {}), enablement: parseConnectorEnablement(source.enablement, selectedKey), syncNow: obj(source.syncNow).provider === selectedKey && str(obj(source.syncNow).path) === `/connectors/${selectedKey}/sync/now` ? { provider: selectedKey, path: `/connectors/${selectedKey}/sync/now` } : null, materialization: obj(source.materialization).provider === selectedKey && str(obj(source.materialization).statusPath) === `/connectors/${selectedKey}/jobs` && str(obj(source.materialization).retryPath) === `/connectors/${selectedKey}/sync/retry` ? { provider: selectedKey, statusPath: `/connectors/${selectedKey}/jobs`, retryPath: `/connectors/${selectedKey}/sync/retry` } : null, introspection: parseIntrospection(source.introspection), relationships: parseRelationshipGraph(source.relationships, selectedKey), }; } /** R22: access is a status from the detail payload, including connections without keychain rows. */ export function accessSentence( keychain: ConnectorKeychainHalf, status: string, connectorKey?: string, ): string { if (status === "connected") return "Connected"; if (status === "reconnect") return connectorKey === "amazon_sp" ? "Needs a test" : "Reconnect"; if (status === "expired") return "Expired"; return keychain.entries.length ? "Stored" : "Not connected"; } /** The brand mark, or the two-letter fallback tile the directory already uses (wave 30, R4). */ export function ConnectorMark({ connectorKey, label }: { connectorKey: string; label: string }) { const mark = brandForConnector(connectorKey, 20); return ( <span className="conn-modal-mark" aria-hidden="true"> {mark ?? <span className="shell-db-chip conn-tile">{tileText(label)}</span>} </span> ); } /** Amazon Settings accepts the SP-API connector and the legacy review connector keys. */ export function isAmazonConnector(key: string): boolean { const k = String(key || "").toLowerCase(); return k === "md_amazon" || k === "amazon" || k === "amazon_sp"; } export function ConnectorOverviewPanel({ detail, row, syncCapability, syncProblem = "", syncReady = true, onSyncReady, hidden = false, onPullReviews, isAdmin = false, deletionRefreshKey, onSyncNow, syncBusy = false, syncReceipt, syncError = "", }: { detail: ConnectorDetail | null; row?: ConnectorRow; syncCapability?: ConnectorSyncCapability | null; syncProblem?: string; syncReady?: boolean; onSyncReady?: (connectorKey: string, refreshKey: number) => void; hidden?: boolean; /** * ⭐ OPTIONAL, AND THE FILE'S OWN HEADER SAYS WHY. The static proof sheets render this panel * with `renderToStaticMarkup` and pass no handlers; a required prop would red `tsc` on files * this ticket does not own β€” the same lesson `onOpen` paid for one ticket earlier. * * β›” ABSENT MEANS NO CONTROL, NOT A DISABLED ONE. This directory's rule is that a reader who * may not do a thing sees no door for it rather than one that would 403. */ onPullReviews?: () => void; onOpenDatabases?: () => void; isAdmin?: boolean; deletionRefreshKey?: number; onSyncNow?: () => void; syncBusy?: boolean; syncReceipt?: SyncNowReceipt | null; syncError?: string; }) { const overview = detail?.overview; const connectorKey = row?.key ?? overview?.key ?? ""; const health = parseDatabaseSyncHealth(overview?.syncHealth); const state = syncReceipt?.state === "queued" ? "queued" : syncReceipt?.state === "running" || syncBusy ? "running" : syncReceipt?.state === "failed" ? "failed" : health?.state; // A partial sync landed most tables. Only a failed one reads as failed, and it names its cause. const failed = state === "failed"; const partial = state === "partial"; const notOffered = health?.notOffered ?? 0; const status = failed ? "Sync failed" : partial ? "Partly synced" : state === "running" ? "Syncing" : state === "queued" ? "Queued" : state === "succeeded" && notOffered > 0 ? `Synced with ${notOffered.toLocaleString()} ${notOffered === 1 ? "report" : "reports"} not offered` : detail ? accessSentence(detail.keychain, detail.overview.status, connectorKey) : ""; const showSync = syncCapability?.supported || (!syncCapability && (row?.spawns_tables || syncProblem)); return ( <div className="conn-settings-overview" hidden={hidden}> <header className="conn-settings-header" aria-label="Connection status"> {showSync ? <div className="conn-settings-sync-row"> {syncCapability?.supported ? <ConnectorOverviewSyncStatus key={JSON.stringify([connectorKey, deletionRefreshKey ?? 0])} connectorKey={connectorKey} refreshKey={deletionRefreshKey ?? 0} onReady={onSyncReady} /> : <p className="conn-settings-last-success" role="status">{syncProblem || "Loading sync status…"}</p>} {isAdmin && onSyncNow ? ( <button type="button" className="conn-settings-sync set-primary" disabled={syncBusy} aria-busy={syncBusy} onClick={onSyncNow}> Sync now </button> ) : null} {syncReady && !hidden && connectorKey === "odoo" && isAdmin ? <OdooSyncEvery /> : null} </div> : null} {overview ? <div className="conn-settings-account"> <span className="conn-settings-label">Account</span> <span className="conn-settings-account-name">{overview.account || "No account recorded"}</span> <div className="conn-settings-health"> <span className="conn-settings-status" data-sync-state={state || overview.status} data-tone={failed ? "error" : state === "running" || state === "queued" ? "active" : "neutral"} role="status">{status}</span> {health?.warning ? <span className="conn-settings-warning" role="note">{health.warning}</span> : (failed || partial) && health?.error ? <span className="conn-settings-warning" role="note">{health.error.message}</span> : null} </div> </div> : null} </header> {!hidden && connectorKey === "amazon_sp" ? <AmazonSyncOverview refreshKey={deletionRefreshKey} /> : null} {!hidden && isAmazonConnector(connectorKey) ? <AmazonWritesSwitch /> : null} {syncError ? <p className="conn-settings-error" role="alert">{syncError}</p> : null} {syncReady && !hidden && overview?.key === "amazon_sp" && isAdmin ? ( <AmazonDeletionNotice isAdmin={isAdmin} refreshKey={deletionRefreshKey} /> ) : null} {onPullReviews ? ( <div className="conn-modal-act"> <button type="button" className="conn-modal-go" onClick={onPullReviews}> Pull reviews </button> </div> ) : null} </div> ); } /** Compatibility export for fixtures. Database rows own the enablement controls. */ export function ProviderEnablementPanel(_props: { detail: ConnectorDetail; onChanged: () => void; }) { return null; } // ── The three tabs that are not built yet. β›” EACH IS ITS OWN COMPONENT SLOT so W49-T13, T14 and // T15 replace a named component rather than editing a sentence out of a branch, and the switch // below never has to change shape. Plain sentences, no dashes, no emojis. /* β›”β›” `KeychainTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T13. The real tab is `connectors/KeychainTab.tsx`, mounted below from the loaded detail payload rather than from a branch that answers before the fetch β€” which is the one structural change this ticket makes to `renderTab`: the keychain half is DATA, so its tab cannot render before the read lands. */ /* β›”β›” `DatabasesTabPlaceholder` STOOD HERE AND IS REPLACED BY W49-T14. The real tab is `connectors/DatabasesTab.tsx`, mounted below from the loaded detail payload rather than from a branch that answers before the fetch. That is the same structural move the keychain and relationship tabs each made, for the third time and for the same reason: the database list, its field catalogue and R24's introspectable flag are all DATA on this read, so a tab rendering above the load guard could only ever paint an empty disclosure and, worse, would read `introspectable: false` on every connector for as long as the fetch was in flight. */ /** * `paging` is present only while later database pages are still being read ("loading") or when * one of them failed ("failed"); the Databases tab says which instead of implying a short list. */ type Load = | { phase: "loading" } | { phase: "ready"; detail: ConnectorDetail; paging?: "loading" | "failed" } | { phase: "error"; message: string }; const CONNECTOR_DETAIL_FRESHNESS_MS = 60_000; const SIGNED_OUT_EVENT = "aios:signed-out"; // Measured reads take 1.34 s cold and 0.01 s warm, with a boot contended read above 8 s. Twenty seconds caps the wait a person sees. // This is deliberately shorter than the server's thirty seconds so this component shows its own readable sentence before a bare 504. const CONNECTOR_DETAIL_DEADLINE_MS = 20_000; // Closing the modal unmounts it; keep the last successful read for the next open. const connectorDetailCache = new Map<string, { detail: ConnectorDetail; at: number }>(); // S67-T31: a refused read shows the server's own plain cause, or this component's sentence when // the server sent none (a bare 500 has no JSON body). A status code never reaches the screen: // "The server answered 500." was the owner's whole report, and it told him nothing he could act on. function plainReadFailure( body: { error?: { message?: string }; detail?: { error?: { message?: string } } } | null, fallback: string, ): string { const said = (body?.error?.message || body?.detail?.error?.message || "").trim(); return said || fallback; } // Shell.tsx::signOut emits SIGNED_OUT_EVENT; an unloaded module has no cache to clear. export function clearConnectorDetailCache(): void { connectorDetailCache.clear(); } // ⭐ S66-T39 / D-723 β€” THE DETAIL IS READ IN PAGES. An unpaged read carried every database with // every field and the whole relationship graph, which is what made the first open slow and // heavy after a fresh boot. A summary page carries 50 databases with their fields deferred; the // rest are read by following `databasesPage.next` until it is null, so every database stays // reachable. `overview.creates` is already the unsliced list on every page. // β›” Nothing below may be exported: verify_wiring's S66-T28 runner executes this block as-is. const CONNECTOR_DETAIL_PAGE_SIZE = 50; function connectorDetailPageUrl(connectorKey: string, offset: number, revalidate: boolean): string { return `${API_V1}/connectors/${encodeURIComponent(connectorKey)}/detail` + `?databases_offset=${offset}&databases_limit=${CONNECTOR_DETAIL_PAGE_SIZE}&fields=summary` + (revalidate ? "&revalidate=1" : ""); } // A later page contributes its databases and its cursor. Every other half is the first page's, // so the overview, keychain and capabilities a reader already sees do not flicker mid-read. function appendDetailPage(current: ConnectorDetail, page: ConnectorDetail): ConnectorDetail { const seen = new Set(current.databases.map((database) => database.key)); return { ...current, databases: [...current.databases, ...page.databases.filter((database) => !seen.has(database.key))], databasesPage: page.databasesPage, }; } if (typeof window !== "undefined") { window.addEventListener(UNAUTHORIZED_EVENT, clearConnectorDetailCache); window.addEventListener(SIGNED_OUT_EVENT, clearConnectorDetailCache); } type PendingLeave = { kind: "close" } | { kind: "tab"; tab: ConnectorTab } | null; /** * THE MODAL. Centered, portalled to <body>, focus-trapped, dismissed by Escape or a click * outside, and it hands focus back to the control that opened it. */ export default function ConnectorModal({ row, onClose, initialTab = "overview", isAdmin = false, }: { row: ConnectorRow; onClose: () => void; /** Credential links land on Setup, including the retired tab aliases. */ initialTab?: ConnectorTab; /** Retained for callers that still pass the retired Databases-tab callback. */ onOpenDatabases?: () => void; isAdmin?: boolean; }) { const connectorKey = row.key; const panelRef = useRef<HTMLDivElement>(null); const closeRef = useRef<HTMLButtonElement>(null); const [tab, setTab] = useState<"overview" | "setup">(() => connectorTab(initialTab)); const [loadKey, setLoadKey] = useState(connectorKey); const [reading, setLoad] = useState<Load>(() => { const cached = connectorDetailCache.get(connectorKey); return cached ? { phase: "ready", detail: cached.detail } : { phase: "loading" }; }); const load: Load = loadKey === connectorKey ? reading : { phase: "loading" }; const databasesRef = useRef<DatabasesTabHandle>(null); const [databasePendingCount, setDatabasePendingCount] = useState(0); const [databaseTabBusy, setDatabaseTabBusy] = useState(false); const [databaseSaving, setDatabaseSaving] = useState(false); const [setupNotice, setSetupNotice] = useState<{ key: string; message: string } | null>(null); const syncWasActive = useRef(false); const [pendingLeave, setPendingLeave] = useState<PendingLeave>(null); /** * ⭐ W49-T13 β€” THE RE-READ, AND IT IS NOT OPTIONAL POLISH. The Keychain tab WRITES: it stores, * tests, deletes and disconnects. Keying the fetch on `connectorKey` alone leaves a deleted key * on screen until the modal is closed and reopened, which reads as a delete that did not land β€” * so the effect below keys on this counter as well and every write bumps it. */ const [reads, setReads] = useState(0); const syncSource = useConnectorSyncCapability(connectorKey, reads, row); const [syncReady, setSyncReady] = useState<{ connectorKey: string; refreshKey: number } | null>(null); const markSyncReady = useCallback((key: string, refreshKey: number) => { setSyncReady((current) => current?.connectorKey === key && current.refreshKey === refreshKey ? current : { connectorKey: key, refreshKey }); }, []); const detailReadsReady = Boolean(syncSource.problem || (syncSource.capability && (!syncSource.capability.supported || (syncReady?.connectorKey === connectorKey && syncReady.refreshKey === reads)))); const syncCapability = isAdmin && detailReadsReady ? syncSource.capability?.syncNow : null; const syncNow = useSyncNow(syncCapability); const [databaseReveal, setDatabaseReveal] = useState<DatabaseReveal | null>(null); const reread = useCallback((reveal?: DatabaseReveal) => { // Evict immediately so closing just after a write cannot reuse the previous read. connectorDetailCache.delete(connectorKey); if (reveal) setDatabaseReveal(reveal); setReads((n) => n + 1); }, [connectorKey]); useEffect(() => { if (syncNow.busy) syncWasActive.current = true; else if (syncWasActive.current && syncNow.receipt && ["done", "failed"].includes(syncNow.receipt.state)) { syncWasActive.current = false; reread(); } }, [reread, syncNow.busy, syncNow.receipt]); /** * ⭐⭐ W49-T19 Β· R31 β€” THE AMAZON REVIEWS PULL, OPENED FROM THE OVERVIEW TAB. * A second overlay above this one, which is why it takes the PORTAL step and this modal keeps * the DIALOG step ([[z-layering-is-a-three-way-order]]). */ const [pulling, setPulling] = useState(false); /** * β›”β›” THE PULL AND CONFIRM DIALOGS' OWN SURFACES, HELD IN STATE RATHER THAN REFS, because * `useOverlayLayer` reads `outsideElements` on every RENDER and a ref that fills in after mount * would never reach it. See the dismissal note on the layer below. */ const [pullSurface, setPullSurface] = useState<HTMLElement | null>(null); const [tabConfirmSurface, setTabConfirmSurface] = useState<HTMLElement | null>(null); const [leaveSurface, setLeaveSurface] = useState<HTMLElement | null>(null); const canPull = isAmazonConnector(row.key) && row.key.toLowerCase() !== "amazon_sp"; const unsavedMessage = databasePendingCount === 1 ? "You have 1 unsaved change to this connection." : `You have ${databasePendingCount} unsaved changes to this connection.`; const requestClose = useCallback(() => { if (databaseSaving || databaseTabBusy) return; if (databasePendingCount) { setPendingLeave({ kind: "close" }); return; } onClose(); }, [databasePendingCount, databaseSaving, databaseTabBusy, onClose]); const requestTab = useCallback((next: ConnectorTab) => { if (databaseSaving || databaseTabBusy) return; if (next === tab) return; if (databasePendingCount) { setPendingLeave({ kind: "tab", tab: next }); return; } setTab(connectorTab(next)); }, [databasePendingCount, databaseSaving, databaseTabBusy, tab]); useEffect(() => { if (!databasePendingCount) return; const warn = (event: BeforeUnloadEvent) => { event.preventDefault(); event.returnValue = unsavedMessage; }; window.addEventListener("beforeunload", warn); return () => window.removeEventListener("beforeunload", warn); }, [databasePendingCount, unsavedMessage]); useOverlayLayer({ panelRef, /** * β›”β›” DISMISS THE TOP LAYER, NOT BOTH OF THEM, AND THE HOOK CANNOT DO THIS FOR US HERE. * * `useOverlayLayer` guards its handlers with `stack.isTop(id)` and that guard is INERT in this * app: `OverlaySurface.tsx` exports `OverlayProvider` and nothing mounts it, so the context is * null and every layer believes it is the top one. Both layers listen for pointers on `document` in * the CAPTURE phase, where `stopPropagation` does not stop a sibling listener on the same * node. So a pointer press can dismiss the dialog AND this modal underneath it. * Answering here keeps the fix in this ticket's own files: while either confirm is open, * this layer refuses dismissal; while the pull dialog is open, it closes THAT and stops. * Escape already belongs to the topmost entry in `useEscapeClose`'s shared stack. */ onDismiss: () => { if (pendingLeave || tabConfirmSurface) return; if (pulling) { setPulling(false); return; } requestClose(); }, // D-724 (S66-T34 remainder): a stray press outside the panel no longer closes it, so a // staged change or a half-read tab is not lost to a missed click (DESIGN.md section 4). // Escape and the close button remain the ways out. dismissOnOutside: false, /** * β›” AND THE POINTER HALF OF THE SAME PROBLEM. These dialogs portal as SIBLINGS of this * panel, so a press inside one is literally outside `panelRef` and would dismiss this modal * out from under a paid pull or a staged change. `outsideElements` is the hook's own answer. * Each surface includes its scrim, so a stray press there cannot dismiss this modal either. */ outsideElements: [pullSurface, tabConfirmSurface, leaveSurface].filter( (element): element is HTMLElement => element !== null, ), initialFocus: "[data-overlay-autofocus]", trapFocus: pendingLeave === null && tabConfirmSurface === null, // The layer captures whatever was focused when it mounted and focuses it again on unmount, // which is the card's own open button. That is the done-when's "focus returns to the card". restoreFocus: true, }); // The overlay captures the opener first. Focus enters before paint, even while detail is pending. useLayoutEffect(() => { closeRef.current?.focus({ preventScroll: true }); }, [connectorKey]); useEffect(() => { let dead = false; setLoadKey(connectorKey); const cached = reads === 0 ? connectorDetailCache.get(connectorKey) : undefined; if (reads > 0) { connectorDetailCache.delete(connectorKey); setLoad((current) => current.phase === "ready" && current.detail.overview.key === connectorKey ? current : { phase: "loading" }); } else if (cached) { setLoad({ phase: "ready", detail: cached.detail }); if (Date.now() - cached.at < CONNECTOR_DETAIL_FRESHNESS_MS) return; } else { setLoad({ phase: "loading" }); } // Status settles before database pages and optional receipt readers compete for the first read. if (!detailReadsReady) return; const controller = new AbortController(); let timedOut = false; const timeoutMessage = `Reading ${row.label} stopped after ${CONNECTOR_DETAIL_DEADLINE_MS / 1000} seconds because the server did not answer.`; const timeout = setTimeout(() => { timedOut = true; controller.abort(); if (!dead && !cached) setLoad({ phase: "error", message: timeoutMessage }); }, CONNECTOR_DETAIL_DEADLINE_MS); // Something is already on screen (a cached detail, or the one a re-read keeps painted). Then // later pages are gathered off screen and swapped in whole, so a background read never // shrinks a complete list to its first page. A first open paints each page as it lands. const painted = Boolean(cached) || reads > 0; const readPage = async (offset: number): Promise<ConnectorDetail> => { const res = await fetch( connectorDetailPageUrl(connectorKey, offset, Boolean(cached)), { credentials: CREDENTIALS, signal: controller.signal } ); if (res.status === 401 || res.status === 403) clearConnectorDetailCache(); const body = (await res.json().catch(() => null)) as | { error?: { message?: string }; detail?: { error?: { message?: string } } } | null; if (dead) throw new Error("closed"); if (timedOut) throw new Error(timeoutMessage); if (!res.ok) { throw new Error(plainReadFailure(body, `The details for ${row.label} could not be read.`)); } const page = parseConnectorDetail(body, connectorKey); if (!page) { throw new Error( "This connector's details were refused because the answer described a different connection." ); } const cursor = page.databasesPage; if (cursor !== undefined && (!cursor || cursor.offset !== offset || page.databases.length !== Math.min(cursor.limit, Math.max(0, cursor.total - offset)) || new Set(page.databases.map((database) => database.key)).size !== page.databases.length || cursor.next !== (offset + page.databases.length < cursor.total ? offset + cursor.limit : null))) { throw new Error("The database list is incomplete. Try again."); } return page; }; void (async () => { try { let detail = await readPage(0); clearTimeout(timeout); // The deadline covers the first page, which is what a person waits on. Later pages run // under the same abort, so closing the modal still stops them. // A complete list already on screen stays there until the new one is whole; anything // else (nothing yet, or a partial list) is replaced page by page. const keep = (current: Load) => painted && current.phase === "ready" && current.paging === undefined; const fail = (partial: ConnectorDetail) => setLoad((current) => keep(current) ? current : { phase: "ready", detail: partial, paging: "failed" }); let cursor = detail.databasesPage; let next = cursor ? cursor.next : null; if (cursor === null) { // A paged answer whose cursor could not be read: say so rather than show one page as all. fail(detail); return; } if (next === null) { connectorDetailCache.set(connectorKey, { detail, at: Date.now() }); setLoad({ phase: "ready", detail }); return; } const firstPage = detail; setLoad((current) => keep(current) ? current : { phase: "ready", detail: firstPage, paging: "loading" }); while (next !== null) { const offset: number = next; let page: ConnectorDetail; // Each later page gets the same deadline; a hung one ends the loop as a failed page. const pageTimer = setTimeout(() => controller.abort(), CONNECTOR_DETAIL_DEADLINE_MS); try { page = await readPage(offset); } catch { if (!dead) fail(detail); return; } finally { clearTimeout(pageTimer); } if (dead) return; cursor = page.databasesPage; detail = appendDetailPage(detail, page); if (!cursor || cursor.offset !== offset || cursor.total !== firstPage.databasesPage?.total || detail.databases.length !== Math.min(offset + cursor.limit, cursor.total)) { fail(detail); return; } next = cursor.next; const sofar = detail; if (next === null) { connectorDetailCache.set(connectorKey, { detail: sofar, at: Date.now() }); setLoad({ phase: "ready", detail: sofar }); } else { setLoad((current) => keep(current) ? current : { phase: "ready", detail: sofar, paging: "loading" }); } } } catch (error) { // A failed background read must leave the already painted detail intact. if (!dead && !cached) { setLoad({ phase: "error", message: timedOut ? timeoutMessage : error instanceof Error ? error.message : "Cannot reach the server.", }); } } finally { clearTimeout(timeout); } })(); return () => { dead = true; clearTimeout(timeout); controller.abort(); }; // eslint-disable-next-line react-hooks/exhaustive-deps -- Omit row.label, which only supplies timeout wording. }, [connectorKey, reads, detailReadsReady]); const rotationNow = useRotationClock(); const rotationEntry = row.key === "amazon_sp" && load.phase === "ready" ? load.detail.keychain.entries .filter((entry) => amazonRotationNotice(entry.client_secret_rotation_deadline, rotationNow)) .sort((a, b) => Date.parse(a.client_secret_rotation_deadline || "") - Date.parse(b.client_secret_rotation_deadline || ""))[0] : undefined; const rotationNotice = rotationEntry ? amazonRotationNotice(rotationEntry.client_secret_rotation_deadline, rotationNow) : null; const renderTab = useCallback(() => { if (tab === "setup" && !isAdmin) { return <p className="conn-setup-refusal">Only an admin can manage connector keys.</p>; } // β›” THE KEYCHAIN TAB IS BELOW THE LOAD GUARD, and the placeholder it replaces was above it. // C4 serves the credential rows on the SAME payload as the overview, so a keychain tab that // rendered before the read landed could only render an empty list β€” i.e. "nobody has // connected this" about a connection nobody had asked the server about yet. if (load.phase === "loading") { return ( <div className="conn-settings-skeleton" role="status" aria-label="Loading connector settings"> <span /><span /><span /><span /> </div> ); } if (load.phase === "error") { return ( <div className="conn-modal-error"> <p role="alert">{load.message}</p> <button className="conn-modal-retry" type="button" onClick={() => reread()}> Try again </button> </div> ); } if (tab === "setup") { return <> {setupNotice?.key === connectorKey ? <p className="conn-kc-note" role="status">{setupNotice.message}</p> : null} <KeychainTab row={row} keychain={load.detail.keychain} onChanged={(message) => { setSetupNotice(message ? { key: connectorKey, message } : null); reread(); }} isAdmin={isAdmin} connectionId={load.detail.databases.find((database) => database.identity?.connectionId)?.identity?.connectionId} /> </>; } if (tab === "overview") { return ( <> {rotationNotice ? <RotationNotice notice={rotationNotice} onRotate={isAdmin && rotationEntry?.replaceable && load.detail.keychain.connect ? () => setTab("setup") : undefined} /> : null} {row.spawns_tables === true || row.key === "scraper" ? <> <DatabasesTab ref={databasesRef} row={row} detail={load.detail} isAdmin={isAdmin} onChanged={reread} onPendingChange={setDatabasePendingCount} onBusyChange={setDatabaseTabBusy} onConfirmSurface={setTabConfirmSurface} reveal={databaseReveal} databasesPaging={load.paging} /> </> : <p className="conn-settings-empty">No databases from this connection.</p>} </> ); } return null; }, [connectorKey, databaseReveal, load, reread, rotationEntry, rotationNotice, row, tab, isAdmin, setupNotice]); const saveDatabaseChanges = useCallback(async () => { if (!databasePendingCount || !databasesRef.current) return; setDatabaseSaving(true); try { await databasesRef.current.savePending(); } finally { setDatabaseSaving(false); } }, [databasePendingCount]); const discardDatabaseChanges = useCallback(() => { databasesRef.current?.discardPending(); setDatabasePendingCount(0); }, []); const confirmLeave = useCallback(() => { if (!pendingLeave) return; const destination = pendingLeave; discardDatabaseChanges(); setPendingLeave(null); if (destination.kind === "close") onClose(); else setTab(connectorTab(destination.tab)); }, [discardDatabaseChanges, onClose, pendingLeave]); const expired = rotationNotice?.tone === "expired"; const status = expired ? "expired" : load.phase === "ready" ? load.detail.overview.status : row.state; const title = load.phase === "ready" ? load.detail.overview.label || row.label : row.label; return ( <BodyPortal> <div className="conn-modal-backdrop"> <section className="conn-modal" ref={panelRef} role="dialog" aria-modal="true" aria-labelledby="conn-modal-title" data-overlay-kind="connector-detail" tabIndex={-1} > <header className="conn-modal-head"> <ConnectorMark connectorKey={row.key} label={row.label} /> <span className="conn-modal-name" id="conn-modal-title">{title}</span> {/* Status words use the same muted type as Keychain metadata. */} {status && tab !== "overview" ? ( <span className="conn-kc-meta" role={status === "expired" ? "alert" : undefined} >{status.charAt(0).toUpperCase() + status.slice(1)}</span> ) : null} {tab === "overview" && databasePendingCount > 0 ? ( <div className="conn-modal-save-actions"> <button type="button" className="conn-db-link" disabled={!databasePendingCount || databaseSaving || databaseTabBusy} onClick={discardDatabaseChanges} > Discard </button> <button type="button" className="conn-modal-go" disabled={!databasePendingCount || databaseSaving || databaseTabBusy} onClick={() => void saveDatabaseChanges()} > {databaseSaving ? "Saving" : databasePendingCount ? `Save ${databasePendingCount} ${databasePendingCount === 1 ? "change" : "changes"}` : "Save"} </button> </div> ) : null} <button type="button" ref={closeRef} className="conn-modal-close" aria-label={`Close the ${row.label} connector`} data-overlay-autofocus disabled={databaseSaving || databaseTabBusy} onClick={requestClose} > Γ— </button> </header> <div className="conn-modal-tabs" role="tablist" aria-label="Connector sections"> {connectorTabs(row).map((entry) => ( <button key={entry.key} type="button" role="tab" id={`conn-tab-${entry.key}`} className="conn-modal-tab" aria-selected={tab === entry.key} aria-controls="conn-tab-panel" disabled={databaseSaving || databaseTabBusy} onClick={() => requestTab(entry.key)} > {entry.label} </button> ))} </div> <div className="conn-modal-body" id="conn-tab-panel" role="tabpanel" aria-labelledby={`conn-tab-${tab}`} aria-busy={tab === "setup" && isAdmin && load.phase === "loading"} > <ConnectorOverviewPanel row={row} detail={load.phase === "ready" ? load.detail : null} hidden={tab !== "overview"} syncReady={detailReadsReady} onSyncReady={markSyncReady} isAdmin={isAdmin} deletionRefreshKey={reads} syncCapability={syncSource.capability} syncProblem={syncSource.problem} onPullReviews={canPull && load.phase === "ready" ? () => setPulling(true) : undefined} onSyncNow={syncCapability ? () => void syncNow.start() : undefined} syncBusy={syncNow.busy} syncReceipt={syncNow.receipt} syncError={syncNow.message} /> {renderTab()} </div> </section> </div> {/* β›” RENDERED AS A SIBLING OF THE MODAL, INSIDE THE SAME PORTAL. Nesting it in `.conn-modal-body` would put it inside a scrolling, overflow-hidden box and the overlay would be clipped by the panel it is supposed to sit above. */} {pulling ? ( <MonidRunDialog label={row.label} onClose={() => setPulling(false)} surfaceRef={setPullSurface} /> ) : null} <ConfirmDialog open={pendingLeave !== null} title="Discard unsaved changes" body={<p>{unsavedMessage}</p>} confirmLabel="Discard changes" tone="destructive" onConfirm={confirmLeave} onCancel={() => setPendingLeave(null)} surfaceRef={setLeaveSurface} /> </BodyPortal> ); }
// ---------------------------------------------------------------------------
// connectors/ConnectorModal.tsx β€” W49-T12, ruling R26, contract C4.
//
// ⭐⭐ R26, verbatim: *"The connector popup is a centered MODAL with tabs Overview,
// Keychain, Databases, Relationships, opened from the card. The Keychain moves
// INTO it and Settings > Keychains becomes a link to the modal (one door). Field
// enablement moves into the Databases tab."*
//
// Overview and Setup are the only tabs. Retired keys open Setup.
// The C7 status reader stays mounted independently of the paged detail read.
//
// β›” NO REUSABLE MODAL COMPONENT EXISTS IN THIS REPO. `CustomerGrid.tsx`'s
// `LinkGridModal` owns the portal-plus-focus-trap pattern and is NOT exported, so
// it is READ as the model and never imported. What IS shared is the layer
// contract underneath it, `customer-grid/OverlaySurface`, which already carries
// the four behaviours the done-when names: focus trap, Escape, outside-pointer
// dismiss, and focus restored to whatever was focused when the overlay mounted.
// Re-implementing those here would be a second answer to one question.
//
// β›”β›” TWO TRAPS, BOTH PAID FOR ALREADY, BOTH RESOLVED IN `styles/wave49/connectors.css`:
// (a) a portalled overlay paints its OWN background, or it renders transparent
// over whatever it covers ([[a-portal-overlay-carries-its-own-surface]]);
// (b) z-order is a THREE-WAY order, so the modal sits on the DIALOG step
// (`--cg-z-record`) and the portal step (`--cg-z-overlay`) stays above it
// ([[z-layering-is-a-three-way-order]]). Tokens, never a number.
//
// ⚠ NO CLIENT UNION OVER A SERVER VOCABULARY (the wave-9 law, and this directory's
// own header). `status` and `scope` arrive as STRINGS: a state the server adds
// later renders in the neutral tone instead of dropping the panel.
// ---------------------------------------------------------------------------
import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT } from "../apiContract";
import { BodyPortal, useOverlayLayer } from "../customer-grid/OverlaySurface";
import { ConfirmDialog } from "../ui/ConfirmDialog";
import { brandForConnector } from "./brandMarks";
import DatabasesTab, { parseDatabaseSyncHealth, useSyncNow } from "./DatabasesTab";
import type { SyncNowReceipt } from "./DatabasesTab";
import type { MaterializationCapability } from "./materializationJobs";
import "../styles/wave58/connectors.css";
import type { DatabaseReveal, DatabasesTabHandle } from "./DatabasesTab";
import KeychainTab, { amazonRotationNotice, RotationNotice, useRotationClock } from "./KeychainTab";
import MonidRunDialog from "./MonidRunDialog";
import AmazonDeletionNotice from "./AmazonDeletionNotice";
import AmazonWritesSwitch from "./AmazonWritesSwitch";
import { OdooSyncEvery } from "./OdooConfig";
import { AmazonSyncOverview, ConnectorSyncStatusLine, useConnectorSyncStatus, tileText } from "./ConnectorsPage";
import type { ConnectorRelationshipGraph, ConnectorRow } from "./ConnectorsPage";
import { parseRelationshipGraph } from "./ConnectorsPage";
import "../styles/wave49/connectors.css";
import "../styles/wave52/connectors.css";
import "../styles/wave55/connectors.css";
import "../styles/wave59/connectors.css";
import "../styles/sdlc74/connectors.css";
import "../styles/sdlc80/connector-setup.css";
import "../styles/sdlc81/connectors-type.css";
/** Retired tab keys remain aliases for existing deep links to Setup. */
export type ConnectorTab = "overview" | "setup" | "keychain" | "databases" | "relationships" | "cadence";
export function connectorTab(tab: ConnectorTab): "overview" | "setup" {
return tab === "overview" ? "overview" : "setup";
}
/** Every connector keeps the same two tabs. */
export function connectorTabs(
_row: ConnectorRow
): ReadonlyArray<{ key: ConnectorTab; label: string }> {
return [
{ key: "overview", label: "Overview" },
{ key: "setup", label: "Setup" },
];
}
interface ConnectorSyncCapability {
provider: string;
supported: boolean;
syncNow: ConnectorDetail["syncNow"];
}
/** Discover sync support without reading database pages or duplicating the provider registry. */
function useConnectorSyncCapability(connectorKey: string, refreshKey: number, directoryRow: ConnectorRow) {
const identity = JSON.stringify([connectorKey, refreshKey]);
const [reading, setReading] = useState<{
identity: string; capability: ConnectorSyncCapability | null; problem: string;
} | null>(null);
useEffect(() => {
const controller = new AbortController();
void (async () => {
try {
const response = await fetch(`${API_V1}/connectors/${encodeURIComponent(connectorKey)}/sync-capability`, {
credentials: CREDENTIALS, signal: controller.signal,
});
const body = obj(await response.json().catch(() => null));
if (controller.signal.aborted) return;
if (response.status === 401) window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT));
if (!response.ok || body.provider !== connectorKey || typeof body.supported !== "boolean") {
throw new Error("Sync status unavailable.");
}
const now = obj(body.syncNow);