// settings / ExternalAccessPane.tsx - W63-T06, rulings R4/R14, contract C7. // // This is the shared setup pane opened by the Connectors directory. OAuth clients receive the remote // MCP URL; API-key secrets appear only in the one-time reveal returned by create or rotate. All // editable metadata is seeded again from the server response. // // Setup instructions share one numbered list. Every AI client receives the public starter prompt. import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { FormEvent, ReactNode } from "react"; import { Copy } from "@phosphor-icons/react/dist/csr/Copy"; import { Check } from "@phosphor-icons/react/dist/csr/Check"; import { API_V1, CREDENTIALS, UNAUTHORIZED_EVENT, checkTenant } from "../apiContract"; import { Mark } from "../shell/Brand"; import { AiClientMark } from "./aiClientMarks"; import { KeyOpenApiRow, openApiDocumentUrl } from "./KeyOpenApiRow"; import { ExpiryPresets, presetToExpiresAt } from "./ExpiryPresets"; import type { ExpiryPreset } from "./ExpiryPresets"; import { parseTutorialGuide } from "../connectors/ConnectTutorial"; import type { TutorialGuide } from "../connectors/ConnectTutorial"; import "../connectors/connectors.css"; import "../styles/sdlc73/connectors.css"; type Access = "read" | "readwrite"; type ResourceScope = string[] | "all"; type ConnectionKind = "mcp" | "key"; // Copyable instructions never interpolate a stored credential. interface StepAction { label: string; url: string } export interface GuideStep { id?: string; title?: string; text: ReactNode; block?: string; copyValue?: string; action?: StepAction; hint?: string; details?: readonly GuideStep[]; } function GuideInstruction({ text }: { text: string }) { // Split only at an existing sentence or sequencing clause, keeping every character. const boundary = /[.!?](?=\s+[A-Z])|,(?=\s+then\b)/.exec(text); const end = boundary ? boundary.index + 1 : text.length; return

{text.slice(0, end)} {end < text.length ? {text.slice(end)} : null}

; } // S70-T09: the AI setup and connector tutorials share this actual frame and guide renderer. // Each caller owns its steps, fields and actions; the frame makes no requests. export function GuideSteps({ steps, tutorial, finalSteps = [], renderCopy, mode = "full" }: { steps: readonly GuideStep[]; tutorial?: TutorialGuide; finalSteps?: readonly GuideStep[]; renderCopy?: (value: string, index: number, step: GuideStep) => ReactNode; /** Short guides keep preparation and test limits outside the numbered instructions. */ mode?: "full" | "short"; }) { const body: readonly GuideStep[] = tutorial && mode === "full" ? [ { id: "tutorial-need", text: `What you need: ${tutorial.need}` }, ...steps, ...(tutorial.testNote ? [{ id: "tutorial-test", text: `Test: ${tutorial.testNote}` }] : []), { id: "tutorial-failure", text: `If it fails: ${tutorial.failureAction}` }, ] : steps; const entries = [...body, ...finalSteps]; if (!entries.length) return null; const content = (entry: GuideStep, index: number): ReactNode => { const copyValue = entry.copyValue ?? entry.block; return <>
{entry.title ?

{entry.title}

: typeof entry.text === "string" ? : entry.text}
{copyValue ? renderCopy?.(copyValue, index, entry) : null} {entry.title ?

{entry.text}

: null} {entry.block ?
{entry.block}
: null} {entry.hint ?

{entry.hint}

: null} {entry.action ? {entry.action.label} : null} {entry.details?.map((detail, detailIndex) =>
{content(detail, detailIndex)}
)} ; }; return <> {tutorial && mode === "short" ?

{tutorial.need}

: null}
    {entries.map((entry, index) => { return
  1. {content(entry, index)}
  2. ; })}
{tutorial && mode === "short" ?
{tutorial.testNote ?

{tutorial.testNote}

: null}

{tutorial.failureAction}

: null} ; } export function ConnectionWizard({ title, titleId, metadata, footer, children }: { title: string; titleId: string; metadata?: ReactNode; footer?: ReactNode; children: ReactNode; }) { return

{title}

{metadata}
{children}
{footer ? : null}
; } // Client identity and grant matching stay stable when the served instructions change. export const CLIENTS = [ { id: "claude", label: "Claude.ai", connections: ["mcp"], skill: false, match: ["claude"] }, { id: "chatgpt", label: "ChatGPT", connections: ["mcp"], skill: false, match: ["chatgpt", "chat gpt"] }, { id: "claude-code", label: "Claude Code", connections: ["mcp", "key"], skill: true, match: ["claude code", "claude-code", "claude_code"] }, { id: "codex", label: "Codex", connections: ["mcp", "key"], skill: true, match: ["codex"] }, { id: "cursor", label: "Cursor", connections: ["mcp", "key"], skill: true, match: ["cursor"] }, { id: "muse", label: "Meta Muse", connections: ["key"], skill: false, match: ["muse", "meta muse"] }, ] as const satisfies readonly { id: string; label: string; connections: readonly ConnectionKind[]; skill: boolean; match: readonly string[]; }[]; export type ClientId = (typeof CLIENTS)[number]["id"]; interface ServedStep { title?: string; text: string; block?: string; action?: StepAction } interface ClientGuide { verified: string; documentation?: string; provenance: string; need: string; steps: ServedStep[]; keySteps?: ServedStep[]; caveat: string; failureAction: string; testNote: string; tutorial: TutorialGuide; keyTutorial?: TutorialGuide; } interface ClientStepsResponse { starterPrompt: string; clients: Record; shared: { connection: Record; skill: ServedStep; verification: Record<"mcp" | "key" | "activeKey" | "newKey" | "savedKey" | "noGrant" | "otherGrant", string>; keySetup: Record<"saved" | "saveNew", string>; }; } export function parseClientSteps(value: unknown): ClientStepsResponse | null { if (!value || typeof value !== "object") return null; const data = value as Partial; const text = (item: unknown): item is string => typeof item === "string" && item.trim() !== ""; const action = (item: unknown): item is StepAction => { if (!item || typeof item !== "object" || Array.isArray(item)) return false; const row = item as Partial; if (!text(row.label) || row.label !== row.label.trim() || /[\x00-\x1f]/.test(row.label) || !text(row.url) || !/^https:\/\/[^/?#]+/.test(row.url) || /[\s\\\x00-\x1f\x7f]/.test(row.url) || /%(?![0-9a-fA-F]{2})/.test(row.url)) return false; try { const url = new URL(row.url); return url.protocol === "https:" && !!url.hostname && !url.username && !url.password; } catch { return false; } }; const step = (item: unknown): item is ServedStep => { if (!item || typeof item !== "object") return false; const row = item as Partial; return text(row.text) && (row.block === undefined || text(row.block)) && (row.action === undefined || action(row.action)); }; const steps = (items: unknown) => Array.isArray(items) && items.length >= 2 && items.length <= 3 && items.every((item) => step(item) && text(item.title) && item.title.length <= 48 && text(item.block) && !/\bTest\s*:/i.test(`${item.title} ${item.text} ${item.block}`)); const shared = data.shared; if (!text(data.starterPrompt) || data.starterPrompt.length >= 600 || !data.clients || !shared || !step(shared.skill) || !text(shared.skill.block) || !text(shared.connection?.mcp) || !text(shared.connection?.key) || !["mcp", "key", "activeKey", "newKey", "savedKey", "noGrant", "otherGrant"].every( (key) => text(shared.verification?.[key as keyof typeof shared.verification])) || !text(shared.keySetup?.saved) || !text(shared.keySetup?.saveNew)) return null; const clients = {} as Record; for (const client of CLIENTS) { const guide = data.clients[client.id]; if (!guide || !text(guide.verified) || !/^\d{4}-\d{2}-\d{2}$/.test(guide.verified) || !Number.isFinite(Date.parse(guide.verified)) || !text(guide.provenance) || (client.id === "muse" ? guide.documentation !== undefined : !text(guide.documentation) || !/^https:\/\//.test(guide.documentation)) || !text(guide.caveat) || !steps(guide.steps) || (guide.keySteps !== undefined && !steps(guide.keySteps)) || ((client.connections as readonly ConnectionKind[]).includes("key") && !steps(guide.keySteps))) return null; const tutorial = parseTutorialGuide({ ...guide, steps: guide.steps.map((entry) => entry.text) }, "ai"); const keyTutorial = (client.connections as readonly ConnectionKind[]).includes("key") ? parseTutorialGuide({ ...guide, steps: guide.keySteps!.map((entry) => entry.text) }, "ai") : null; if (!tutorial || ((client.connections as readonly ConnectionKind[]).includes("key") && !keyTutorial)) return null; clients[client.id] = { ...guide, tutorial, ...(keyTutorial ? { keyTutorial } : {}) }; } return { ...data, clients } as ClientStepsResponse; } export function isClientId(value: unknown): value is ClientId { return typeof value === "string" && CLIENTS.some((entry) => entry.id === value); } interface ExternalKeyMetadata { id: string; label: string; created: string; last_used: string | null; revoked_at: string | null; access: Access; databases: ResourceScope; expires_at: string | null; } interface ScopeDatabase { database: string; label: string } interface ExternalConnection { id: string; // This field holds the grant id; its existing name keeps disconnect URLs addressing the server's connection id. client: string; clientId: ClientId | null; label: string | null; status: "connected" | "expired" | "disconnected"; created: string | null; last_used: string | null; expires_at: string | null; disconnected_at: string | null; access: Access | null; databases: ResourceScope | null; } interface KeyListResponse { keys: ExternalKeyMetadata[]; can_mint: boolean } interface ConnectionListResponse { connections: unknown[] } interface MintResponse { key: ExternalKeyMetadata; secret: string } interface KeyDraft { label: string; access: Access; databaseMode: "all" | "subset"; databases: string[]; expiryPreset: ExpiryPreset; } const KEY_REFUSALS = { minted_elsewhere: "This key was minted on another Space. Create a key on this Space", revoked: "This key was revoked. Create a new key", expired: "This key expired. Update its expiry or create a new key", unknown_key: "This key is unknown to your account on this Space. Paste your saved key or create a new one", } as const; type KeyRefusal = keyof typeof KEY_REFUSALS; interface OwnerKeyVerification { valid: boolean; cause: KeyRefusal | null; warning: "store_write_refused" | null; origin_recorded: boolean | null; key_id?: string; } type VerifyResult = { state: "ok" | "failed"; message: string; cause?: KeyRefusal | "store_write_refused" }; type ConfirmedConnection = { clientId: ClientId } & ( { kind: "mcp"; grantId: string } | { kind: "key"; keyId: string } ); type KeyChoice = "create" | "saved"; type ApiResult = | { ok: true; data: T } | { ok: false; message: string; status: number }; // The one spelling of the OAuth connections route. The pane reads it on mount and again when // the MCP step verifies, and two copies of a route are two things to keep in step. const CONNECTIONS_PATH = "/external/oauth/connections"; function messageFrom(body: unknown, fallback: string): string { if (!body || typeof body !== "object") return fallback; const error = (body as { error?: unknown }).error; if (!error || typeof error !== "object") return fallback; const message = (error as { message?: unknown }).message; return typeof message === "string" && message.trim() !== "" ? message : fallback; } async function call(path: string, init?: RequestInit): Promise> { try { const response = await fetch(`${API_V1}${path}`, { credentials: CREDENTIALS, ...init }); if (checkTenant(response)) { return { ok: false, message: "This workspace changed. Reloading.", status: 409 }; } let body: unknown = null; try { body = await response.json(); } catch { /* Keep non-JSON failures generic. */ } if (!response.ok) { if (response.status === 401 && typeof window !== "undefined") { window.dispatchEvent(new CustomEvent(UNAUTHORIZED_EVENT)); } return { ok: false, status: response.status, message: response.status >= 500 ? "The AI API is unavailable right now." : messageFrom(body, "That request could not be completed."), }; } return { ok: true, data: body as T }; } catch { return { ok: false, message: "The server could not be reached.", status: 0 }; } } function parseKey(value: unknown): ExternalKeyMetadata | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const row = value as Record; if (typeof row.id !== "string" || typeof row.label !== "string" || typeof row.created !== "string") { return null; } const databases = Array.isArray(row.databases) && row.databases.every( (database): database is string => typeof database === "string" && database.trim() !== "", ) ? row.databases.map((database) => database.trim()) : "all"; return { id: row.id, label: row.label, created: row.created, last_used: typeof row.last_used === "string" ? row.last_used : null, revoked_at: typeof row.revoked_at === "string" ? row.revoked_at : null, access: row.access === "read" ? "read" : "readwrite", databases, expires_at: typeof row.expires_at === "string" ? row.expires_at : null, }; } function parseConnection(value: unknown): ExternalConnection | null { if (!value || typeof value !== "object" || Array.isArray(value)) return null; const row = value as Record; if (typeof row.id !== "string" || !row.id.trim()) return null; const label = typeof row.label === "string" ? row.label : null; // Prefer the longest matching name, so Claude Code resolves before the broader Claude match. const resolved = CLIENTS.flatMap((entry) => entry.match.map((match) => ({ id: entry.id, match }))) .sort((a, b) => b.match.length - a.match.length) .find((entry) => label?.toLowerCase().includes(entry.match))?.id; const expires_at = typeof row.expires_at === "string" ? row.expires_at : null; const disconnected_at = typeof row.disconnected_at === "string" ? row.disconnected_at : null; return { id: row.id, client: row.id, clientId: isClientId(resolved) ? resolved : null, label, status: disconnected_at ? "disconnected" : expires_at && Date.parse(expires_at) <= Date.now() ? "expired" : "connected", created: typeof row.created === "string" ? row.created : null, last_used: typeof row.last_used === "string" ? row.last_used : null, expires_at, disconnected_at, access: row.access === "read" || row.access === "readwrite" ? row.access : null, databases: row.databases === "all" ? "all" : Array.isArray(row.databases) ? row.databases.filter((item): item is string => typeof item === "string") : null, }; } function when(value: string | null): string { if (!value) return "Never"; const parsed = new Date(value); if (Number.isNaN(parsed.getTime())) return "Unknown"; return parsed.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short" }); } function keyExpiryLabel(key: ExternalKeyMetadata): string { if (!key.expires_at) return "No expiry"; if (Date.parse(key.expires_at) <= Date.now()) return "Expired"; return `Expires ${when(key.expires_at)}`; } function draftFor(key: ExternalKeyMetadata): KeyDraft { return { label: key.label, access: key.access, databaseMode: key.databases === "all" ? "all" : "subset", databases: key.databases === "all" ? [] : [...key.databases], expiryPreset: "keep", }; } function connectionLabel(connection: ExternalConnection | undefined): string { if (!connection || connection.status === "disconnected") return "Not connected"; if (connection.status === "connected") return "Connected"; if (connection.status === "expired") return "Reconnect required"; return "Not connected"; } function SettingsSkeleton({ label }: { label: string }) { return
; } /** The directory selects a client; this pane remains the one setup and credential implementation. */ export default function ExternalAccessPane({ initialClient, view = "all", settings = false, onChanged, onOpenApi, }: { initialClient?: ClientId; view?: "all" | "client" | "api"; settings?: boolean; onChanged?: () => void; onOpenApi?: () => void; } = {}) { const initialEntry = CLIENTS.find((entry) => entry.id === initialClient); const [clientId, setClientId] = useState(initialClient ?? null); const [connection, setConnection] = useState( initialEntry?.connections[0] ?? null, ); const [showSetup, setShowSetup] = useState(!settings || view === "api"); const [keyChoice, setKeyChoice] = useState(view === "client" ? "saved" : "create"); const [selectedKeyId, setSelectedKeyId] = useState(""); const [verifyResult, setVerifyResult] = useState(null); const [confirmedConnection, setConfirmedConnection] = useState(null); const [verifySecret, setVerifySecret] = useState(""); const verificationVersion = useRef(0); const [keys, setKeys] = useState(null); const [keysError, setKeysError] = useState(""); const [connections, setConnections] = useState([]); const [connectionsLoading, setConnectionsLoading] = useState(view !== "api"); const [connectionsError, setConnectionsError] = useState(""); const [clientSteps, setClientSteps] = useState(null); const [stepsError, setStepsError] = useState(""); const [stepsLoading, setStepsLoading] = useState(view !== "api"); const [canMint, setCanMint] = useState(null); const [label, setLabel] = useState(""); const [access, setAccess] = useState("read"); const [databaseMode, setDatabaseMode] = useState<"all" | "subset">("all"); const [selectedDatabases, setSelectedDatabases] = useState([]); const [expiryPreset, setExpiryPreset] = useState("1-year"); const [scopeDatabases, setScopeDatabases] = useState(null); const [scopeError, setScopeError] = useState(""); const [scopeRevision, setScopeRevision] = useState(0); const [editing, setEditing] = useState(null); const [editDraft, setEditDraft] = useState(null); const [busy, setBusy] = useState(""); const [error, setError] = useState(""); const [notice, setNotice] = useState(""); const [revealed, setRevealed] = useState(null); // The client view closes its in-step reveal but keeps the secret in memory for the verify step. const [revealClosed, setRevealClosed] = useState(false); const [copied, setCopied] = useState(""); const copyTimer = useRef | null>(null); const savedKeySelect = useRef(null); useEffect(() => () => { if (copyTimer.current !== null) clearTimeout(copyTimer.current); }, []); const mcpUrl = useMemo(() => { const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return `${origin}${API_V1}/external/mcp`; }, []); const openApiUrl = useMemo(() => { const origin = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return openApiDocumentUrl(API_V1, origin); }, []); const client = CLIENTS.find((entry) => entry.id === clientId); const guide = client ? clientSteps?.clients[client.id] : undefined; const sharedSteps = clientSteps?.shared; // Replace only known text tokens. React escapes the result, including command placeholders. function instruction(value: string): string { const base = typeof window === "undefined" ? "https://your-loopable-host" : window.location.origin; return value.replace(/||/g, (token) => token === "" ? base : token === "" ? mcpUrl : client?.label ?? ""); } function guideStep(step: ServedStep): GuideStep { return { title: step.title, text: instruction(step.text), ...(step.block ? { block: instruction(step.block) } : {}), ...(step.action ? { action: step.action } : {}) }; } const starterPrompt = view === "client" && clientSteps ? instruction(clientSteps.starterPrompt) : null; const connectionKinds: readonly ConnectionKind[] = client?.connections ?? []; const selectedKey = keys?.find((key) => key.id === selectedKeyId); const keyIsActive = (key: ExternalKeyMetadata) => !key.revoked_at && (!key.expires_at || Date.parse(key.expires_at) > Date.now()); const selectedKeyIsActive = selectedKey !== undefined && keyIsActive(selectedKey); // The client view opens on a saved key only when an active one exists. const shownKeyChoice: KeyChoice = view === "client" && canMint === true && keys !== null && !keys.some(keyIsActive) ? "create" : keyChoice; const stepReveal = view === "client" && !revealClosed ? revealed : null; // A reveal from a different key must never silently replace the saved key the user chose. const verificationReveal = revealed?.key.id === selectedKeyId ? revealed : null; const confirmedGrant = confirmedConnection?.kind === "mcp" ? connections.find((grant) => grant.id === confirmedConnection.grantId && grant.clientId === clientId) : undefined; const confirmationIsActive = confirmedConnection?.clientId === clientId && ( connection === "mcp" && confirmedConnection?.kind === "mcp" && !connectionsLoading && !connectionsError && confirmedGrant?.status === "connected" && !confirmedGrant.disconnected_at && (!confirmedGrant.expires_at || Date.parse(confirmedGrant.expires_at) > Date.now()) || connection === "key" && confirmedConnection?.kind === "key" && confirmedConnection.keyId === selectedKeyId && selectedKeyIsActive ); const canCopyStarterPrompt = view === "client" && showSetup && confirmationIsActive; const confirmationExpiresAt = connection === "key" ? selectedKey?.expires_at : confirmedGrant?.expires_at; useEffect(() => { if (!confirmedConnection) return; const invalidate = () => { verificationVersion.current += 1; setConfirmedConnection(null); setVerifyResult(null); setCopied(""); }; if (!confirmationIsActive) { invalidate(); return; } if (!confirmationExpiresAt) return; let timer: ReturnType; const schedule = () => { const remaining = Date.parse(confirmationExpiresAt) - Date.now(); if (remaining <= 0) { invalidate(); return; } timer = setTimeout(schedule, Math.min(remaining, 2_147_483_647)); }; schedule(); return () => clearTimeout(timer); }, [confirmedConnection, confirmationIsActive, confirmationExpiresAt]); useEffect(() => { if (revealClosed) savedKeySelect.current?.focus(); }, [revealClosed]); function resetVerification() { verificationVersion.current += 1; setConfirmedConnection(null); setVerifyResult(null); setVerifySecret(""); setCopied(""); } function chooseClient(id: ClientId) { const entry = CLIENTS.find((candidate) => candidate.id === id); if (id !== clientId) { setClientId(id); setConnection(entry?.connections[0] ?? null); resetVerification(); setCopied(""); setError(""); setNotice(""); } } function chooseConnection(kind: ConnectionKind) { if (kind !== connection) { setConnection(kind); resetVerification(); setCopied(""); setError(""); setNotice(""); } } function chooseKey(id: string) { setSelectedKeyId(id); resetVerification(); } const load = useCallback(async () => { setKeysError(""); const result = await call("/external/keys"); if (!result.ok) { setKeys(null); setCanMint(null); setKeysError(result.message); setError(result.message); return; } if (!Array.isArray(result.data?.keys) || typeof result.data.can_mint !== "boolean") { setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response."); setError("The AI API returned an unreadable response."); return; } const parsed = result.data.keys.map(parseKey); if (parsed.some((row) => row === null)) { setKeys(null); setCanMint(null); setKeysError("The AI API returned an unreadable response."); setError("The AI API returned an unreadable response."); return; } setKeys(parsed as ExternalKeyMetadata[]); setCanMint(result.data.can_mint); setError(""); }, []); const loadConnections = useCallback(async (confirmClient = true) => { const version = verificationVersion.current; if (connection === "mcp") { setConfirmedConnection(null); setVerifyResult(null); setCopied(""); } setConnectionsLoading(true); setConnectionsError(""); const result = await call(CONNECTIONS_PATH); setConnectionsLoading(false); if (version !== verificationVersion.current) return; if (!result.ok || !Array.isArray(result.data?.connections)) { // Key management remains usable if OAuth discovery is unavailable. setConnectionsError(result.ok ? "Connections could not be loaded." : result.message); return; } const parsed = result.data.connections.map(parseConnection); if (parsed.some((row) => row === null)) { setConnectionsError("Connections could not be loaded."); return; } const grants = parsed as ExternalConnection[]; setConnections(grants); const matched = grants.find((grant) => grant.clientId === clientId && grant.status === "connected" && (!grant.expires_at || Date.parse(grant.expires_at) > Date.now())); if (confirmClient && connection === "mcp" && clientId && matched) { setConfirmedConnection({ clientId, kind: "mcp", grantId: matched.id }); } }, [clientId, connection]); const loadClientSteps = useCallback(async () => { setStepsLoading(true); setStepsError(""); setClientSteps(null); const result = await call("/connectors/ai-client-steps"); const parsed = result.ok ? parseClientSteps(result.data) : null; setStepsLoading(false); if (!parsed) { setStepsError(result.ok ? "AI client instructions could not be read." : result.message); return; } setClientSteps(parsed); }, []); useEffect(() => { if (view !== "api") void loadClientSteps(); }, [loadClientSteps, view]); useEffect(() => { if (view !== "client" || connection === "key") void load(); }, [load, view, connection]); useEffect(() => { if (view !== "api") void loadConnections(); }, [loadConnections, view]); const visibleConnections = view === "client" ? connections.filter((entry) => entry.clientId === initialClient) : connections; // Report changed metadata only. Secrets remain inside this pane's one-time reveal. const changed = useRef(false); useEffect(() => { if (changed.current) onChanged?.(); changed.current = true; }, [keys, connections, onChanged]); useEffect(() => { if (canMint !== true) return; let active = true; setScopeDatabases(null); setScopeError(""); void call<{ databases: ScopeDatabase[] }>("/external/scope/databases").then((result) => { if (!active) return; if (!result.ok) { setScopeError(result.message); setScopeDatabases([]); return; } const rows = result.data?.databases; if (!Array.isArray(rows) || rows.some((row) => !row || typeof row.database !== "string" || !row.database.trim())) { setScopeError("The database list could not be read."); setScopeDatabases([]); return; } setScopeError(""); setScopeDatabases(rows.map((row) => ({ database: row.database, label: typeof row.label === "string" && row.label.trim() ? row.label : row.database, }))); }); return () => { active = false; }; }, [canMint, scopeRevision]); function databaseLabels(databases: ResourceScope): string { if (databases === "all") return "All databases"; if (databases.length === 0) return "No databases"; const labels = databases.slice(0, 4).map((database) => ( scopeDatabases?.find((row) => row.database === database)?.label || database )); return labels.join(", ") + (databases.length > 4 ? ` and ${databases.length - 4} more` : ""); } function selectedScope(mode: "all" | "subset", selected: string[]): ResourceScope { return mode === "all" ? "all" : selected; } function validateDraft(draft: KeyDraft): string { if (!draft.label.trim()) return "Enter a label for this API key."; if (draft.databaseMode === "subset" && draft.databases.length === 0) { return "Choose at least one database for this API key."; } return ""; } async function create(event: FormEvent) { event.preventDefault(); const draft: KeyDraft = { label, access: access as Access, databaseMode, databases: selectedDatabases, expiryPreset, }; const invalid = validateDraft(draft); if (invalid) { setError(invalid); return; } const databases = selectedScope(databaseMode, selectedDatabases); setBusy("create"); setError(""); setNotice(""); resetVerification(); const result = await call("/external/keys", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: label.trim(), access: access, databases: databases, resources: databases, expires_at: presetToExpiresAt(expiryPreset, new Date()), }), }); setBusy(""); if (!result.ok) { setError(result.message); return; } const key = parseKey(result.data?.key); if (!key || typeof result.data?.secret !== "string" || result.data.secret === "") { setError("The API key was created, but its secret could not be read."); void load(); return; } setKeys((current) => [key, ...(current ?? []).filter((row) => row.id !== key.id)]); setLabel(""); setAccess("read"); setDatabaseMode("all"); setSelectedDatabases([]); setExpiryPreset("1-year"); setCopied(""); setRevealed({ key, secret: result.data.secret }); setSelectedKeyId(key.id); setKeyChoice("saved"); setRevealClosed(false); } async function copy(value: string, name: string) { if (copyTimer.current !== null) clearTimeout(copyTimer.current); setCopied(""); setBusy(`copy:${name}`); try { await navigator.clipboard.writeText(value); setCopied(name); setError(""); copyTimer.current = setTimeout(() => { setCopied(""); copyTimer.current = null; }, 2000); } catch { setCopied(""); setError("That text could not be copied. Select it and copy it manually."); } finally { setBusy((current) => current === `copy:${name}` ? "" : current); } } async function saveEdit(event: FormEvent) { event.preventDefault(); if (!editing || !editDraft) return; const invalid = validateDraft(editDraft); if (invalid) { setError(invalid); return; } const databases = selectedScope(editDraft.databaseMode, editDraft.databases); setBusy(`edit:${editing}`); setError(""); setNotice(""); resetVerification(); const result = await call<{ key: ExternalKeyMetadata }>(`/external/keys/${encodeURIComponent(editing)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ label: editDraft.label.trim(), access: editDraft.access, databases: databases, ...(editDraft.expiryPreset === "keep" ? {} : { expires_at: presetToExpiresAt(editDraft.expiryPreset, new Date()), }), }), }); setBusy(""); if (!result.ok) { setError(result.message); return; } const saved = parseKey(result.data?.key); if (!saved) { setError("The API key was updated, but its metadata could not be read."); void load(); return; } setKeys((current) => (current ?? []).map((row) => row.id === saved.id ? saved : row)); setEditing(null); setEditDraft(null); setNotice("API key settings saved."); } async function rotate(key: ExternalKeyMetadata) { if (!window.confirm(`Rotate "${key.label}"? Its current secret will stop working immediately.`)) return; setBusy(`rotate:${key.id}`); setError(""); setNotice(""); resetVerification(); const result = await call(`/external/keys/${encodeURIComponent(key.id)}/rotate`, { method: "POST" }); setBusy(""); if (!result.ok) { setError(result.message); return; } const replacement = parseKey(result.data?.key); if (!replacement || typeof result.data?.secret !== "string" || !result.data.secret) { setError("The API key was rotated, but its replacement secret could not be read."); void load(); return; } setKeys((current) => (current ?? []).map((row) => row.id === key.id ? replacement : row)); setSelectedKeyId((current) => current === key.id ? replacement.id : current); setEditing(null); setEditDraft(null); setCopied(""); setRevealed({ key: replacement, secret: result.data.secret }); } async function revoke(key: ExternalKeyMetadata) { if (!window.confirm(`Revoke "${key.label}"? Its next request will be refused.`)) return; setBusy(`revoke:${key.id}`); setError(""); setNotice(""); resetVerification(); const result = await call<{ key: ExternalKeyMetadata }>( `/external/keys/${encodeURIComponent(key.id)}/revoke`, { method: "POST" }, ); setBusy(""); if (!result.ok) { setError(result.message); return; } setKeys((current) => (current ?? []).filter((row) => row.id !== key.id)); if (revealed?.key.id === key.id) setRevealed(null); if (editing === key.id) { setEditing(null); setEditDraft(null); } setNotice("API key revoked. Its next request will be refused."); } async function disconnect(connection: ExternalConnection) { const name = connection.label?.trim() || CLIENTS.find((entry) => entry.id === connection.clientId)?.label || "this AI app"; if (!window.confirm(`Disconnect ${name} from Loopable?`)) return; setBusy(`disconnect:${connection.client}`); setError(""); resetVerification(); const result = await call<{ connection: unknown }>( `/external/oauth/connections/${encodeURIComponent(connection.client)}/disconnect`, { method: "POST" }, ); setBusy(""); if (!result.ok) { setError(result.message); return; } setConnections((current) => current.filter((grant) => grant.id !== connection.id)); void loadConnections(false); setNotice("AI app disconnected. Its next request will be refused."); } async function verifyKey() { const useSelectedKey = view === "client"; const secret = (useSelectedKey ? verificationReveal?.secret : undefined) ?? verifySecret.trim(); if (!secret || busy !== "" || canMint !== true) return; setBusy("verify:key"); setConfirmedConnection(null); setVerifyResult(null); setCopied(""); const version = ++verificationVersion.current; const report = (state: VerifyResult["state"], message: string, cause?: VerifyResult["cause"]) => { if (version !== verificationVersion.current) return; setVerifyResult({ state, message, cause }); if (state === "ok" && useSelectedKey && clientId && selectedKeyIsActive) { setConfirmedConnection({ clientId, kind: "key", keyId: selectedKeyId }); } }; try { const result = await call("/external/keys/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ token: secret }), }); if (version !== verificationVersion.current) return; if (!result.ok) { report("failed", result.status === 403 ? "Verifying API keys requires AI apps access. Ask an administrator for access" : "Could not verify the API key. Try again"); return; } const diagnosis = result.data; if (diagnosis?.valid === false && diagnosis.cause && Object.prototype.hasOwnProperty.call(KEY_REFUSALS, diagnosis.cause)) { report("failed", KEY_REFUSALS[diagnosis.cause], diagnosis.cause); return; } if (diagnosis?.valid !== true || diagnosis.cause !== null || typeof diagnosis.origin_recorded !== "boolean" || typeof diagnosis.key_id !== "string" || (diagnosis.warning !== null && diagnosis.warning !== "store_write_refused")) { report("failed", "The AI API returned an unreadable response."); return; } if (useSelectedKey && selectedKeyId && diagnosis.key_id !== selectedKeyId) { report("failed", "This secret does not match the selected API key."); return; } const warning = diagnosis.warning === "store_write_refused" ? ". The last-used store write was refused. Retry Verify to save it" : ""; const origin = diagnosis.origin_recorded ? "" : ". This legacy key has no recorded Space origin. Its minting Space cannot be proved"; report("ok", `API key accepted${warning}${origin}`, diagnosis.warning ?? undefined); } catch { report("failed", "The server could not be reached."); } finally { setVerifySecret(""); setBusy((current) => current === "verify:key" ? "" : current); } } async function verifyMcp() { if (!client || !sharedSteps || busy !== "" || connection !== "mcp") return; setBusy("verify:mcp"); setConfirmedConnection(null); setVerifyResult(null); setCopied(""); const version = ++verificationVersion.current; // OAuth grants belong to the signed-in session, independently of the API-key bearer check. const result = await call(CONNECTIONS_PATH); setBusy((current) => current === "verify:mcp" ? "" : current); if (version !== verificationVersion.current) return; if (!result.ok) { setVerifyResult({ state: "failed", message: result.status ? `${result.status}: ${result.message}` : result.message }); return; } if (!Array.isArray(result.data?.connections)) { setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." }); return; } const parsed = result.data.connections.map(parseConnection); const grants = parsed.filter((row): row is ExternalConnection => row !== null); if (grants.length !== parsed.length) { setVerifyResult({ state: "failed", message: "The AI API returned an unreadable response." }); return; } setConnections(grants); setConnectionsError(""); const live = grants.filter((grant) => grant.status === "connected" && (!grant.expires_at || Date.parse(grant.expires_at) > Date.now())); const matched = live.find((grant) => grant.clientId === client.id); if (matched) { setConfirmedConnection({ clientId: client.id, kind: "mcp", grantId: matched.id }); setVerifyResult({ state: "ok", message: `Loopable sign-in completed for ${matched.label}. Last used: ${when(matched.last_used)}.` }); } else if (live.length) { setVerifyResult({ state: "failed", message: `Connected: ${live.map((grant) => grant.label || "Unnamed AI app").join(", ")}. ${instruction(sharedSteps.verification.otherGrant)}` }); } else { setVerifyResult({ state: "failed", message: instruction(sharedSteps.verification.noGrant) }); } } function databaseChecks(selected: string[], change: (next: string[]) => void) { return (
{scopeDatabases === null ? : null} {scopeError ?
Could not read the database list.
: null} {scopeDatabases?.map((database) => ( ))} {selected.length === 0 ?

Choose at least one database for this API key.

: null}
); } function codeBlock(value: string, name: string, content?: ReactNode) { return (
{content ?? value}
); } function clientGuide(kind: ConnectionKind): GuideStep[] { if (!guide) return []; const tutorial = kind === "mcp" ? guide.tutorial : guide.keyTutorial; if (!tutorial) return []; return (kind === "mcp" ? guide.steps : guide.keySteps ?? []).map((step, index) => ({ ...guideStep({ ...step, text: tutorial.steps[index] }), id: `client-step-${index}` })); } function clientSetupSteps(keySteps: GuideStep[], completionSteps: GuideStep[]): GuideStep[] { if (view === "api") return keySteps; if (!connection) return []; const steps = clientGuide(connection); return steps.map((step, index) => ({ ...step, details: [ ...(index === 0 ? keySteps : []), ...(index === steps.length - 1 ? completionSteps : []), ] })); } function revealPanel(reveal: MintResponse, close: ReactNode) { return <>

Copy it now. Loopable cannot show this secret again.

{close}
; } // The client view shows its reveal inside the key step, so only the other views draw this card. const revealCard = revealed && view !== "client" ? (

API key

{revealPanel(revealed, )}
) : null; return (
{view === "all" ?

Loopable connections

: null} {error ?

{error}

: null} {notice ?

{notice}

: null} {view !== "api" && connectionsLoading ? : null} {view !== "api" && connectionsError ? (
Could not load connections.
) : null} {!showSetup && view === "client" && !connectionsLoading ? (
) : null} {showSetup ? {clientId === "muse" ? "Setup guide" : <> Checked {" · "} Documentation }

: undefined}> {view !== "api" ? ( <>
{CLIENTS.map((entry) => ( ))}
) : null} {view !== "api" && client && connectionKinds.length > 1 ? ( <>

How should {client.label} reach Loopable?

{connectionKinds.includes("mcp") ? ( ) : null} {connectionKinds.includes("key") ? ( ) : null}
) : null}
{view !== "api" && stepsLoading ? : null} {view !== "api" && stepsError ?
Could not read the instructions.
: null} {view === "api" || (guide && sharedSteps) ? { const name = `guide:${clientId}:${connection}:${step.id ?? index}`; const isStarter = step.id === "starter-prompt"; return ; }} steps={clientSetupSteps([ ...((connection === "key" && client) || view === "api" ? [{ id: "key-step", text: stepReveal ? (
{revealPanel(stepReveal, )}
) : <> {view === "all" || (view === "client" && canMint === true) ?
: null} {keysError ? (

{keysError}

) : keys === null ? ( ) : keys.length === 0 ? (

{view === "client" ? "No saved API keys." : "You have no saved keys yet, so create one here."}

) : !keys.some(keyIsActive) ? (

{view === "client" ? "No active API keys." : "No saved key is active. Create one or update its expiry below."}

) : null} {canMint === false ? (

Creating API keys requires AI apps access. Ask an administrator for access

) : null} {(shownKeyChoice === "create" || view === "api") && canMint === true ? (
void create(event)}>
setLabel(event.currentTarget.value)} />
{databaseMode === "subset" ? databaseChecks(selectedDatabases, setSelectedDatabases) : null}
) : null} {shownKeyChoice === "saved" && client && keys && keys.length > 0 ? (

{sharedSteps ? instruction(sharedSteps.keySetup.saved) : null}

{verificationReveal && view !== "client" ?

{sharedSteps?.keySetup.saveNew}

: null}
) : null} {view === "client" && onOpenApi ? (
) : null} }] : []), ], [ ...(view !== "api" && client?.skill && connection && sharedSteps ? [guideStep(sharedSteps.skill)] : []), ...(view !== "api" && client && connection && sharedSteps ? [{ text: <> {connection === "key" ? ( <> {selectedKey ?

Key: {selectedKey.label}

: null} {verificationReveal ?

{sharedSteps.verification.newKey}

: (
{ resetVerification(); setVerifySecret(event.currentTarget.value); }} />

{sharedSteps.verification.savedKey}

)}

{sharedSteps.verification.key}

) : ( )}
{connection === "key" ? ( ) : ( )}
{verifyResult ? (

{verifyResult.message}

) : null} }] : []), ...(starterPrompt ? [{ id: "starter-prompt", text: "Starter prompt", block: starterPrompt, copyValue: starterPrompt, hint: canCopyStarterPrompt ? undefined : "Verify the connection to copy the starter prompt." }] : []), ])} /> : null}
: null} {revealCard} {view !== "client" ?

Verify

{keysError ?
Could not load API key access
: canMint === null ? : canMint === false ?

Verifying API keys requires AI apps access. Ask an administrator for access

:
{ event.preventDefault(); void verifyKey(); }}>
{ resetVerification(); setVerifySecret(event.currentTarget.value); }} />

Paste your saved key, including a revoked or expired key

} {verifyResult ?

{verifyResult.message}

: null}
: null} {view !== "api" && visibleConnections.length > 0 ? ( /* HOTFIX 2026-09-24 (owner: the AI connections list "is really ugly, let's make it look like a Grid view"). One row per connection in the Data grid's own look: row numbers, a washed header, hairline cells and a status pill (`index.css` `.ea-grid`). */

AI connections

{visibleConnections.map((connection, index) => ( ))}
Row AI app Status Access Databases Connected Last used Actions
{index + 1} {connection.clientId ? : null} {connection.label || "Unnamed AI app"} {connectionLabel(connection)} {connection.access === null ? "" : connection.access === "read" ? "Read only" : "Read and write"} {connection.databases === null ? "" : databaseLabels(connection.databases)} {when(connection.created)} {when(connection.last_used)} {connection.status === "connected" ? ( ) : null}
) : null} {view !== "client" ? <>

API keys

{keysError ?
Could not load API keys.
: keys === null ? : keys.length === 0 ?

You have no API keys yet.

: (
{keys.map((key) => (
{editing === key.id && editDraft ? (
void saveEdit(event)}>

Edit API key

setEditDraft({ ...editDraft, label: event.currentTarget.value })} />
{editDraft.databaseMode === "subset" ? databaseChecks(editDraft.databases, (databases) => setEditDraft({ ...editDraft, databases })) : null} {keyExpiryLabel(key) === "Expired" ?

Expired

: null} setEditDraft({ ...editDraft, expiryPreset })} />
) : ( <>

{key.label}

Access {key.access === "read" ? "Read only" : "Read and write"}
Resources {databaseLabels(key.databases)}
Expiry {keyExpiryLabel(key)}
Last used {when(key.last_used)}
{keyIsActive(key) ? codeBlock(value, `openapi:${key.id}:${name}`, content)} /> : null}
)}
))}
)} : null}
); }