"use client"; import { useState, useEffect, useRef, useCallback } from "react"; import PropTypes from "prop-types"; import { Card, Button, Input, Modal, CardSkeleton, Toggle, ConfirmModal } from "@/shared/components"; import { useCopyToClipboard } from "@/shared/hooks/useCopyToClipboard"; import { getCurrentLocale, onLocaleChange } from "@/i18n/runtime"; import { WENYAN_LOCALES, TUNNEL_BENEFITS, TUNNEL_PING_INTERVAL_MS, TUNNEL_PING_MAX_MS, STATUS_POLL_FAST_MS, REACHABLE_MISS_THRESHOLD, CLIENT_PING_FAST_MS, CAVEMAN_LEVELS, } from "./endpointConstants"; import { clientPingUrl, clientPingAny } from "./endpointPing"; import EndpointRow from "./components/EndpointRow"; import StatusAlert from "./components/StatusAlert"; import Tooltip from "./components/Tooltip"; import SecurityWarning from "./components/SecurityWarning"; export default function APIPageClient({ machineId }) { const [keys, setKeys] = useState([]); const [loading, setLoading] = useState(true); const [showAddModal, setShowAddModal] = useState(false); const [newKeyName, setNewKeyName] = useState(""); const [createdKey, setCreatedKey] = useState(null); const [confirmState, setConfirmState] = useState(null); const [requireApiKey, setRequireApiKey] = useState(false); const [requireLogin, setRequireLogin] = useState(true); const [hasPassword, setHasPassword] = useState(true); const [tunnelDashboardAccess, setTunnelDashboardAccess] = useState(false); const [rtkEnabled, setRtkEnabledState] = useState(true); const [cavemanEnabled, setCavemanEnabled] = useState(false); const [cavemanLevel, setCavemanLevel] = useState("full"); const [locale, setLocale] = useState("en"); // Cloudflare Tunnel state const [tunnelChecking, setTunnelChecking] = useState(true); const [tunnelEnabled, setTunnelEnabled] = useState(false); const [tunnelReachable, setTunnelReachable] = useState(false); const [tunnelUrl, setTunnelUrl] = useState(""); const [tunnelPublicUrl, setTunnelPublicUrl] = useState(""); const [tunnelLoading, setTunnelLoading] = useState(false); const [tunnelProgress, setTunnelProgress] = useState(""); const [tunnelStatus, setTunnelStatus] = useState(null); const [showEnableTunnelModal, setShowEnableTunnelModal] = useState(false); const [showDisableTunnelModal, setShowDisableTunnelModal] = useState(false); // Tailscale state const [tsEnabled, setTsEnabled] = useState(false); const [tsReachable, setTsReachable] = useState(false); const [tsUrl, setTsUrl] = useState(""); const [tsLoading, setTsLoading] = useState(false); const [tsProgress, setTsProgress] = useState(""); const [tsStatus, setTsStatus] = useState(null); const [tsAuthUrl, setTsAuthUrl] = useState(""); const [tsAuthLabel, setTsAuthLabel] = useState(""); const [tsInstalled, setTsInstalled] = useState(null); // null=checking, true/false const [tsInstalling, setTsInstalling] = useState(false); const [tsInstallLog, setTsInstallLog] = useState([]); const [tsSudoPassword, setTsSudoPassword] = useState(""); const [tsConnecting, setTsConnecting] = useState(false); const [showTsModal, setShowTsModal] = useState(false); const [showDisableTsModal, setShowDisableTsModal] = useState(false); const tsLogRef = useRef(null); // Debounce reachable=false: server may briefly return false during background refresh. // Only flip UI to "reconnecting" after N consecutive misses to avoid spinner flicker. const tunnelMissRef = useRef(0); const tsMissRef = useRef(0); // Browser-side reachable cache (independent of backend DNS quirks) const tunnelClientReachableRef = useRef(false); const tsClientReachableRef = useRef(false); // Track whether reachable=true was ever observed in this session. // Distinguishes "Checking..." (initial cold cache) from "Reconnecting..." (lost connection). const tunnelEverReachableRef = useRef(false); const tsEverReachableRef = useRef(false); const [tunnelEverReachable, setTunnelEverReachable] = useState(false); const [tsEverReachable, setTsEverReachable] = useState(false); // API key visibility toggle state const [visibleKeys, setVisibleKeys] = useState(new Set()); // Client-side local/remote detection (UI hint only, not a security gate) const [isRemoteHost, setIsRemoteHost] = useState(false); useEffect(() => { if (typeof window !== "undefined") setIsRemoteHost(!["localhost", "127.0.0.1", "::1"].includes(window.location.hostname)); }, []); // Track app UI locale to gate wenyan caveman levels useEffect(() => { setLocale(getCurrentLocale()); return onLocaleChange(() => setLocale(getCurrentLocale())); }, []); const isWenyanLocale = WENYAN_LOCALES.includes(locale); const visibleCavemanLevels = isWenyanLocale ? CAVEMAN_LEVELS : CAVEMAN_LEVELS.filter((lvl) => !lvl.wenyan); // Reset wenyan level to "ultra" when leaving a Chinese locale useEffect(() => { const current = CAVEMAN_LEVELS.find((lvl) => lvl.id === cavemanLevel); if (current?.wenyan && !isWenyanLocale) { setCavemanLevel("ultra"); patchSetting({ cavemanLevel: "ultra" }); } }, [isWenyanLocale, cavemanLevel]); const { copied, copy } = useCopyToClipboard(); // Security gate: block remote exposure while dashboard uses default password or login is off. const isLoginUnsafe = !requireLogin || !hasPassword; const unsafeReason = !requireLogin ? "Enable \"Require login\" and set a custom password before activating the tunnel." : "Change the default dashboard password before activating the tunnel."; // Auto-scroll install log useEffect(() => { if (tsLogRef.current) tsLogRef.current.scrollTop = tsLogRef.current.scrollHeight; }, [tsInstallLog]); useEffect(() => { fetchData(); loadSettings(); }, []); // Status poll: only while degraded (not yet reachable). Stop once healthy to avoid spam. // Visibility re-check: refresh once when tab becomes visible. useEffect(() => { const anyEnabled = tunnelEnabled || tsEnabled; if (!anyEnabled) return; const tunnelHealthy = !tunnelEnabled || tunnelReachable; const tsHealthy = !tsEnabled || tsReachable; const allHealthy = tunnelHealthy && tsHealthy; const onVisible = () => { if (!document.hidden) syncTunnelStatus(); }; document.addEventListener("visibilitychange", onVisible); if (allHealthy) return () => document.removeEventListener("visibilitychange", onVisible); const timer = setInterval(() => { if (!document.hidden) syncTunnelStatus(); }, STATUS_POLL_FAST_MS); return () => { clearInterval(timer); document.removeEventListener("visibilitychange", onVisible); }; }, [tunnelEnabled, tsEnabled, tunnelReachable, tsReachable]); // Browser-side periodic ping: probes tunnel/tailscale URLs directly so UI stays // "reachable" even when backend DNS (1.1.1.1) hiccups on *.ts.net or *.trycloudflare.com. // Adaptive: slow when healthy, fast when degraded; pause when tab hidden. useEffect(() => { const probeBoth = async () => { if (document.hidden) return; if (tunnelEnabled && (tunnelUrl || tunnelPublicUrl)) { const ok = await clientPingAny(tunnelPublicUrl, tunnelUrl); tunnelClientReachableRef.current = ok; if (ok) { tunnelMissRef.current = 0; setTunnelReachable(true); if (!tunnelEverReachableRef.current) { tunnelEverReachableRef.current = true; setTunnelEverReachable(true); } } else { tunnelMissRef.current += 1; if (tunnelMissRef.current >= REACHABLE_MISS_THRESHOLD) setTunnelReachable(false); } } else { tunnelClientReachableRef.current = false; } if (tsEnabled && tsUrl) { const ok = await clientPingUrl(tsUrl); tsClientReachableRef.current = ok; if (ok) { tsMissRef.current = 0; setTsReachable(true); if (!tsEverReachableRef.current) { tsEverReachableRef.current = true; setTsEverReachable(true); } } else { tsMissRef.current += 1; if (tsMissRef.current >= REACHABLE_MISS_THRESHOLD) setTsReachable(false); } } else { tsClientReachableRef.current = false; } }; const anyEnabled = (tunnelEnabled && (tunnelUrl || tunnelPublicUrl)) || (tsEnabled && tsUrl); if (!anyEnabled) return; probeBoth(); const tunnelHealthy = !tunnelEnabled || tunnelReachable; const tsHealthy = !tsEnabled || tsReachable; if (tunnelHealthy && tsHealthy) return; const id = setInterval(probeBoth, CLIENT_PING_FAST_MS); return () => clearInterval(id); }, [tunnelEnabled, tunnelUrl, tunnelPublicUrl, tsEnabled, tsUrl, tunnelReachable, tsReachable]); // Client-side reachable only (server no longer probes; watchdog handles backend health). // Miss-debounce: only flip to false after N consecutive misses. const updateReachable = useCallback((_unused, clientRef, missRef, setter, everRef, everSetter) => { const reachable = clientRef.current; if (reachable) { missRef.current = 0; setter(true); if (!everRef.current) { everRef.current = true; everSetter(true); } } else { missRef.current += 1; if (missRef.current >= REACHABLE_MISS_THRESHOLD) setter(false); } }, []); // Trust user intent (settingsEnabled): UI stays "enabled" while watchdog restarts process const syncTunnelStatus = async () => { try { const statusRes = await fetch("/api/tunnel/status", { cache: "no-store" }); if (!statusRes.ok) return; const data = await statusRes.json(); const tEnabled = data.tunnel?.settingsEnabled ?? data.tunnel?.enabled ?? false; const tUrl = data.tunnel?.tunnelUrl || ""; setTunnelUrl(tUrl); setTunnelPublicUrl(data.tunnel?.publicUrl || ""); setTunnelEnabled(tEnabled); updateReachable(null, tunnelClientReachableRef, tunnelMissRef, setTunnelReachable, tunnelEverReachableRef, setTunnelEverReachable); const tsEn = data.tailscale?.settingsEnabled ?? data.tailscale?.enabled ?? false; const tsUrlVal = data.tailscale?.tunnelUrl || ""; setTsUrl(tsUrlVal); setTsEnabled(tsEn); updateReachable(null, tsClientReachableRef, tsMissRef, setTsReachable, tsEverReachableRef, setTsEverReachable); } catch { /* ignore poll errors */ } }; const loadSettings = async () => { setTunnelChecking(true); try { const [settingsRes, statusRes] = await Promise.all([ fetch("/api/settings"), fetch("/api/tunnel/status", { cache: "no-store" }) ]); if (settingsRes.ok) { const data = await settingsRes.json(); setRequireApiKey(data.requireApiKey || false); setRequireLogin(data.requireLogin !== false); setHasPassword(data.hasPassword || false); setTunnelDashboardAccess(data.tunnelDashboardAccess || false); setRtkEnabledState(data.rtkEnabled !== false); setCavemanEnabled(!!data.cavemanEnabled); setCavemanLevel(data.cavemanLevel || "full"); } if (statusRes.ok) { const data = await statusRes.json(); const tEnabled = data.tunnel?.settingsEnabled ?? data.tunnel?.enabled ?? false; const tUrl = data.tunnel?.tunnelUrl || ""; setTunnelUrl(tUrl); setTunnelPublicUrl(data.tunnel?.publicUrl || ""); setTunnelEnabled(tEnabled); updateReachable(null, tunnelClientReachableRef, tunnelMissRef, setTunnelReachable, tunnelEverReachableRef, setTunnelEverReachable); const tsEn = data.tailscale?.settingsEnabled ?? data.tailscale?.enabled ?? false; const tsUrlVal = data.tailscale?.tunnelUrl || ""; setTsUrl(tsUrlVal); setTsEnabled(tsEn); updateReachable(null, tsClientReachableRef, tsMissRef, setTsReachable, tsEverReachableRef, setTsEverReachable); } } catch (error) { console.log("Error loading settings:", error); } finally { setTunnelChecking(false); } }; const handleTunnelDashboardAccess = async (value) => { try { const res = await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ tunnelDashboardAccess: value }), }); if (res.ok) setTunnelDashboardAccess(value); } catch (error) { console.log("Error updating tunnelDashboardAccess:", error); } }; const handleRequireApiKey = async (value) => { try { const res = await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ requireApiKey: value }), }); if (res.ok) setRequireApiKey(value); } catch (error) { console.log("Error updating requireApiKey:", error); } }; const handleRtkEnabled = async (value) => { try { const res = await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ rtkEnabled: value }), }); if (res.ok) setRtkEnabledState(value); } catch (error) { console.log("Error updating rtkEnabled:", error); } }; const patchSetting = async (patch) => { try { await fetch("/api/settings", { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify(patch), }); } catch (error) { console.log("Error updating setting:", error); } }; const handleCavemanEnabled = (value) => { setCavemanEnabled(value); patchSetting({ cavemanEnabled: value }); }; const handleCavemanLevel = (level) => { setCavemanLevel(level); patchSetting({ cavemanLevel: level }); }; const fetchData = async () => { try { const keysRes = await fetch("/api/keys"); const keysData = await keysRes.json(); if (keysRes.ok) { setKeys(keysData.keys || []); } } catch (error) { console.log("Error fetching data:", error); } finally { setLoading(false); } }; // u2500u2500u2500 Cloudflare Tunnel handlers // Ping tunnel health until reachable. Race multiple URLs (shortlink + direct) — 1 OK is enough. const pingTunnelHealth = async (...urls) => { setTunnelLoading(true); setTunnelProgress("Waiting for tunnel ready..."); const targets = urls.filter(Boolean).map((u) => `${u}/api/health`); const start = Date.now(); while (Date.now() - start < TUNNEL_PING_MAX_MS) { await new Promise((r) => setTimeout(r, TUNNEL_PING_INTERVAL_MS)); const ok = await Promise.any(targets.map(async (h) => { const p = await fetch(h, { mode: "cors", cache: "no-store" }); if (p.ok) return true; throw new Error("not ready"); })).catch(() => false); if (ok) { setTunnelEnabled(true); setTunnelLoading(false); setTunnelProgress(""); return true; } // Every 5 pings (~10s), check if backend process still alive if ((Date.now() - start) % 10000 < TUNNEL_PING_INTERVAL_MS) { try { const statusRes = await fetch("/api/tunnel/status"); if (statusRes.ok) { const status = await statusRes.json(); if (!status.tunnel?.enabled) { setTunnelStatus({ type: "error", message: "Tunnel process stopped unexpectedly." }); setTunnelLoading(false); setTunnelProgress(""); return false; } } } catch { /* ignore */ } } } setTunnelStatus({ type: "error", message: "Tunnel created but not reachable. Please try again." }); setTunnelLoading(false); setTunnelProgress(""); return false; }; const handleEnableTunnel = async () => { setShowEnableTunnelModal(false); setTunnelLoading(true); setTunnelStatus(null); setTunnelProgress("Creating tunnel..."); // Poll download progress while enable request is pending let polling = true; const pollProgress = async () => { while (polling) { try { const r = await fetch("/api/tunnel/status"); if (r.ok) { const s = await r.json(); if (s.download?.downloading) { setTunnelProgress(`Downloading cloudflared... ${s.download.progress}%`); } else if (polling) { setTunnelProgress("Creating tunnel..."); } } } catch { /* ignore */ } await new Promise((r) => setTimeout(r, 1000)); } }; pollProgress(); try { const res = await fetch("/api/tunnel/enable", { method: "POST" }); polling = false; const data = await res.json(); if (!res.ok) { setTunnelStatus({ type: "error", message: data.error || "Failed to enable tunnel" }); return; } const url = data.tunnelUrl; if (!url) { setTunnelStatus({ type: "error", message: "No tunnel URL returned" }); return; } setTunnelUrl(url); setTunnelPublicUrl(data.publicUrl || ""); await pingTunnelHealth(data.publicUrl, url); } catch (error) { setTunnelStatus({ type: "error", message: error.message }); } finally { polling = false; setTunnelLoading(false); setTunnelProgress(""); } }; const handleDisableTunnel = async () => { setTunnelLoading(true); setTunnelStatus(null); try { const res = await fetch("/api/tunnel/disable", { method: "POST" }); const data = await res.json(); if (res.ok) { setTunnelEnabled(false); setTunnelUrl(""); setShowDisableTunnelModal(false); setTunnelStatus({ type: "success", message: "Tunnel disabled" }); } else { setTunnelStatus({ type: "error", message: data.error || "Failed to disable tunnel" }); } } catch (error) { setTunnelStatus({ type: "error", message: error.message }); } finally { setTunnelLoading(false); } }; // u2500u2500u2500 Tailscale handlers const checkTailscaleInstalled = async () => { setTsInstalled(null); try { const res = await fetch("/api/tunnel/tailscale-check"); if (res.ok) { const data = await res.json(); setTsInstalled(data.installed); return data; } } catch { /* ignore */ } setTsInstalled(false); return { installed: false }; }; const handleInstallTailscale = async () => { setTsInstalling(true); setTsStatus(null); setTsInstallLog([]); try { const res = await fetch("/api/tunnel/tailscale-install", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ sudoPassword: tsSudoPassword }), }); setTsSudoPassword(""); const reader = res.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const parts = buffer.split("\n\n"); buffer = parts.pop() || ""; for (const part of parts) { const lines = part.split("\n"); let event = "progress"; let data = null; for (const line of lines) { if (line.startsWith("event: ")) event = line.slice(7).trim(); if (line.startsWith("data: ")) { try { data = JSON.parse(line.slice(6)); } catch { /* skip */ } } } if (!data) continue; if (event === "progress") { setTsInstallLog((prev) => [...prev.slice(-50), data.message]); } else if (event === "done") { setTsInstalled(true); setTsInstalling(false); setShowTsModal(false); handleConnectTailscale(); return; } else if (event === "error") { setTsStatus({ type: "error", message: data.error || "Install failed" }); } } } } catch (e) { setTsStatus({ type: "error", message: e.message }); } finally { setTsInstalling(false); } }; // Ping Tailscale health until reachable const pingTsHealth = async (url) => { setTsProgress("Waiting for Tailscale ready..."); const healthUrl = `${url}/api/health`; const start = Date.now(); while (Date.now() - start < TUNNEL_PING_MAX_MS) { await new Promise((r) => setTimeout(r, TUNNEL_PING_INTERVAL_MS)); try { const ping = await fetch(healthUrl, { mode: "no-cors", cache: "no-store" }); if (ping.ok || ping.type === "opaque") return true; } catch { /* not ready yet */ } } return false; }; // Show inline login button instead of auto-opening popup (browsers block popups // opened after async work because the user gesture is lost). const requestUserAuth = (url, label) => { setTsAuthUrl(url); setTsAuthLabel(label); }; const clearUserAuth = () => { setTsAuthUrl(""); setTsAuthLabel(""); }; const handleConnectTailscale = async () => { setShowTsModal(false); setTsConnecting(true); setTsLoading(true); setTsStatus(null); setTsProgress("Connecting..."); clearUserAuth(); try { const res = await fetch("/api/tunnel/tailscale-enable", { method: "POST" }); const data = await res.json(); if (res.ok && data.success) { setTsUrl(data.tunnelUrl || ""); const reachable = await pingTsHealth(data.tunnelUrl); setTsEnabled(true); setTsStatus(reachable ? null : { type: "warning", message: "Connected but not reachable yet." }); return; } if (data.needsLogin && data.authUrl) { requestUserAuth(data.authUrl, "Open Login Page"); setTsProgress("Login required — click \"Open Login Page\" to continue"); for (let i = 0; i < 40; i++) { await new Promise((r) => setTimeout(r, 3000)); try { const r2 = await fetch("/api/tunnel/tailscale-check"); if (r2.ok) { const check = await r2.json(); if (check.loggedIn) { clearUserAuth(); setTsProgress("Starting funnel..."); const res2 = await fetch("/api/tunnel/tailscale-enable", { method: "POST" }); const data2 = await res2.json(); if (res2.ok && data2.success) { setTsUrl(data2.tunnelUrl || ""); const ok2 = await pingTsHealth(data2.tunnelUrl); setTsEnabled(true); setTsStatus(ok2 ? null : { type: "warning", message: "Connected but not reachable yet." }); } else if (data2.funnelNotEnabled && data2.enableUrl) { await pollFunnelEnable(data2.enableUrl); } else { setTsStatus({ type: "error", message: data2.error || "Failed to start funnel" }); } return; } } } catch { /* retry */ } } clearUserAuth(); setTsStatus({ type: "error", message: "Login timed out. Please try again." }); return; } if (data.funnelNotEnabled && data.enableUrl) { await pollFunnelEnable(data.enableUrl); return; } setTsStatus({ type: "error", message: data.error || "Failed to connect" }); } catch (error) { setTsStatus({ type: "error", message: error.message }); } finally { setTsLoading(false); setTsConnecting(false); setTsProgress(""); clearUserAuth(); } }; const pollFunnelEnable = async (enableUrl) => { requestUserAuth(enableUrl, "Open Funnel Settings"); setTsProgress("Click \"Open Funnel Settings\" to enable Funnel..."); for (let i = 0; i < 40; i++) { await new Promise((r) => setTimeout(r, 3000)); try { const res = await fetch("/api/tunnel/tailscale-enable", { method: "POST" }); const data = await res.json(); if (res.ok && data.success) { clearUserAuth(); setTsUrl(data.tunnelUrl || ""); const ok3 = await pingTsHealth(data.tunnelUrl); setTsEnabled(true); setTsStatus(ok3 ? null : { type: "warning", message: "Connected but not reachable yet." }); return; } if (data.funnelNotEnabled) continue; if (data.error) { clearUserAuth(); setTsStatus({ type: "error", message: data.error }); return; } } catch { /* retry */ } } clearUserAuth(); setTsStatus({ type: "error", message: "Timed out waiting for Funnel to be enabled." }); }; const handleDisableTailscale = async () => { setTsLoading(true); setTsStatus(null); try { const res = await fetch("/api/tunnel/tailscale-disable", { method: "POST" }); const data = await res.json(); if (res.ok) { setTsEnabled(false); setTsUrl(""); setShowDisableTsModal(false); setTsStatus({ type: "success", message: "Tailscale disabled" }); } else { setTsStatus({ type: "error", message: data.error || "Failed to disable Tailscale" }); } } catch (e) { setTsStatus({ type: "error", message: e.message }); } finally { setTsLoading(false); } }; const handleOpenTsModal = async () => { setTsStatus(null); setTsInstallLog([]); const data = await checkTailscaleInstalled(); if (data?.installed && data?.hasCachedPassword) { handleConnectTailscale(); } else { setShowTsModal(true); } }; const handleCreateKey = async () => { if (!newKeyName.trim()) return; try { const res = await fetch("/api/keys", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: newKeyName }), }); const data = await res.json(); if (res.ok) { setCreatedKey(data.key); await fetchData(); setNewKeyName(""); setShowAddModal(false); } } catch (error) { console.log("Error creating key:", error); } }; const handleDeleteKey = async (id) => { setConfirmState({ title: "Delete API Key", message: "Delete this API key?", onConfirm: async () => { setConfirmState(null); try { const res = await fetch(`/api/keys/${id}`, { method: "DELETE" }); if (res.ok) { setKeys(keys.filter((k) => k.id !== id)); setVisibleKeys(prev => { const next = new Set(prev); next.delete(id); return next; }); } } catch (error) { console.log("Error deleting key:", error); } } }); }; const handleToggleKey = async (id, isActive) => { try { const res = await fetch(`/api/keys/${id}`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ isActive }), }); if (res.ok) { setKeys(prev => prev.map(k => k.id === id ? { ...k, isActive } : k)); } } catch (error) { console.log("Error toggling key:", error); } }; const maskKey = (fullKey) => { if (!fullKey || fullKey.length <= 10) return fullKey || ""; return fullKey.slice(0, 6) + "•".repeat(fullKey.length - 10) + fullKey.slice(-4); }; const toggleKeyVisibility = (keyId) => { setVisibleKeys(prev => { const next = new Set(prev); if (next.has(keyId)) next.delete(keyId); else next.add(keyId); return next; }); }; const [baseUrl, setBaseUrl] = useState("/v1"); // Hydration fix: Only access window on client side useEffect(() => { if (typeof window !== "undefined") { setBaseUrl(`${window.location.origin}/v1`); } }, []); if (loading) { return (
Allow dashboard access via tunnel
Compress tool output{" "} (RTK)
git/grep/ls/tree/logs → 60-90% fewer input tokens
Compress LLM output{" "} (Caveman)
Terse-style system prompt → ~65% fewer output tokens (up to 87%)
{CAVEMAN_LEVELS.find((lvl) => lvl.id === cavemanLevel)?.desc}
Require API key
Requests without a valid key will be rejected
No API keys yet
Create your first API key to get started
{key.name}
{visibleKeys.has(key.id) ? key.key : maskKey(key.key)}
Created {new Date(key.createdAt).toLocaleDateString()}
{key.isActive === false && (Paused
)}Save this key now!
This is the only time you will see this key. Store it securely.
Cloudflare Tunnel
Expose your local 9Router to the internet. No port forwarding, no static IP needed. Share endpoint URL with your team or use it in Cursor, Cline, and other AI tools from anywhere.
{benefit.title}
{benefit.desc}
Requires outbound port 7844 (TCP/UDP). Connection may take 10-30s.
The Cloudflare tunnel will be disconnected. Remote access via tunnel URL will stop working.
progress_activity Checking...
)} {/* Not installed */} {tsInstalled === false && !tsInstalling && (Tailscale is not installed. Install it to enable Funnel.
Tailscale Funnel will be stopped. Remote access via Tailscale URL will stop working.