import { useEffect, useRef, useState } from "octane"; import { Button } from "octane-kumo/components/button"; import { LayerCard } from "octane-kumo/components/layer-card"; import { usePublisherSession } from "./PublisherQueryProvider"; import { useInstallationQuery } from "./queries/use-installation-query"; import { useProviderQuery } from "./queries/use-provider-query"; import type { usePublisherIdentityQuery } from "./queries/use-publisher-identity-query"; import { PublisherReadError } from "./publisher-request"; type State = "loading" | "confirm" | "provisioning" | "error" | "reconnect" | "success"; function safeMessage(status: number, code: unknown) { if (status === 403) return "You do not have permission to manage this installation."; if (status === 404) return "This installation could not be found. Check the setup link and try again."; if (status === 503 && code === "resource_conflict") return "OpenRouter setup conflicts with an existing Cloudflare resource. Resolve the conflicting resource, then retry."; if (status === 503 && code === "setup_required") return "This installation needs setup or an upgrade before OpenRouter can be enabled."; return "OpenRouter setup is temporarily unavailable. Try again."; } async function responseJson( response: Response, ): Promise> { try { const value = await response.json(); return typeof value === "object" && value !== null ? value : {}; } catch { return {}; } } export function ProviderSetup({ installationId, identity, }: { installationId: string; identity: ReturnType; }) { const [commandState, setState] = useState(null); const [commandError, setError] = useState(""); const cache = usePublisherSession(); const epoch = cache.getSnapshot().epoch; const installation = useInstallationQuery({ id: installationId }); const query = useProviderQuery( installationId, installation.data?.installation.accountId ?? "", commandState !== "provisioning" && commandState !== "success", ); const details = query.data ?? null; const readError = identity.error ?? installation.error ?? query.error; const state: State = commandState ?? (cache.getSnapshot().signedOut || (readError instanceof PublisherReadError && readError.status === 401) ? "reconnect" : details ? "confirm" : readError ? "error" : "loading"); const error = commandError || (readError && state !== "reconnect" ? safeMessage( readError instanceof PublisherReadError ? readError.status : 0, readError instanceof PublisherReadError ? readError.code : null, ) : ""); const generation = useRef(0); const endpoint = `/api/installations/${installationId}/providers/openrouter`; const load = () => { setState(null); setError(""); if (!cache.getSnapshot().ownerSubject) void identity.refetch(); else { if (!installation.data || installation.error) void installation.refetch(); if (installation.data) void query.refetch(); } }; useEffect( () => () => { generation.current++; }, [installationId], ); async function enable() { if ( state === "provisioning" || !navigator.onLine || !cache.getSnapshot().ownerSubject ) return; const version = ++generation.current; setState("provisioning"); setError(""); try { const response = await fetch(endpoint, { method: "POST", credentials: "same-origin", headers: { "Content-Type": "application/x-www-form-urlencoded" }, body: "", signal: AbortSignal.timeout(60_000), }); const data = await responseJson(response); if (version !== generation.current || cache.getSnapshot().epoch !== epoch) return; if (response.status === 401) return setState("reconnect"); if (!response.ok) { setError(safeMessage(response.status, data.error)); return setState("error"); } if (typeof data.returnTo !== "string" || !details) throw new Error("Invalid setup response"); const destination = new URL(data.returnTo); const runtime = new URL(details.runtimeOrigin); const localDevelopment = window.location.hostname === "localhost" || window.location.hostname === "127.0.0.1"; if ( destination.origin !== runtime.origin || destination.username || destination.password || destination.pathname !== "/settings" || destination.search || destination.hash || (destination.protocol !== "https:" && !( destination.protocol === "http:" && localDevelopment && ["localhost", "127.0.0.1"].includes(destination.hostname) )) ) throw new Error("Unsafe setup destination"); setState("success"); window.location.assign(destination.href); } catch { if ( version === generation.current && cache.getSnapshot().epoch === epoch ) { setError( "OpenRouter may not have been enabled. Check your connection and retry setup safely.", ); setState("error"); } } } return (

Enable OpenRouter

Connect OpenRouter to this installation through Cloudflare AI Gateway.

{state === "loading" && (

Checking installation access…

)} {state === "provisioning" && (

Enabling OpenRouter… Do not close this page.

)} {state === "success" && (

OpenRouter enabled. Returning to model settings…

)} {error &&

{error}

} {state === "confirm" && details && ( <>

Confirm setup for installation {details.installationId.slice(0, 8)}{" "} in Cloudflare account {details.accountId}.

{readError && ( )} Cancel
)} {state === "error" && (
)} {state === "reconnect" && ( <>

Reconnect Cloudflare to confirm ownership and continue setup.

)}
); }