"use client"; import { AnimatePresence, motion } from "framer-motion"; import { Activity, ArrowUpRight, Bell, Camera, Cable, ChevronRight, CirclePlay, Copy, FileUp, HardDrive, Home, Languages, Loader2, Menu, MonitorPlay, Moon, Network, RefreshCw, Route, Server, Settings, ShieldCheck, Smartphone, Sparkles, Send, Sun, Trash2, Wifi, Power, X, } from "lucide-react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { LiveConsoleWorkspace } from "@/components/console/LiveConsoleWorkspace"; import { LiveAndroidWorkstation } from "@/components/live-product/LiveAndroidWorkstation"; import { LiveTiktokHdmiView } from "@/components/live-product/LiveTiktokHdmiView"; import type { PortalNavTarget } from "@/components/live-product/LivePipelineStrip"; import { DashboardOverview } from "@/components/live-product/DashboardOverview"; import { LiveYoutubeUnmannedView } from "@/components/live-product/LiveYoutubeUnmannedView"; import { classifyProcessMonitorActivity, processMonitorPollMs } from "@/lib/adaptivePoll"; import { fetchJsonResponse } from "@/lib/fetchJson"; import { extractNekoBrowserLinks, formatNekoPorts, type NekoBrowserLink } from "@/lib/nekoLinks"; import { normalizeBrowserReachableHttpUrl } from "@/lib/panelUrls"; type Lang = "zh" | "en"; type PortalTheme = "dark" | "light"; type ViewKey = | "dashboard" | "services" | "live_youtube" | "live_tiktok" | "android" | "studio" | "network" | "settings"; const VIEW_KEYS: ViewKey[] = [ "dashboard", "services", "live_youtube", "live_tiktok", "android", "studio", "network", "settings", ]; const SHOW_STUDIO_SERIAL_CONTROL = false; function isViewKey(value: string | null): value is ViewKey { return !!value && VIEW_KEYS.includes(value as ViewKey); } function initialViewKey(): ViewKey { if (typeof window === "undefined") return "dashboard"; const requested = new URLSearchParams(window.location.search).get("view"); if (isViewKey(requested)) return requested; if (window.location.pathname.replace(/\/$/, "") === "/youtube-events") return "live_youtube"; if (window.location.pathname.replace(/\/$/, "") === "/youtube-relay-log") return "live_youtube"; return "dashboard"; } const apiBase = () => (typeof process !== "undefined" && process.env.NEXT_PUBLIC_API_URL) || ""; function tr(lang: Lang, zh: string, en: string) { return lang === "zh" ? zh : en; } type HubDashboard = { snapshot?: { cpu_load?: { "1m"?: number; "5m"?: number; "15m"?: number }; memory?: { total?: number; available?: number; free?: number }; disk?: { total?: number; free?: number; used?: number }; netdata?: { available?: boolean; version?: string }; uptime_seconds?: number; }; hardware?: Record; stack?: { hostname?: string; mdns_host?: string; machine?: string; kernel?: string; python?: string; platform?: string; ips?: string[]; quick_links?: Record; neko_instances?: Array<{ id?: number; label?: string; port?: number; url?: string; alternate_urls?: Array<{ kind?: string; label?: string; host?: string; url?: string }>; quick_link_key?: string; }>; neko_login?: { user_login?: string; user_password?: string; admin_login?: string; admin_password?: string; note_zh?: string; }; }; services?: Array<{ service_id: string; label: string; category?: string; description: string; available: boolean; running: boolean; status: string; detail?: string; url?: string; }>; android?: { adb_available: boolean; devices: Array<{ serial: string; model?: string; state: string; transport?: string }>; }; live?: { backend_mode?: string; processes?: Array<{ pm2: string; label?: string; process_status?: string; script?: string; }>; }; network?: { interfaces?: Array<{ name?: string; rx_bytes?: number; tx_bytes?: number; rx_packets?: number; tx_packets?: number; rx_bps?: number; tx_bps?: number; sample_interval_seconds?: number; speed_mbps?: number | null; operstate?: string; }>; total_rx_bytes?: number; total_tx_bytes?: number; total_rx_bps?: number; total_tx_bps?: number; sample_interval_seconds?: number; }; live_events?: { pm2_tail?: string[]; process_digest?: Array<{ pm2?: string; label?: string; status?: string }>; }; hdmi?: { status?: string; can_stream_hdmi?: boolean; preferred_device?: string; video_devices?: string[]; usb_capture_matches?: string[]; issues?: string[]; suggested_ffmpeg_cmd?: string; }; probes?: { srs?: { port?: number; api_port?: number; api_ok?: boolean; tcp?: { ok?: boolean; reachable?: boolean; latency_ms?: number; error?: string }; tcp_api?: { ok?: boolean; reachable?: boolean; latency_ms?: number; error?: string }; http?: { ok?: boolean; http_code?: number; reachable?: boolean; latency_ms?: number; error?: string }; http_ui?: { ok?: boolean; http_code?: number; reachable?: boolean; latency_ms?: number; error?: string }; }; neko?: { port?: number; tcp?: { ok?: boolean; reachable?: boolean; latency_ms?: number; error?: string }; http?: { ok?: boolean; http_code?: number; reachable?: boolean; latency_ms?: number; error?: string }; instances?: Array<{ id?: number; port?: number; tcp?: { ok?: boolean; reachable?: boolean; latency_ms?: number; error?: string }; http?: { ok?: boolean; http_code?: number; reachable?: boolean; latency_ms?: number; error?: string }; }>; running_count?: number; required_count?: number; }; }; }; type WolDevice = { id?: string; name?: string; mac: string; ip?: string; reachable?: boolean; source?: string; last_seen?: number; }; type SerialPortInfo = { path: string; label?: string; name?: string; }; type StudioOpsPlaybook = { id?: string; title?: string; category?: string; priority?: string; description?: string; services?: string[]; dependencies?: Array<{ service_id?: string; label?: string; available?: boolean; running?: boolean; status?: string; detail?: string }>; required_count?: number; running_count?: number; available_count?: number; ready?: boolean; actions?: Array<{ service?: string; action?: string; label?: string }>; snapshot?: boolean; status?: string; }; type StudioOpsSummary = { doctor?: { score?: number; status?: string; critical?: number; warnings?: number; services_running?: number; services_available?: number; checks?: Array<{ id?: string; label?: string; ok?: boolean; severity?: string; detail?: string; recommendation?: string }>; recommendations?: string[]; }; inventory?: { counts?: { wol?: number; serial?: number; video?: number }; wol?: WolDevice[]; serial?: SerialPortInfo[]; video?: Array<{ path?: string; label?: string; name?: string }>; updated_at?: number; }; playbooks?: StudioOpsPlaybook[]; recipes?: Array<{ id?: string; title?: string; category?: string; priority?: string; status?: string; trigger?: string; actions?: string[] }>; apps?: Array<{ id?: string; title?: string; category?: string; priority?: string; installed?: boolean; status?: string; description?: string }>; backups?: { snapshots?: Array<{ id?: string; name?: string; size?: number; created_at?: number; included?: number; skipped?: number }> }; }; type DeploymentReport = { ready?: boolean; pass_count?: number; total_count?: number; required_total?: number; mdns_host?: string; primary_lan_ip?: string; port?: string; live_edge_enabled?: boolean; mdns_enabled?: boolean; checks?: Array<{ id: string; label: string; ok: boolean; kind?: string; detail?: string; url?: string; target?: string; http_code?: number; reachable?: boolean; }>; failing_checks?: Array<{ id: string; label: string; ok: boolean; detail?: string }>; hints?: string[]; urls?: Record; }; type WireGuardPeerSummary = { id?: number; public_key?: string; endpoint?: string; endpoint_host?: string; endpoint_port?: number | null; allowed_ips?: string[]; persistent_keepalive?: number | null; }; type WireGuardImportResult = { message?: string; wireguard?: { name?: string; path?: string; relative_path?: string; interface?: { addresses?: string[]; dns?: string[]; mtu?: number | null; listen_port?: string; private_key?: string; }; peers?: WireGuardPeerSummary[]; peer_count?: number; warnings?: string[]; redacted_config?: string; linux_apply_commands?: string[]; windows_route_template?: { endpoint_host?: string; powershell?: string; delete?: string; }; }; }; type WireGuardRuntimePeer = { endpoint?: string; endpoint_host?: string; endpoint_port?: number | null; allowed_ips?: string[]; latest_handshake?: number; latest_handshake_age_seconds?: number | null; transfer_rx_bytes?: number; transfer_tx_bytes?: number; persistent_keepalive?: string | number | null; routes_default?: boolean; status_source?: string; config_source?: string; }; type WireGuardRuntimeInterface = { name?: string; addresses?: string[]; listen_port?: string; fwmark?: string; peers?: WireGuardRuntimePeer[]; configured_peers?: WireGuardRuntimePeer[]; configured_from?: { name?: string; path?: string; source?: string; readable?: boolean }; configured_interface?: { addresses?: string[]; mtu?: number | null }; status_source?: string; details_available?: boolean; systemd?: { unit?: string; active?: string; enabled?: string }; }; type WireGuardSavedConfig = NonNullable & { size?: number }; type WireGuardRuntimeStatus = { active?: boolean; available?: boolean; quality?: { status?: string; score?: number; peer_count?: number; fresh_peer_count?: number; best_handshake_age_seconds?: number | null; transfer_rx_bytes?: number; transfer_tx_bytes?: number; routes_default?: boolean; details_available?: boolean; configured_peer_count?: number; reasons?: string[]; }; interfaces?: WireGuardRuntimeInterface[]; repo_configs?: WireGuardSavedConfig[]; system_configs?: Array<{ name?: string; path?: string; size?: number }>; endpoint_routes?: Array<{ host?: string; ok?: boolean; route?: string; dev?: string; via?: string; src?: string; warning?: string; uses_wireguard_interface?: boolean }>; shellcrash?: { running?: boolean; mixed_port?: string; unit?: { active?: string; enabled?: string }; redir_mode?: string; dns_mode?: string; }; neko_access?: { mode?: "lan" | "remote"; mode_label?: string; wireguard_active?: boolean; remote_ready?: boolean; nat1to1?: string; lan_host?: string; wireguard_host?: string; target_nat1to1?: string; needs_reconfigure?: boolean; remote_urls?: Array<{ id?: number; kind?: string; host?: string; port?: number; url?: string }>; }; neko_browser_proxy?: { enabled?: boolean; manual?: boolean; resolved_proxy?: string; shellcrash_port?: string; shellcrash_node?: string; attach_mode?: string; }; recommendations?: string[]; last_checked_at?: number; }; type SystemNetworkProbeTarget = { target?: string; label?: string; role?: string; ok?: boolean; status?: number; elapsed_ms?: number; error?: string; url?: string; proxy?: string; }; type SystemNetworkProbe = { ok?: boolean; mode?: "direct" | "shellcrash" | "failed" | string; direct_ready?: boolean; global_direct_ok?: boolean; douyin_direct_ok?: boolean; direct?: SystemNetworkProbeTarget[]; proxied?: SystemNetworkProbeTarget[]; summary?: string; shellcrash?: { running?: boolean; mixed_port?: string; unit_active?: string; }; shellcrash_policy?: { manual_only?: boolean; autostart_allowed?: boolean; autostart_on_direct_fail?: boolean; configured_autostart?: boolean; auto_start_on_web_panel?: boolean; attach_when_direct_ok?: boolean; attach_neko?: string; enable_neko_browser_proxy?: boolean; neko_browser_proxy_recommended?: boolean; attach_ffmpeg?: string; recommendation?: string; }; }; type ProcessEntry = { pm2: string; script: string; label: string }; type ProcessMonitorRow = ProcessEntry & { process_status?: string; business_status?: string; business_note?: string; is_pushing?: boolean; }; function formatBytes(value?: number) { if (value == null || !Number.isFinite(value)) return "—"; if (value === 0) return "0 B"; const u = ["B", "KB", "MB", "GB", "TB"]; let n = value; let i = 0; while (n >= 1024 && i < u.length - 1) { n /= 1024; i += 1; } return `${n.toFixed(n >= 10 || i === 0 ? 0 : 1)} ${u[i]}`; } function formatDurationSeconds(value?: number | null) { if (value == null || !Number.isFinite(value)) return "—"; const seconds = Math.max(0, Math.floor(value)); if (seconds < 60) return `${seconds}s`; const minutes = Math.floor(seconds / 60); if (minutes < 60) return `${minutes}m`; const hours = Math.floor(minutes / 60); if (hours < 48) return `${hours}h`; return `${Math.floor(hours / 24)}d`; } function statusPill(status: string) { if (status === "online" || status === "running") return "bg-emerald-500/15 text-emerald-300 ring-1 ring-emerald-500/30"; if (status === "configured") return "bg-sky-500/15 text-sky-200 ring-1 ring-sky-500/25"; if (status === "skipped") return "bg-slate-500/15 text-slate-300 ring-1 ring-slate-500/30"; if (status === "stopped" || status === "not_found") return "bg-zinc-500/15 text-zinc-400 ring-1 ring-zinc-500/25"; if (status === "error") return "bg-rose-500/15 text-rose-300 ring-1 ring-rose-500/35"; return "bg-violet-500/15 text-violet-200 ring-1 ring-violet-500/30"; } function wireGuardQualityLabel(status?: string, t?: (zh: string, en: string) => string) { const trText = t ?? ((zh: string, en: string) => en || zh); const normalized = (status || "").trim().toLowerCase(); if (normalized === "connected") return trText("高速可用", "Ready"); if (normalized === "configured") return trText("已配置", "Configured"); if (normalized === "detected") return trText("接口已起", "Detected"); if (normalized === "idle") return trText("等待握手", "Idle"); if (normalized === "stale") return trText("握手过期", "Stale"); if (normalized === "down") return trText("未连接", "Down"); return status || "—"; } function wireGuardEndpointHostFromValue(endpoint?: string) { const raw = (endpoint || "").trim(); if (!raw) return ""; if (raw.startsWith("[")) { const end = raw.indexOf("]"); return end > 0 ? raw.slice(1, end) : ""; } const idx = raw.lastIndexOf(":"); return idx > 0 ? raw.slice(0, idx) : raw; } export default function LiveControlApp() { const base = apiBase(); const [lang, setLang] = useState("zh"); const [portalTheme, setPortalTheme] = useState("dark"); const [view, setView] = useState("dashboard"); const [viewReady, setViewReady] = useState(false); const [mobileNav, setMobileNav] = useState(false); const [dash, setDash] = useState(null); const [dashErr, setDashErr] = useState(null); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(null); const [toast, setToast] = useState(null); const [lastSyncedAt, setLastSyncedAt] = useState(null); const [pageVisible, setPageVisible] = useState(true); const [entries, setEntries] = useState([]); const [processRows, setProcessRows] = useState([]); const [currentProc, setCurrentProc] = useState(""); const [urlConfig, setUrlConfig] = useState(""); const [apkPath, setApkPath] = useState("/sdcard/app.apk"); const [androidSerial, setAndroidSerial] = useState(""); const [hubCfgSnapshot, setHubCfgSnapshot] = useState | null>(null); const [deployCheck, setDeployCheck] = useState(null); const [autoRefreshEnabled, setAutoRefreshEnabled] = useState(true); const [showStreamProbes, setShowStreamProbes] = useState(true); const [wgConfigName, setWgConfigName] = useState("tencent-relay-wg0"); const [wgConfigText, setWgConfigText] = useState(""); const [wgImportResult, setWgImportResult] = useState(null); const [wgStatus, setWgStatus] = useState(null); const [systemNetworkProbe, setSystemNetworkProbe] = useState(null); const [systemNetworkProbeLoading, setSystemNetworkProbeLoading] = useState(false); const [wgEditing, setWgEditing] = useState(true); const [wgRouteMode, setWgRouteMode] = useState<"overlay" | "preserve">("overlay"); const [wgRouteGateway, setWgRouteGateway] = useState(""); const [wgRouteIfIndex, setWgRouteIfIndex] = useState(""); const [wolMac, setWolMac] = useState(""); const [wolBroadcast, setWolBroadcast] = useState("255.255.255.255"); const [wolPort, setWolPort] = useState("9"); const [wolDevices, setWolDevices] = useState([]); const [wolSelectedMac, setWolSelectedMac] = useState(""); const [wolDeviceName, setWolDeviceName] = useState(""); const [wolDeviceIp, setWolDeviceIp] = useState(""); const [serialPorts, setSerialPorts] = useState([]); const [serialPort, setSerialPort] = useState(""); const [serialBaudrate, setSerialBaudrate] = useState("115200"); const [serialCommand, setSerialCommand] = useState("AT"); const [serialResponse, setSerialResponse] = useState(""); const [studioOps, setStudioOps] = useState(null); const dashboardInFlightRef = useRef | null>(null); const stackSummaryInFlightRef = useRef | null>(null); const processMonitorInFlightRef = useRef | null>(null); const currentProcRef = useRef(currentProc); const urlConfigRequestSeqRef = useRef(0); const toastTimerRef = useRef(null); const t = useCallback((zh: string, en: string) => tr(lang, zh, en), [lang]); const notify = useCallback((msg: string) => { setToast(msg); if (toastTimerRef.current != null) { window.clearTimeout(toastTimerRef.current); } toastTimerRef.current = window.setTimeout(() => { setToast(null); toastTimerRef.current = null; }, 2800); }, []); const fetchJson = useCallback( async (path: string, init?: RequestInit): Promise => { return fetchJsonResponse(`${base}${path}`, init); }, [base], ); const refreshStackSummary = useCallback(async () => { if (stackSummaryInFlightRef.current) return stackSummaryInFlightRef.current; const task = (async () => { try { const stack = await fetchJson>("/stack/summary"); setDash((prev) => ({ ...(prev ?? {}), stack })); setDashErr(null); setLastSyncedAt(Date.now()); } catch (e) { setDashErr((e as Error).message); } finally { stackSummaryInFlightRef.current = null; } })(); stackSummaryInFlightRef.current = task; return task; }, [fetchJson]); const refreshDashboard = useCallback(async () => { if (dashboardInFlightRef.current) return dashboardInFlightRef.current; const task = (async () => { try { const [dashResult, deployResult] = await Promise.allSettled([ fetchJson("/hub/dashboard"), fetchJson("/deploy/check"), ] as const); if (dashResult.status !== "fulfilled") { throw dashResult.reason; } const d = dashResult.value; setDash(d); setDashErr(null); setLastSyncedAt(Date.now()); if (deployResult.status === "fulfilled") { setDeployCheck(deployResult.value); } else { setDeployCheck(null); } const devs = d.android?.devices || []; if (devs.length && !androidSerial) { const ready = devs.find((x) => (x.state || "").toLowerCase() === "device"); setAndroidSerial((ready ?? devs[0]).serial); } } catch (e) { setDashErr((e as Error).message); setDeployCheck(null); } finally { setLoading(false); dashboardInFlightRef.current = null; } })(); dashboardInFlightRef.current = task; return task; }, [androidSerial, fetchJson]); const processMonitorPath = useMemo(() => { const params = new URLSearchParams({ light: "1" }); if (view === "live_youtube") params.set("family", "youtube"); else if (view === "live_tiktok") params.set("family", "tiktok"); return `/process_monitor?${params.toString()}`; }, [view]); const processMonitorActivity = useMemo( () => classifyProcessMonitorActivity(processRows), [processRows], ); const processMonitorPollIntervalMs = useMemo( () => processMonitorPollMs({ view, activity: processMonitorActivity, pageVisible, }), [view, processMonitorActivity, pageVisible], ); const refreshProcessMonitor = useCallback(async () => { if (processMonitorInFlightRef.current) return processMonitorInFlightRef.current; const task = (async () => { try { const data = await fetchJson<{ entries?: ProcessMonitorRow[] }>(processMonitorPath); const list = data.entries || []; setProcessRows(list); setEntries(list.map((row) => ({ pm2: row.pm2, script: row.script, label: row.label }))); setLastSyncedAt(Date.now()); setCurrentProc((prev) => { if (!list.length) return prev; if (prev && list.some((row) => row.pm2 === prev)) return prev; return list[0].pm2; }); } catch { /* ignore */ } finally { processMonitorInFlightRef.current = null; } })(); processMonitorInFlightRef.current = task; return task; }, [fetchJson, processMonitorPath]); useEffect(() => { setView(initialViewKey()); setViewReady(true); const s = window.localStorage.getItem("live-hub-lang"); if (s === "zh" || s === "en") setLang(s); const th = window.localStorage.getItem("live-hub-theme"); if (th === "light" || th === "dark") setPortalTheme(th); }, []); useEffect(() => { if (!viewReady) return; const url = new URL(window.location.href); if (view === "dashboard") { url.searchParams.delete("view"); } else { url.searchParams.set("view", view); } window.history.replaceState(null, "", url.toString()); }, [view, viewReady]); useEffect(() => { window.localStorage.setItem("live-hub-lang", lang); }, [lang]); useEffect(() => { document.documentElement.setAttribute("data-theme", portalTheme); try { window.localStorage.setItem("live-hub-theme", portalTheme); } catch { /* ignore */ } }, [portalTheme]); useEffect(() => { const onVis = () => setPageVisible(document.visibilityState === "visible"); onVis(); document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, []); useEffect(() => { if (!mobileNav) return; const onKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") setMobileNav(false); }; window.addEventListener("keydown", onKeyDown); const prev = document.body.style.overflow; document.body.style.overflow = "hidden"; return () => { window.removeEventListener("keydown", onKeyDown); document.body.style.overflow = prev; }; }, [mobileNav]); useEffect( () => () => { if (toastTimerRef.current != null) { window.clearTimeout(toastTimerRef.current); } }, [], ); useEffect(() => { try { if (localStorage.getItem("livehub.autorefresh") === "0") setAutoRefreshEnabled(false); if (localStorage.getItem("livehub.showStreamProbes") === "0") setShowStreamProbes(false); } catch { /* ignore */ } }, []); useEffect(() => { if (!viewReady) return; if (view === "live_youtube" || view === "live_tiktok") { setLoading(false); void refreshStackSummary(); return; } void refreshDashboard(); }, [refreshDashboard, refreshStackSummary, view, viewReady]); useEffect(() => { if (!viewReady) return; void refreshProcessMonitor(); }, [refreshProcessMonitor, viewReady]); useEffect(() => { if (!viewReady || !autoRefreshEnabled || !pageVisible || view === "live_youtube" || view === "live_tiktok") return; const id = window.setInterval(() => { void refreshDashboard(); }, 10000); return () => clearInterval(id); }, [autoRefreshEnabled, pageVisible, refreshDashboard, view, viewReady]); useEffect(() => { if (!viewReady || !autoRefreshEnabled) return; const id = window.setInterval(() => { void refreshProcessMonitor(); }, processMonitorPollIntervalMs); return () => clearInterval(id); }, [autoRefreshEnabled, processMonitorPollIntervalMs, refreshProcessMonitor, viewReady]); useEffect(() => { const onVis = () => { if (document.visibilityState === "visible") void refreshProcessMonitor(); }; document.addEventListener("visibilitychange", onVis); return () => document.removeEventListener("visibilitychange", onVis); }, [refreshProcessMonitor]); useEffect(() => { currentProcRef.current = currentProc; }, [currentProc]); useEffect(() => { if (view !== "settings") return; void (async () => { try { const cfg = await fetchJson>("/hub/config"); setHubCfgSnapshot(cfg); } catch { setHubCfgSnapshot(null); } })(); }, [fetchJson, view]); const ql = useMemo(() => { const raw = dash?.stack?.quick_links || {}; const o: Record = {}; for (const [k, v] of Object.entries(raw)) { if (/^https?:\/\//i.test(v)) o[k] = normalizeBrowserReachableHttpUrl(v); else o[k] = v; } return o; }, [dash?.stack?.quick_links]); const serviceById = useMemo(() => { const map = new Map[number]>(); for (const service of dash?.services || []) { map.set(service.service_id, service); } return map; }, [dash?.services]); const studioServices = useMemo( () => ["homeassistant", "frigate", "ntfy", "wol"].map((id) => serviceById.get(id)).filter(Boolean) as NonNullable, [serviceById], ); const studioPlaybooks = studioOps?.playbooks || []; const wolService = serviceById.get("wol"); const nekoLinks = useMemo(() => extractNekoBrowserLinks(ql), [ql]); const nekoPortsLabel = useMemo(() => formatNekoPorts(nekoLinks), [nekoLinks]); const wgRuntimePeers = useMemo(() => (wgStatus?.interfaces || []).flatMap((iface) => iface.peers || []), [wgStatus?.interfaces]); const wgConfiguredPeers = useMemo( () => (wgStatus?.interfaces || []).flatMap((iface) => iface.configured_peers || []), [wgStatus?.interfaces], ); const wgRepoPeers = useMemo( () => ((wgStatus?.repo_configs || []).flatMap((cfg) => cfg.peers || []) as WireGuardRuntimePeer[]).map((peer) => ({ ...peer, status_source: "config", config_source: "repo" })), [wgStatus?.repo_configs], ); const wgDisplayPeer = wgRuntimePeers[0] || wgConfiguredPeers[0] || wgRepoPeers[0] || null; const wgStatusEndpointHost = useMemo(() => { const candidates = [...wgRuntimePeers, ...wgConfiguredPeers, ...wgRepoPeers]; for (const peer of candidates) { const host = peer.endpoint_host || wireGuardEndpointHostFromValue(peer.endpoint); if (host) return host; } return ""; }, [wgConfiguredPeers, wgRepoPeers, wgRuntimePeers]); const wgEndpointHost = wgImportResult?.windows_route_template?.endpoint_host || wgImportResult?.peers?.find((peer) => peer.endpoint_host)?.endpoint_host || wgStatusEndpointHost || ""; const wgRouteCommand = useMemo(() => { if (!wgEndpointHost) return ""; const gateway = wgRouteGateway.trim() || ""; const ifIndex = wgRouteIfIndex.trim() || ""; return `route -p add ${wgEndpointHost} mask 255.255.255.255 ${gateway} metric 1 if ${ifIndex}`; }, [wgEndpointHost, wgRouteGateway, wgRouteIfIndex]); const refreshWireGuardStatus = useCallback(async () => { try { const data = await fetchJson<{ wireguard?: WireGuardRuntimeStatus }>("/hub/network/wireguard/status"); setWgStatus(data.wireguard ?? null); } catch { setWgStatus(null); } }, [fetchJson]); const refreshSystemNetworkProbe = useCallback(async () => { setSystemNetworkProbeLoading(true); try { const data = await fetchJson("/hub/network/system_probe"); setSystemNetworkProbe(data ?? null); } catch { setSystemNetworkProbe(null); } finally { setSystemNetworkProbeLoading(false); } }, [fetchJson]); useEffect(() => { if (view !== "network") return; void refreshWireGuardStatus(); void refreshSystemNetworkProbe(); }, [refreshSystemNetworkProbe, refreshWireGuardStatus, view]); const saveWireGuardConfig = async (apply = false) => { const content = wgConfigText.trim(); if (!content) { notify(t("请先选择或粘贴 WireGuard 配置", "Pick or paste a WireGuard config first")); return; } setBusy(apply ? "wg:apply" : "wg:save"); try { const data = await fetchJson("/hub/network/wireguard/save", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: wgConfigName, content, route_mode: wgRouteMode, apply }), }); setWgImportResult(data.wireguard ?? null); await refreshWireGuardStatus(); notify(apply ? t("WireGuard 配置已保存并应用", "WireGuard config saved and applied") : t("WireGuard 配置已保存", "WireGuard config saved")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const setWireGuardNekoAccessMode = async (mode: "lan" | "remote") => { setBusy(`wg:neko:${mode}`); try { await fetchJson<{ neko_access?: WireGuardRuntimeStatus["neko_access"] }>("/hub/network/wireguard/neko_access", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mode, restart: true }), }); await refreshWireGuardStatus(); await refreshDashboard(); notify(mode === "remote" ? "Neko switched to WireGuard remote access" : "Neko switched back to LAN"); } catch (e) { notify((e as Error).message); await refreshWireGuardStatus(); } finally { setBusy(null); } }; const setNekoBrowserProxy = async (enabled: boolean) => { setBusy(`neko:proxy:${enabled ? "on" : "off"}`); try { const data = await fetchJson<{ neko_browser_proxy?: WireGuardRuntimeStatus["neko_browser_proxy"] }>("/hub/network/neko_browser_proxy", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled, restart: true }), }); if (data.neko_browser_proxy) { setWgStatus((prev) => (prev ? { ...prev, neko_browser_proxy: data.neko_browser_proxy } : prev)); } await refreshWireGuardStatus(); await refreshSystemNetworkProbe(); await refreshDashboard(); notify( enabled ? t("已开启 Neko proxycheap 代理(7894)", "Neko proxycheap proxy enabled (7894)") : t("已关闭 proxycheap,直连失败时将走 ShellCrash 7890", "Proxycheap off; ShellCrash 7890 when direct blocked"), ); } catch (e) { notify((e as Error).message); await refreshWireGuardStatus(); } finally { setBusy(null); } }; const importWireGuardConfig = async () => { await saveWireGuardConfig(false); }; const loadSavedWireGuardConfig = async (name?: string) => { const target = (name || "").trim(); if (!target) return; setBusy(`wg:load:${target}`); try { const data = await fetchJson<{ name?: string; content?: string; wireguard?: WireGuardImportResult["wireguard"] }>( `/hub/network/wireguard/config/${encodeURIComponent(target)}`, ); setWgConfigName(data.name || target); setWgConfigText(data.content || ""); setWgImportResult(data.wireguard ?? null); setWgEditing(true); notify(t("已载入 WireGuard 配置", "WireGuard config loaded")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const readWireGuardFile = async (file?: File | null) => { if (!file) return; try { const text = await file.text(); setWgConfigText(text); if (!wgConfigName.trim()) { setWgConfigName(file.name.replace(/\.conf$/i, "")); } } catch (e) { notify((e as Error).message); } }; const runService = async ( service: string, action: "install" | "start" | "stop" | "restart" | "uninstall" | "upgrade", ) => { setBusy(`svc:${service}`); try { const data = await fetchJson<{ message?: string; status?: string; detail?: string }>("/service_action", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ service, action }), }); if (data.status === "error") { notify(data.detail || data.message || t("操作失败", "Action failed")); } else { notify(data.message || "OK"); } await refreshDashboard(); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const sendWolWake = async () => { const mac = wolMac.trim(); const broadcast = wolBroadcast.trim() || "255.255.255.255"; const port = Number(wolPort.trim() || "9"); if (!mac) { notify(t("请输入 MAC 地址", "Enter a MAC address")); return; } if (!Number.isInteger(port) || port < 1 || port > 65535) { notify(t("端口必须在 1-65535 之间", "Port must be 1-65535")); return; } setBusy("wol:wake"); try { const data = await fetchJson<{ message?: string }>("/studio/wol/wake", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mac, broadcast, port }), }); notify(data.message || t("唤醒包已发送", "Wake packet sent")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const refreshWolDevices = useCallback( async (probe = false) => { try { const data = await fetchJson<{ devices?: WolDevice[] }>( probe ? "/studio/wol/devices/probe" : "/studio/wol/devices", probe ? { method: "POST" } : undefined, ); setWolDevices(data.devices || []); } catch (e) { if (probe) notify((e as Error).message); } }, [fetchJson, notify], ); const saveWolDevice = async () => { const mac = wolMac.trim(); if (!mac) { notify(t("请输入 MAC 地址", "Enter a MAC address")); return; } setBusy("wol:save"); try { const data = await fetchJson<{ devices?: WolDevice[]; device?: WolDevice; message?: string }>("/studio/wol/devices", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: wolDeviceName, mac, ip: wolDeviceIp }), }); setWolDevices(data.devices || []); setWolSelectedMac(data.device?.mac || mac); notify(data.message || t("设备已保存", "Device saved")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const deleteWolDevice = async () => { const mac = (wolSelectedMac || wolMac).trim(); if (!mac) return; setBusy("wol:delete"); try { const data = await fetchJson<{ devices?: WolDevice[] }>("/studio/wol/devices/delete", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ mac }), }); setWolDevices(data.devices || []); setWolSelectedMac(""); setWolMac(""); setWolDeviceName(""); setWolDeviceIp(""); notify(t("设备已删除", "Device removed")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const refreshSerialPorts = useCallback(async () => { try { const data = await fetchJson<{ ports?: SerialPortInfo[] }>("/studio/serial/ports"); const ports = data.ports || []; setSerialPorts(ports); setSerialPort((prev) => (prev && ports.some((item) => item.path === prev) ? prev : ports[0]?.path || prev)); } catch { setSerialPorts([]); } }, [fetchJson]); const sendSerialAtCommand = async () => { if (!serialPort) { notify(t("请选择串口", "Select a serial port")); return; } const baudrate = Number(serialBaudrate.trim() || "115200"); if (!Number.isInteger(baudrate) || baudrate < 1200) { notify(t("波特率无效", "Invalid baudrate")); return; } setBusy("serial:send"); try { const data = await fetchJson<{ response?: string }>("/studio/serial/command", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ port: serialPort, baudrate, command: serialCommand, append_crlf: true, timeout: 2 }), }); setSerialResponse(data.response || ""); notify(t("指令已发送", "Command sent")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const refreshStudioOps = useCallback( async (refresh = false) => { try { const data = await fetchJson(`/studio/ops/summary${refresh ? "?refresh=1" : ""}`); setStudioOps(data); } catch (e) { if (refresh) notify((e as Error).message); } }, [fetchJson, notify], ); const createStudioSnapshot = async () => { setBusy("studio:snapshot"); try { const data = await fetchJson<{ message?: string }>("/studio/ops/snapshot", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ reason: "studio" }), }); await refreshStudioOps(false); notify(data.message || t("系统快照已创建", "System snapshot created")); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const runStudioPlaybook = async (playbookId?: string) => { const id = (playbookId || "").trim(); if (!id) return; setBusy(`studio:playbook:${id}`); try { const data = await fetchJson<{ message?: string; failed?: number; summary?: StudioOpsSummary; actions?: Array<{ service_id?: string; action?: string; status?: string; message?: string }>; }>("/studio/ops/playbook", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ playbook_id: id }), }); if (data.summary) setStudioOps(data.summary); else await refreshStudioOps(false); await refreshDashboard(); const failed = data.failed ?? (data.actions || []).filter((item) => item.status === "error").length; notify(data.message || (failed ? t("场景执行完成,但存在失败步骤", "Playbook completed with failed steps") : t("场景执行完成", "Playbook completed"))); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; useEffect(() => { if (view !== "studio") return; void refreshWolDevices(true); if (SHOW_STUDIO_SERIAL_CONTROL) void refreshSerialPorts(); void refreshStudioOps(true); const id = window.setInterval(() => { void refreshWolDevices(true); if (SHOW_STUDIO_SERIAL_CONTROL) void refreshSerialPorts(); void refreshStudioOps(false); }, 30000); return () => window.clearInterval(id); }, [refreshSerialPorts, refreshStudioOps, refreshWolDevices, view]); const runProcess = async (action: "start" | "stop" | "restart", processOverride?: string) => { const proc = (processOverride ?? currentProc).trim(); if (!proc) return; setBusy(`proc:${action}:${proc}`); try { const path = `/${action}`; const data = await fetchJson<{ output?: string; message?: string }>(path, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ process: proc }), }); notify(String(data.output || data.message || "OK")); await refreshProcessMonitor(); if (view === "live_youtube" || view === "live_tiktok") { void refreshDashboard(); } else { await refreshDashboard(); } } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const saveUrlConfig = async (overrideContent?: string, processOverride?: string) => { const proc = (processOverride ?? currentProc).trim(); if (!proc) { notify(t("请选择要保存地址的进程", "Pick a process before saving URLs")); throw new Error(t("请选择要保存地址的进程", "Pick a process before saving URLs")); } const content = overrideContent ?? urlConfig; const requestId = ++urlConfigRequestSeqRef.current; setBusy("save:url"); try { const params = new URLSearchParams({ process: proc }); const data = await fetchJson<{ message?: string; path?: string }>(`/save_url_config?${params}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content }), }); if (requestId === urlConfigRequestSeqRef.current && proc === currentProcRef.current.trim()) { setUrlConfig(content); } notify(data.path ? t(`URL 配置已保存: ${data.path}`, `URL config saved: ${data.path}`) : t("URL 配置已保存", "URL config saved")); } catch (e) { notify((e as Error).message); throw e; } finally { setBusy(null); } }; const androidAction = async (action: string, payload: Record = {}) => { if (!androidSerial) { notify(t("请选择设备", "Pick a device")); return; } setBusy(`adb:${action}`); try { const data = await fetchJson<{ message?: string }>("/android/action", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ action, serial: androidSerial, payload }), }); notify(data.message || "OK"); } catch (e) { notify((e as Error).message); } finally { setBusy(null); } }; const navItems: { id: ViewKey; icon: typeof Activity; labelZh: string; labelEn: string }[] = [ { id: "dashboard", icon: Activity, labelZh: "总览", labelEn: "Dashboard" }, { id: "services", icon: Server, labelZh: "服务", labelEn: "Services" }, { id: "live_youtube", icon: CirclePlay, labelZh: "YouTube 无人直播", labelEn: "YouTube unmanned" }, { id: "live_tiktok", icon: MonitorPlay, labelZh: "TikTok 无人直播", labelEn: "TikTok unmanned" }, { id: "android", icon: Smartphone, labelZh: "安卓", labelEn: "Android" }, { id: "studio", icon: Home, labelZh: "工作室", labelEn: "Studio" }, { id: "network", icon: Network, labelZh: "网络", labelEn: "Network" }, { id: "settings", icon: Settings, labelZh: "设置", labelEn: "Settings" }, ]; const copyText = (text: string) => { const write = async () => { if (navigator.clipboard?.writeText) { await navigator.clipboard.writeText(text); return; } const ta = document.createElement("textarea"); ta.value = text; ta.readOnly = true; ta.style.position = "fixed"; ta.style.opacity = "0"; document.body.appendChild(ta); ta.select(); document.execCommand("copy"); ta.remove(); }; void write().then( () => notify(t("已复制", "Copied")), () => notify(t("复制失败", "Copy failed")), ); }; const lastSyncLabel = lastSyncedAt ? new Date(lastSyncedAt).toLocaleTimeString(lang === "zh" ? "zh-CN" : "en-US", { hour12: false }) : t("未同步", "Not synced"); const refreshStateLabel = pageVisible ? t("前台自动刷新", "Auto refresh") : t("后台已暂停刷新", "Refresh paused in background"); return (
{toast ? ( {toast} ) : null}
{/* Desktop sidebar */} {/* Main */}

{t( navItems.find((n) => n.id === view)?.labelZh || "", navItems.find((n) => n.id === view)?.labelEn || "", )}

{dash?.stack?.mdns_host || "live.local"} ·{" "} {portalTheme === "dark" ? t("夜间", "Dark mode") : t("日间", "Light mode")} · {refreshStateLabel} ·{" "} {t("最后同步", "Last sync")} {lastSyncLabel}

{view === "dashboard" ? ( ) : null} {view === "services" ? (
{(dash?.services || []).map((s, i) => (

{s.label}

{s.description}

{s.running ? t("运行中", "Running") : s.status}
{s.detail ? (

{s.detail}

) : null} {s.service_id === "shellcrash" && s.available && !s.running ? (

{t( "stopped 为常态:仅当需要透明代理 / 规则分流时再手动点 Start,不建议设置自启。", "Stopped is normal; click Start manually only when the proxy is needed. Autostart stays off.", )}

) : null}
{s.url ? ( {t("打开面板", "Open panel")} ) : null}
))} {!dash?.services?.length ? (

{t("暂无服务数据", "No services")}

) : null}
) : null} {view === "live_youtube" ? ( void runProcess(a, pm)} onSaveUrlConfig={(c, pm) => saveUrlConfig(c, pm)} fetchJson={fetchJson} liveProcesses={processRows.length ? processRows : (dash?.live?.processes ?? [])} notify={notify} quickLinks={ql} onRefresh={() => void Promise.all([refreshDashboard(), refreshProcessMonitor()])} onNavigate={(target: PortalNavTarget) => setView(target)} /> ) : null} {view === "live_tiktok" ? ( void runProcess(a)} onSaveUrlConfig={(c) => saveUrlConfig(c)} onReplayGoLive={async (replayUrl, label) => { const safe = label.replace(/[,,|]/g, "_"); await saveUrlConfig(`原画,${replayUrl},主播: ${safe}`); await runProcess("start"); }} onCopy={copyText} fetchJson={fetchJson} apiPrefix={base} quickLinks={ql} hdmiStatus={dash?.hdmi} notify={notify} onNavigate={(target: PortalNavTarget) => setView(target)} /> ) : null} {view === "android" ? ( androidAction(action, payload ?? {})} onCopy={copyText} onRefreshDevices={() => void refreshDashboard()} /> ) : null} {view === "studio" ? (

{t("工作室", "Studio")}

Home Assistant / Frigate / WOL

{studioServices.filter((s) => s?.running).length}/{studioServices.length || 4} online
{studioPlaybooks.map((playbook) => { const playbookId = playbook.id || ""; const playbookBusy = busy === `studio:playbook:${playbookId}`; const dependencies = playbook.dependencies || (playbook.services || []).map((serviceId) => { const svc = serviceById.get(serviceId); return { service_id: serviceId, label: svc?.label || serviceId, running: !!svc?.running, available: svc?.available !== false, status: svc?.status || "unknown", detail: svc?.detail || "" }; }); const requiredCount = playbook.required_count ?? dependencies.length; const runningCount = playbook.running_count ?? dependencies.filter((item) => item.running).length; return (

{playbook.title || playbookId}

{playbook.description || playbook.category || "Playbook"}

{runningCount}/{requiredCount || 0}
{dependencies.map((dependency) => { const serviceId = dependency.service_id || ""; return ( {serviceId || dependency.label || "service"}:{dependency.running ? "on" : dependency.available === false ? "off" : dependency.status || "idle"} ); })}
{(playbook.actions || []).slice(0, 4).map((step, idx) => (
{step.label || step.service || "service"} {step.action || "run"}
))}
); })}
{[ { id: "homeassistant", label: "Home Assistant", icon: Home, fallbackUrl: ql.homeassistant, iconClass: portalTheme === "light" ? "text-emerald-700" : "text-emerald-300", openClass: portalTheme === "light" ? "bg-emerald-50 text-emerald-800 ring-1 ring-emerald-200 hover:bg-emerald-100" : "bg-emerald-500/15 text-emerald-100 ring-1 ring-emerald-400/25 hover:bg-emerald-500/25", }, { id: "frigate", label: "Frigate NVR", icon: Camera, fallbackUrl: ql.frigate, iconClass: portalTheme === "light" ? "text-cyan-700" : "text-cyan-300", openClass: portalTheme === "light" ? "bg-cyan-50 text-cyan-800 ring-1 ring-cyan-200 hover:bg-cyan-100" : "bg-cyan-500/15 text-cyan-100 ring-1 ring-cyan-400/25 hover:bg-cyan-500/25", }, { id: "ntfy", label: "ntfy", icon: Bell, fallbackUrl: ql.ntfy, iconClass: portalTheme === "light" ? "text-violet-700" : "text-violet-300", openClass: portalTheme === "light" ? "bg-violet-50 text-violet-800 ring-1 ring-violet-200 hover:bg-violet-100" : "bg-violet-500/15 text-violet-100 ring-1 ring-violet-400/25 hover:bg-violet-500/25", }, ].map((item) => { const svc = serviceById.get(item.id); const Icon = item.icon; const openUrl = svc?.url || item.fallbackUrl || ""; const disabled = !!busy || svc?.available === false; return (

{item.label}

{svc?.description || (item.id === "frigate" ? "Camera NVR and detection console" : "Local automation workspace")}

{svc?.running ? t("运行中", "Running") : svc?.status || "unknown"}
{svc?.detail ? (

{svc.detail}

) : null}
{openUrl ? ( {t("打开", "Open")} ) : null}
); })}

{t("WOL 网络唤醒", "WOL Network Wake")}

{wolService?.detail || "broadcast=255.255.255.255;port=9"}

{wolService?.status || "ready"}
{SHOW_STUDIO_SERIAL_CONTROL ? (

{t("串口控制", "Serial control")}

{serialPorts.length ? `${serialPorts.length} ${t("个端口", "ports")}` : t("未发现串口,可手动输入路径", "No serial port detected; path can be entered manually")}