import { useMemo, useState, useSyncExternalStore } from "react"; import { Check, CircleDot, Eye, EyeOff, Link as LinkIcon, Plus, Save, Trash2, X, } from "@/ui/icon-registry"; import type { ApiConnectionSettings, ConnectionStatus } from "./types"; import { loadSavedControllers, normalizeControllerUrl, saveSavedControllers, type SavedController, } from "@/lib/api/controllers"; import { clearApiKey, getStoredBackendUrl, setApiKey, setStoredBackendUrl, } from "@/lib/api/connection"; import { scheduleDurableUiPreferencesSave } from "@/lib/desktop-ui-preferences"; import { DeployControllerPanel } from "./deploy-controller-panel"; import { AppVersionSection } from "./app-version-section"; import { StatusPill, Spinner, type UiTone } from "@/ui"; import { ApiUrlCensorToggle, useApiUrlCensored } from "@/ui/api-url-censor"; import { SettingsButton, SettingsGroup, SettingsInput, SettingsRow, SettingsValue, } from "./settings-ui"; type ControllerEntry = SavedController & { id: string }; /** * Rebuild the unified list: every controller stored in `local-studio.controllers` * is a first-class entry, the currently active controller (from * `localstudio_backend_url`) is just whichever row matches. If the active URL * isn't yet saved, we synthesize an entry for it so toggling away doesn't * lose it. */ function subscribeToStorage(callback: () => void): () => void { if (typeof window === "undefined") return () => undefined; window.addEventListener("storage", callback); return () => window.removeEventListener("storage", callback); } let cachedEntriesKey = ""; let cachedEntries: ControllerEntry[] = []; const serverEntries: ControllerEntry[] = []; function controllerEntriesKey(entries: ControllerEntry[]): string { return JSON.stringify( entries.map((entry) => [entry.id, entry.url, entry.name ?? "", entry.apiKey ?? ""]), ); } function readEntries(): ControllerEntry[] { const saved = loadSavedControllers(); const byUrl = new Map(); for (const entry of saved) { const url = normalizeControllerUrl(entry.url); if (!url) continue; byUrl.set(url, { ...entry, url }); } const next = [...byUrl.entries()].map(([url, value]) => ({ id: url, url, apiKey: value.apiKey, name: value.name, })); const key = controllerEntriesKey(next); if (key === cachedEntriesKey) return cachedEntries; cachedEntriesKey = key; cachedEntries = next; return cachedEntries; } export function ApiConnectionSection({ apiSettingsLoading, apiSettings, testing, saving, connectionStatus, statusMessage, onApiSettingsChange, onTestConnection, onSave, }: { apiSettingsLoading: boolean; apiSettings: ApiConnectionSettings; testing: boolean; saving: boolean; connectionStatus: ConnectionStatus; statusMessage: string; onApiSettingsChange: (nextSettings: ApiConnectionSettings) => void; onTestConnection: () => void; onSave: () => void; }) { const activeUrl = apiSettings.backendUrl; const entries = useSyncExternalStore(subscribeToStorage, readEntries, () => serverEntries); const setEntries = (next: ControllerEntry[]) => { saveSavedControllers(next); scheduleDurableUiPreferencesSave(); if (typeof window !== "undefined") window.dispatchEvent(new Event("storage")); }; const [draft, setDraft] = useState({ url: "" }); const [revealed, setRevealed] = useState>({}); const censorUrls = useApiUrlCensored(); const activeId = useMemo(() => normalizeControllerUrl(activeUrl), [activeUrl]); const persist = setEntries; const toggleReveal = (id: string) => setRevealed((current) => ({ ...current, [id]: !current[id] })); const activate = (entry: ControllerEntry) => { // Switching never deletes anything — every row stays in the list. // Clear the runtime key when the target has none, so the previous // controller's key isn't leaked to this controller's host. if (entry.apiKey) setApiKey(entry.apiKey); else clearApiKey(); setStoredBackendUrl(entry.url); onApiSettingsChange({ ...apiSettings, backendUrl: entry.url, apiKey: entry.apiKey ?? "", hasApiKey: Boolean(entry.apiKey), }); void fetch("/api/settings", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ backendUrl: entry.url, apiKey: entry.apiKey ?? "", }), }).finally(() => { if (typeof window !== "undefined") { window.dispatchEvent(new Event("storage")); } }); }; return (
} > {entries.length === 0 ? (
No controllers yet. Add one below.
) : ( entries.map((entry, index) => ( toggleReveal(entry.id)} onActivate={() => activate(entry)} onCommit={(next) => { const updated = entries.slice(); updated[index] = { ...next, id: entry.id }; persist(updated); const urlChanged = normalizeControllerUrl(next.url) !== entry.id; if (entry.id === activeId && urlChanged) { const url = normalizeControllerUrl(next.url); activate({ ...next, url, id: url }); } else if (entry.id === activeId && next.apiKey !== entry.apiKey) { activate({ ...next, id: entry.id }); } }} onRemove={() => { const remaining = entries.filter((row) => row.id !== entry.id); persist(remaining); if (entry.id === activeId && remaining[0]) activate(remaining[0]); }} /> )) )}
setDraft((current) => ({ ...current, name }))} className="w-36 shrink-0" /> setDraft((current) => ({ ...current, url }))} className="min-w-60 flex-1" censored={censorUrls} /> toggleReveal("__draft")} onChange={(apiKey) => setDraft((current) => ({ ...current, apiKey }))} className="w-40 shrink-0" /> { const url = normalizeControllerUrl(draft.url); if (!url) return; const exists = entries.find((entry) => entry.id === url); if (exists) return; persist([ ...entries, { id: url, url, apiKey: draft.apiKey?.trim() || undefined, name: draft.name?.trim() || undefined, }, ]); setDraft({ url: "" }); }} title="Add controller" > Add
{ const url = normalizeControllerUrl(controller.url); if (!url) return; const entry: ControllerEntry = { ...controller, url, id: url }; if (!entries.find((row) => row.id === url)) { persist([...entries, entry]); } activate(entry); }} /> {testing ? : } Test {saving ? : } Save active } /> ); } function ControllerListRow({ entry, index, active, revealed, censorUrls, onToggleReveal, onActivate, onCommit, onRemove, }: { entry: ControllerEntry; index: number; active: boolean; revealed: boolean; censorUrls: boolean; onToggleReveal: () => void; onActivate: () => void; onCommit: (entry: ControllerEntry) => void; onRemove: () => void; }) { const [draft, setDraft] = useState(entry); const commit = (next: ControllerEntry) => { if (next.name === entry.name && next.url === entry.url && next.apiKey === entry.apiKey) { return; } onCommit(next); }; return (
setDraft((current) => ({ ...current, name }))} onBlur={() => commit(draft)} className="w-32 shrink-0" /> setDraft((current) => ({ ...current, url }))} onBlur={() => commit(draft)} className="min-w-60 flex-1" censored={censorUrls} /> setDraft((current) => ({ ...current, apiKey }))} onBlur={() => commit(draft)} className="w-36 shrink-0" />
); } function ControllerTextInput({ value, placeholder, onChange, onBlur, className, censored = false, }: { value: string; placeholder: string; onChange: (value: string) => void; onBlur?: () => void; className: string; censored?: boolean; }) { return (
); } function ControllerSecretInput({ value, revealed, onToggleReveal, onChange, onBlur, className, }: { value: string; revealed: boolean; onToggleReveal: () => void; onChange: (value: string) => void; onBlur?: () => void; className: string; }) { return (
); } function ApiStatus({ status, message, loading, }: { status: ConnectionStatus; message: string; loading: boolean; }) { if (loading) { return loading; } const tone: UiTone = status === "connected" ? "good" : status === "error" ? "danger" : "default"; const label = message || (status === "unknown" ? "not tested" : status); return ( {status === "connected" ? : null} {status === "error" ? : null} {label} ); }