import { tr } from '../lib/i18n'; import { useEffect, useRef, useState } from 'react'; import { Btn, ErrorNotice, Dialog, Icon } from './ui'; import { CopyBtn } from './CopyBtn'; import { api } from '../lib/client'; import { setCloudflare, useStore } from '../lib/store'; import type { TunnelState } from '../lib/types'; export function CloudflareDialog({ open, onClose, onCreateKey }: { open: boolean; onClose: () => void; onCreateKey: () => void; }) { const serving = useStore(s => s.serving); const [mode, setMode] = useState<'quick' | 'domain'>('quick'), [step, setStep] = useState(0); const [hostname, setHostname] = useState(''), [token, setToken] = useState(''), [pending, setPending] = useState(false), [error, setError] = useState(''); const [detected, setDetected] = useState(null), [retry, setRetry] = useState(0); const heading = useRef(null); const tunnel = serving?.tunnel ?? detected; const active = !!tunnel && ['starting', 'connected', 'stopping'].includes(tunnel.status); const steps = mode === 'quick' ? ['Address', 'Connector', 'API key', 'Connect'] : ['Address', 'Connector', 'API key', 'Domain', 'Connect']; const last = steps.length - 1; const installed = !!tunnel?.installed, keyReady = !!serving?.access.apiKeySet, other = tunnel?.external ?? null; const canContinue = step === 1 ? installed : step === 2 ? true : step === 3 && mode === 'domain' ? !!hostname.trim() && !!token.trim() : true; async function inspect() { setPending(true); setError(''); try { setDetected(await api.get('/api/serving/tunnel')); } catch (e) { setError((e as Error).message); } finally { setPending(false); } } useEffect(() => { if (open) void inspect(); else { setToken(''); setError(''); } }, [open]); useEffect(() => { if (!open || step !== 1 || installed) return; let alive = true; setPending(true); setError(''); void setCloudflare({ action: 'prepare' }).then(() => { if (alive) { setPending(false); setStep(2); } }).catch(e => { if (alive) { setError((e as Error).message); setPending(false); } }); return () => { alive = false; }; }, [open, step, retry]); useEffect(() => { if (open && step > 0) heading.current?.focus({ preventScroll: true }); }, [step, open]); function dismiss() { setStep(0); onClose(); } function next() { setError(''); setStep(s => s === 0 && installed ? 2 : Math.min(last, s + 1)); } function back() { setError(''); if (!step) dismiss(); else setStep(s => s === 2 && installed ? 0 : s - 1); } async function connect() { setPending(true); setError(''); try { await setCloudflare({ action: 'start', mode, hostname, token }); setToken(''); } catch (e) { setError((e as Error).message); } finally { setPending(false); } } async function stop() { setPending(true); setError(''); try { await setCloudflare({ action: 'stop' }); setStep(0); } catch (e) { setError((e as Error).message); } finally { setPending(false); } } const titles = ['Choose your address', installed ? 'Connector ready' : 'Preparing your connector', 'Protect your connection', ...(mode === 'domain' ? ['Set up your domain'] : []), 'Ready to connect']; return {tr(active ? <>{tr("Done")} void stop()}>{tr(tunnel?.status === 'stopping' ? 'Stopping…' : 'Stop tunnel')} : <>{tr(step ? 'Back' : 'Cancel')}{tr(step === last ? void connect()}>{tr(pending ? 'Connecting…' : (error || tunnel?.error) ? 'Try again' : mode === 'quick' ? 'Create temporary URL' : 'Connect domain')} : {tr("Continue")})})} }>
{tr(!active ?
    {tr(steps.map((label, i) =>
  1. i || undefined}>
  2. ))}
: null)} {tr(active ?

{tr(tunnel?.status === 'connected' ? 'You’re connected' : tunnel?.status === 'stopping' ? 'Stopping the tunnel…' : 'Connecting to Cloudflare…')}

{tr(tunnel?.url ? <>

{tr("Use this address and your Strata API key in your other app.")}

{tunnel.url}

{tr(tunnel.mode === 'quick' ? 'Temporary address · turn off streaming in your client.' : `Your Cloudflare route must point to ${tunnel.originUrl}.`)}

:

{tr("This usually takes a few seconds. You can close this window while it connects.")}

)}
:

{tr(titles[step])}

{tr(step === 0 ? <>

{tr("Give your local API an HTTPS address that another app can reach.")}

{tr([{ value: 'quick' as const, title: 'Free temporary URL', detail: 'No account or domain needed. Good for a quick connection.', icon: 'bolt' as const }, { value: 'domain' as const, title: 'My own domain', detail: 'A stable address on a domain you manage with Cloudflare.', icon: 'link' as const }].map(choice => ))}
: null)} {tr(step === 1 ?

{tr(installed ? 'Your Cloudflare connector is installed and ready.' : error ? 'Automatic setup needs another try.' : 'Strata downloads and sets up the Cloudflare connector for you.')}

{tr(installed ? <>{tr(tunnel?.connector ?

{tr("Using {0}", [tunnel.connector.summary])}

: null)}{tr(other ?

{tr(other.others.length === 1 && !other.own.length ? "cloudflared is already running for another tunnel (PID {0})." : other.own.length ? "Strata’s tunnel for this address is already running (PID {0})." : "cloudflared is already running for other tunnels (PIDs {0}).", [(other.own.length ? other.own : other.others).join(", ")])}

: null)} : error ? setRetry(v => v + 1)}>{tr("Retry setup")} : {tr("Setting up\u2026")})}
: null)} {tr(step === 2 ? <>

{tr(keyReady ? "Only apps with your Strata API key can use this connection." : "Without an API key, anyone who finds the link can use your model.")}

{tr(keyReady ?
{tr("API key ready")}{tr("Use your existing key in the app you connect.")}
:

{tr("Create a key to protect your API. You\u2019ll return here when it\u2019s ready. You can also continue without one, but anyone who finds the link can then use your model.")}

{tr("Create an API key (recommended)")}
)} : null)} {tr(mode === 'domain' && step === 3 ? <>

{tr("Create a tunnel in your ")}{tr("Cloudflare dashboard \u2197")}{tr(". Copy the token from its connector setup.")}

{tr("Add a published application route for this hostname with this service URL:")}

{tunnel?.originUrl ?? 'Loading…'}

{tr("The token is used for this connection only and is not saved.")}

: null)} {tr(step === last ? <>

{tr(mode === 'quick' ? 'Cloudflare will create your address when you connect.' : 'Start the connector for the domain you configured.')}

{tr("Address")}
{tr(mode === 'quick' ? 'Free temporary URL' : hostname)}
{tr("Connector")}
{tr(tunnel?.connector?.version ? "Installed · cloudflared {0}" : "Installed", tunnel?.connector?.version ? [tunnel.connector.version] : undefined)}
{tr("Access")}
{tr(keyReady ? "API key required" : "No API key: anyone with the link can use it")}

{tr(mode === 'quick' ? 'The address changes each time. Turn off streaming in your client; replies arrive all at once.' : 'Use this hostname and your Strata API key in your client. Streaming is supported.')}

{tr("Only the inference API is shared. Your computer and Strata must stay on.")}

: null)}
)} {tr(error || tunnel?.error ? : null)}
; }