sh2/d2ypp2/web-console/components/live-product/LiveControlApp.tsx
2026-06-03 10:53:02 -05:00

3476 lines
183 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"use client";
import { AnimatePresence, motion } from "framer-motion";
import {
Activity,
ArrowUpRight,
Bell,
Camera,
Cable,
ChevronRight,
CirclePlay,
Clock,
Copy,
Cpu,
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 { LiveStudioScene3D } from "@/components/LiveStudioScene3D";
import OverviewCharts from "@/components/OverviewCharts";
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 { LiveYoutubeUnmannedView } from "@/components/live-product/LiveYoutubeUnmannedView";
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;
const HIDE_DASHBOARD_LIVE_PROCESS_CARD = true;
function isViewKey(value: string | null): value is ViewKey {
return !!value && VIEW_KEYS.includes(value as ViewKey);
}
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<string, unknown>;
stack?: {
hostname?: string;
mdns_host?: string;
machine?: string;
kernel?: string;
python?: string;
platform?: string;
ips?: string[];
quick_links?: Record<string, string>;
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 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;
};
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<string, string>;
};
type SrsProbe = NonNullable<HubDashboard["probes"]>["srs"];
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<WireGuardImportResult["wireguard"]> & { 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 }>;
};
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;
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 formatUptime(sec?: number) {
if (sec == null || !Number.isFinite(sec)) return "—";
const s = Math.max(0, Math.floor(sec));
const d = Math.floor(s / 86400);
const h = Math.floor((s % 86400) / 3600);
const m = Math.floor((s % 3600) / 60);
if (d > 0) return `${d}d ${h}h`;
if (h > 0) return `${h}h ${m}m`;
return `${m}m`;
}
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 formatRate(value?: number) {
const text = formatBytes(value);
return text === "—" ? text : `${text}/s`;
}
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 statusLabel(status: string, t: (zh: string, en: string) => string) {
const normalized = (status || "").trim().toLowerCase();
if (normalized === "online" || normalized === "running") return t("运行中", "Running");
if (normalized === "configured") return t("已配置", "Configured");
if (normalized === "not_found") return t("未注册", "Unregistered");
if (normalized === "stopped") return t("已停止", "Stopped");
if (normalized === "error") return t("异常", "Error");
return status || "—";
}
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<Lang>("zh");
const [portalTheme, setPortalTheme] = useState<PortalTheme>("dark");
const [view, setView] = useState<ViewKey>("dashboard");
const [mobileNav, setMobileNav] = useState(false);
const [dash, setDash] = useState<HubDashboard | null>(null);
const [dashErr, setDashErr] = useState<string | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState<string | null>(null);
const [toast, setToast] = useState<string | null>(null);
const [lastSyncedAt, setLastSyncedAt] = useState<number | null>(null);
const [pageVisible, setPageVisible] = useState(true);
const [entries, setEntries] = useState<ProcessEntry[]>([]);
const [processRows, setProcessRows] = useState<ProcessMonitorRow[]>([]);
const [currentProc, setCurrentProc] = useState("");
const [urlConfig, setUrlConfig] = useState("");
const [apkPath, setApkPath] = useState("/sdcard/app.apk");
const [androidSerial, setAndroidSerial] = useState("");
const [hubCfgSnapshot, setHubCfgSnapshot] = useState<Record<string, unknown> | null>(null);
const [deployCheck, setDeployCheck] = useState<DeploymentReport | null>(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<WireGuardImportResult["wireguard"] | null>(null);
const [wgStatus, setWgStatus] = useState<WireGuardRuntimeStatus | null>(null);
const [systemNetworkProbe, setSystemNetworkProbe] = useState<SystemNetworkProbe | null>(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<WolDevice[]>([]);
const [wolSelectedMac, setWolSelectedMac] = useState("");
const [wolDeviceName, setWolDeviceName] = useState("");
const [wolDeviceIp, setWolDeviceIp] = useState("");
const [serialPorts, setSerialPorts] = useState<SerialPortInfo[]>([]);
const [serialPort, setSerialPort] = useState("");
const [serialBaudrate, setSerialBaudrate] = useState("115200");
const [serialCommand, setSerialCommand] = useState("AT");
const [serialResponse, setSerialResponse] = useState("");
const [studioOps, setStudioOps] = useState<StudioOpsSummary | null>(null);
const dashboardInFlightRef = useRef<Promise<void> | null>(null);
const processMonitorInFlightRef = useRef<Promise<void> | null>(null);
const currentProcRef = useRef(currentProc);
const urlConfigRequestSeqRef = useRef(0);
const toastTimerRef = useRef<number | null>(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 <T,>(path: string, init?: RequestInit): Promise<T> => {
return fetchJsonResponse<T>(`${base}${path}`, init);
},
[base],
);
const refreshDashboard = useCallback(async () => {
if (dashboardInFlightRef.current) return dashboardInFlightRef.current;
const task = (async () => {
try {
const [dashResult, deployResult] = await Promise.allSettled([
fetchJson<HubDashboard>("/hub/dashboard"),
fetchJson<DeploymentReport>("/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 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(() => {
const initialView = new URLSearchParams(window.location.search).get("view");
if (isViewKey(initialView)) setView(initialView);
else if (window.location.pathname.replace(/\/$/, "") === "/youtube-events") setView("live_youtube");
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(() => {
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]);
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(() => {
void refreshDashboard();
}, [refreshDashboard]);
useEffect(() => {
void refreshProcessMonitor();
}, [refreshProcessMonitor]);
useEffect(() => {
if (!autoRefreshEnabled || !pageVisible || view === "live_youtube" || view === "live_tiktok") return;
const id = window.setInterval(() => {
void refreshDashboard();
}, 10000);
return () => clearInterval(id);
}, [autoRefreshEnabled, pageVisible, refreshDashboard, view]);
useEffect(() => {
if (!autoRefreshEnabled || !pageVisible) return;
const id = window.setInterval(() => {
void refreshProcessMonitor();
}, view === "live_youtube" || view === "live_tiktok" ? 700 : 4000);
return () => clearInterval(id);
}, [autoRefreshEnabled, pageVisible, refreshProcessMonitor, view]);
useEffect(() => {
currentProcRef.current = currentProc;
}, [currentProc]);
useEffect(() => {
if (!currentProc || view !== "live_youtube") return;
void (async () => {
const targetProc = currentProcRef.current.trim();
const requestId = ++urlConfigRequestSeqRef.current;
try {
const params = new URLSearchParams({
process: targetProc,
_ts: String(Date.now()),
});
const data = await fetchJson<{ content?: string }>(`/get_url_config?${params}`);
if (requestId !== urlConfigRequestSeqRef.current || targetProc !== currentProcRef.current.trim()) return;
setUrlConfig(data.content || "");
} catch {
/* 保留当前草稿,避免临时读取失败把编辑器清空 */
}
})();
}, [currentProc, fetchJson, view]);
useEffect(() => {
if (view !== "settings") return;
void (async () => {
try {
const cfg = await fetchJson<Record<string, unknown>>("/hub/config");
setHubCfgSnapshot(cfg);
} catch {
setHubCfgSnapshot(null);
}
})();
}, [fetchJson, view]);
const ql = useMemo(() => {
const raw = dash?.stack?.quick_links || {};
const o: Record<string, string> = {};
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<string, NonNullable<HubDashboard["services"]>[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<HubDashboard["services"]>,
[serviceById],
);
const wolService = serviceById.get("wol");
const nekoLinks = useMemo<NekoBrowserLink[]>(() => 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() || "<gateway>";
const ifIndex = wgRouteIfIndex.trim() || "<ifIndex>";
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<SystemNetworkProbe>("/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<WireGuardImportResult>("/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 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<StudioOpsSummary>(`/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);
}
};
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) return;
const content = overrideContent ?? urlConfig;
const requestId = ++urlConfigRequestSeqRef.current;
setBusy("save:url");
try {
const params = new URLSearchParams({ process: proc });
await fetchJson(`/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(t("URL 配置已保存", "URL config saved"));
} catch (e) {
notify((e as Error).message);
throw e;
} finally {
setBusy(null);
}
};
const androidAction = async (action: string, payload: Record<string, unknown> = {}) => {
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 onlineServices =
dash?.services?.filter((s) => s.running && s.available).length ?? 0;
const totalServices = dash?.services?.length ?? 0;
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 (
<div
className={`lp-root min-h-screen transition-colors duration-300 ${
portalTheme === "light"
? "bg-slate-100 text-slate-900 selection:bg-violet-400/25"
: "bg-[#050508] text-zinc-100 selection:bg-violet-500/30"
}`}
>
<div
className={`lp-noise pointer-events-none fixed inset-0 z-0 ${portalTheme === "light" ? "opacity-[0.06]" : "opacity-[0.22]"}`}
aria-hidden
/>
<div
className={`lp-aurora pointer-events-none fixed -left-1/4 top-0 h-[42rem] w-[42rem] rounded-full blur-[120px] ${
portalTheme === "light" ? "bg-violet-400/15" : "bg-violet-600/20"
}`}
aria-hidden
/>
<div
className={`lp-aurora2 pointer-events-none fixed bottom-0 right-0 h-[36rem] w-[36rem] rounded-full blur-[100px] ${
portalTheme === "light" ? "bg-cyan-400/10" : "bg-cyan-500/10"
}`}
aria-hidden
/>
{toast ? (
<motion.div
initial={{ opacity: 0, y: 16 }}
animate={{ opacity: 1, y: 0 }}
role="status"
aria-live="polite"
aria-atomic="true"
className="fixed bottom-6 left-1/2 z-[100] max-w-md -translate-x-1/2 rounded-2xl border border-white/10 bg-zinc-950/95 px-5 py-3 text-center text-sm text-zinc-100 shadow-2xl shadow-black/50 backdrop-blur-xl"
>
{toast}
</motion.div>
) : null}
<div className="relative z-10 flex min-h-screen">
{/* Desktop sidebar */}
<aside
className={`hidden w-64 shrink-0 flex-col border-r px-4 py-6 backdrop-blur-2xl lg:flex ${
portalTheme === "light" ? "border-slate-200/90 bg-white/70" : "border-white/[0.06] bg-zinc-950/40"
}`}
>
<div className="flex items-center gap-2 px-2">
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-gradient-to-br from-violet-500 to-cyan-400 shadow-lg shadow-violet-500/25">
<Sparkles className="h-4 w-4 text-white" />
</div>
<div>
<p className={`text-[10px] font-semibold uppercase tracking-[0.2em] ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
live.local
</p>
<p className={`text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
{t("无人直播系统", "Unmanned Live System")}
</p>
</div>
</div>
<nav className="mt-10 flex flex-1 flex-col gap-1">
{navItems.map((item) => {
const Icon = item.icon;
const active = view === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => setView(item.id)}
aria-current={active ? "page" : undefined}
className={`flex items-center gap-3 rounded-xl px-3 py-2.5 text-left text-sm font-medium transition ${
portalTheme === "light"
? active
? "bg-violet-100/90 text-slate-900 shadow-inner shadow-violet-200/50"
: "text-slate-600 hover:bg-slate-200/60 hover:text-slate-900"
: active
? "bg-white/[0.08] text-white shadow-inner shadow-white/5"
: "text-zinc-500 hover:bg-white/[0.04] hover:text-zinc-200"
}`}
>
<Icon
className={`h-4 w-4 ${
portalTheme === "light"
? active
? "text-violet-600"
: "text-slate-400"
: active
? "text-violet-300"
: "text-zinc-600"
}`}
/>
{t(item.labelZh, item.labelEn)}
{active ? (
<ChevronRight className={`ml-auto h-4 w-4 ${portalTheme === "light" ? "text-slate-400" : "text-zinc-600"}`} />
) : null}
</button>
);
})}
</nav>
</aside>
{/* Main */}
<div className="flex min-w-0 flex-1 flex-col">
<header
className={`sticky top-0 z-20 flex items-center justify-between gap-3 border-b px-4 py-3 backdrop-blur-xl lg:px-8 ${
portalTheme === "light"
? "border-slate-200/80 bg-white/75 text-slate-900"
: "border-white/[0.06] bg-zinc-950/70 text-white"
}`}
>
<div className="flex min-w-0 items-center gap-3">
<button
type="button"
className={`rounded-xl border p-2 lg:hidden ${portalTheme === "light" ? "border-slate-200 bg-white/80" : "border-white/10 bg-white/5"}`}
onClick={() => setMobileNav(true)}
aria-label="Menu"
>
<Menu className="h-5 w-5" />
</button>
<div className="min-w-0">
<h1
className={`truncate text-lg font-semibold tracking-tight lg:text-xl ${
portalTheme === "light" ? "text-slate-900" : "text-white"
}`}
>
{t(
navItems.find((n) => n.id === view)?.labelZh || "",
navItems.find((n) => n.id === view)?.labelEn || "",
)}
</h1>
<p className={`truncate text-xs ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{dash?.stack?.mdns_host || "live.local"} ·{" "}
{portalTheme === "dark" ? t("夜间", "Dark mode") : t("日间", "Light mode")} · {refreshStateLabel} ·{" "}
{t("最后同步", "Last sync")} {lastSyncLabel}
</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-1.5 sm:gap-2">
<button
type="button"
onClick={() => setPortalTheme((prev) => (prev === "dark" ? "light" : "dark"))}
className={`rounded-xl border p-2 transition ${
portalTheme === "light"
? "border-slate-200 bg-white text-amber-500 shadow-sm"
: "border-white/10 bg-white/[0.06] text-violet-200"
}`}
title={portalTheme === "dark" ? t("切换到日间", "Switch to light") : t("切换到夜间", "Switch to dark")}
aria-label={portalTheme === "dark" ? t("日间模式", "Light mode") : t("夜间模式", "Dark mode")}
aria-pressed={portalTheme === "light"}
>
{portalTheme === "dark" ? <Moon className="h-5 w-5" strokeWidth={2} /> : <Sun className="h-5 w-5" strokeWidth={2} />}
</button>
<button
type="button"
onClick={() => setLang((prev) => (prev === "zh" ? "en" : "zh"))}
className={`relative rounded-xl border p-2 transition ${
portalTheme === "light"
? "border-slate-200 bg-white text-cyan-600 shadow-sm"
: "border-white/10 bg-white/[0.06] text-cyan-200"
}`}
title={lang === "zh" ? "English" : "中文"}
aria-label={t("切换语言", "Toggle language")}
aria-pressed={lang === "en"}
>
<Languages className="h-5 w-5" strokeWidth={2} />
<span
className={`absolute -bottom-0.5 -right-0.5 flex h-4 min-w-[1rem] items-center justify-center rounded px-0.5 text-[9px] font-bold leading-none ${
portalTheme === "light" ? "bg-cyan-100 text-cyan-800" : "bg-cyan-500/30 text-cyan-100"
}`}
>
{lang === "zh" ? "中" : "A"}
</span>
</button>
<button
type="button"
disabled={!!busy}
onClick={() => void Promise.all([refreshDashboard(), refreshProcessMonitor()])}
className={`flex items-center gap-2 rounded-xl border px-3 py-2 text-xs font-medium transition disabled:opacity-40 ${
portalTheme === "light"
? "border-slate-200 bg-white text-slate-700 hover:bg-slate-50"
: "border-white/10 bg-white/[0.04] text-zinc-300 hover:bg-white/[0.07]"
}`}
>
{busy ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <RefreshCw className="h-3.5 w-3.5" />}
<span className="hidden sm:inline">{t("刷新", "Refresh")}</span>
</button>
</div>
</header>
<main className="flex-1 px-4 py-6 lg:px-8 lg:py-8">
<AnimatePresence mode="wait">
<motion.div
key={view}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
exit={{ opacity: 0, y: -6 }}
transition={{ duration: 0.28, ease: [0.22, 1, 0.36, 1] }}
>
{view === "dashboard" ? (
<div className="space-y-6">
{dashErr ? (
<div className="rounded-2xl border border-rose-500/25 bg-rose-950/20 p-4 text-sm text-rose-200">
{t("无法加载仪表盘:", "Dashboard error: ")}
{dashErr}
</div>
) : null}
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.02 }}
className={`rounded-2xl border p-2 backdrop-blur-xl ${
portalTheme === "light"
? "border-slate-200/90 bg-white/80 shadow-sm shadow-slate-200/30"
: "border-white/[0.07] bg-zinc-950/30"
}`}
>
<OverviewCharts snapshot={dash?.snapshot ?? null} theme={portalTheme} tr={t} />
</motion.div>
<motion.div
initial={{ opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: 0.05 }}
className={`rounded-2xl border p-3 shadow-lg ${
portalTheme === "light"
? "border-fuchsia-200/80 bg-gradient-to-br from-fuchsia-50/90 via-white to-cyan-50/70 shadow-fuchsia-100/40"
: "border-fuchsia-500/20 bg-gradient-to-br from-fuchsia-500/10 via-zinc-950/60 to-cyan-500/10 shadow-fuchsia-900/10"
}`}
>
<LiveStudioScene3D tr={t} />
</motion.div>
<div className="grid gap-2 sm:grid-cols-2 xl:grid-cols-5">
{[
{
icon: Cpu,
label: t("CPU 1m", "CPU 1m"),
value: dash?.snapshot?.cpu_load?.["1m"]?.toFixed(2) ?? "—",
sub: t("负载均值", "Load avg"),
},
{
icon: Activity,
label: t("内存", "Memory"),
value: formatBytes(dash?.snapshot?.memory?.available),
sub: `/ ${formatBytes(dash?.snapshot?.memory?.total)}`,
},
{
icon: HardDrive,
label: t("磁盘可用", "Disk free"),
value: formatBytes(dash?.snapshot?.disk?.free),
sub: `/ ${formatBytes(dash?.snapshot?.disk?.total)}`,
},
{
icon: Server,
label: t("服务在线", "Services up"),
value: `${onlineServices}/${totalServices || "—"}`,
sub: t("基础服务层", "Infra layer"),
},
{
icon: Clock,
label: t("运行时间", "Uptime"),
value: formatUptime(dash?.snapshot?.uptime_seconds),
sub: t("自开机", "Since boot"),
},
].map((card, i) => (
<motion.div
key={card.label}
initial={{ opacity: 0, y: 12 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.05, duration: 0.35, ease: [0.22, 1, 0.36, 1] }}
whileHover={{ y: -2 }}
className="group relative overflow-hidden rounded-xl border border-white/[0.07] bg-gradient-to-br from-white/[0.05] to-transparent p-3 shadow-lg shadow-black/20"
>
<div className="absolute -right-4 -top-4 h-16 w-16 rounded-full bg-violet-500/10 blur-xl transition group-hover:bg-violet-500/18" />
<card.icon className="h-4 w-4 text-violet-300/90" />
<p className="mt-2 text-[10px] font-semibold uppercase tracking-wider text-zinc-500">{card.label}</p>
<p className="mt-0.5 font-mono text-lg font-semibold leading-tight text-white">{loading ? "…" : card.value}</p>
<p className="mt-0.5 text-[10px] text-zinc-500">{card.sub}</p>
</motion.div>
))}
</div>
{dash?.hardware && typeof dash.hardware === "object" ? (
<div className="rounded-2xl border border-indigo-500/25 bg-gradient-to-br from-indigo-500/[0.1] via-zinc-950/70 to-violet-500/[0.08] p-6 shadow-2xl shadow-indigo-500/5">
<h3 className="text-base font-semibold text-white">
{t("系统硬件与软件能力", "Hardware & software profile")}
</h3>
<p className="mt-1 text-[11px] text-zinc-500">
{t(
"来自 hardware_probe;用于直播/解码策略参考。",
"From hardware_probe; guides decode/streaming posture.",
)}
</p>
<div className="mt-5 grid gap-4 lg:grid-cols-2">
<div className="space-y-3 rounded-xl border border-white/[0.06] bg-black/30 p-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-indigo-300/90">
{t("平台", "Platform")}
</p>
<dl className="space-y-2 font-mono text-[11px] text-zinc-400">
<div className="flex justify-between gap-2">
<dt className="text-zinc-600">arch</dt>
<dd className="text-right text-zinc-200">{String(dash.hardware.arch ?? "—")}</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-zinc-600">kernel</dt>
<dd className="text-right text-zinc-200">{String(dash.hardware.kernel ?? dash.stack?.kernel ?? "—")}</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-zinc-600">Python</dt>
<dd className="text-right text-zinc-200">{String(dash.stack?.python ?? "—")}</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-zinc-600">mDNS</dt>
<dd className="text-right text-cyan-200/90">{dash.stack?.mdns_host ?? "—"}</dd>
</div>
<div className="flex justify-between gap-2">
<dt className="text-zinc-600">IP</dt>
<dd className="text-right text-zinc-300">{(dash.stack?.ips || []).join(" · ") || "—"}</dd>
</div>
</dl>
</div>
<div className="space-y-3 rounded-xl border border-white/[0.06] bg-black/30 p-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-fuchsia-300/90">GPU / NPU</p>
{(() => {
const gpu = dash.hardware.gpu as
| { present?: boolean; driver?: string; cards?: string[]; render_nodes?: string[] }
| undefined;
const npu = dash.hardware.npu as { present?: boolean; devices?: string[] } | undefined;
return (
<dl className="space-y-2 font-mono text-[11px] text-zinc-400">
<div>
<dt className="text-zinc-600">GPU</dt>
<dd className="mt-0.5 text-zinc-200">
{gpu?.present ? t("已检测", "present") : t("未检测", "absent")}
{gpu?.driver ? ` · ${gpu.driver}` : ""}
</dd>
</div>
<div>
<dt className="text-zinc-600">render</dt>
<dd className="mt-0.5 break-all text-zinc-500">
{(gpu?.render_nodes || []).join(", ") || "—"}
</dd>
</div>
<div>
<dt className="text-zinc-600">NPU</dt>
<dd className="mt-0.5 break-all text-zinc-500">
{npu?.present ? (npu.devices || []).join(", ") : t("—", "—")}
</dd>
</div>
</dl>
);
})()}
</div>
<div className="space-y-3 rounded-xl border border-white/[0.06] bg-black/30 p-4 lg:col-span-2">
<p className="text-[10px] font-semibold uppercase tracking-wider text-emerald-300/90">
ffmpeg / 建议策略
</p>
{(() => {
const acc = (dash.hardware.ffmpeg_hwaccels as string[] | undefined) || [];
const rec = dash.hardware.recommendation as
| {
video_decoder?: string;
hdmi_player?: string;
browser_hwaccel?: string;
stability_mode?: string;
degradation_reasons?: string[];
}
| undefined;
return (
<div className="space-y-2 text-[11px] text-zinc-400">
<p>
<span className="text-zinc-600">hwaccels: </span>
<span className="font-mono text-emerald-200/90">{acc.length ? acc.join(", ") : "—"}</span>
</p>
<div className="grid gap-2 sm:grid-cols-2">
<p>
<span className="text-zinc-600">{t("解码", "Decoder")}: </span>
<span className="text-zinc-200">{rec?.video_decoder ?? "—"}</span>
</p>
<p>
<span className="text-zinc-600">HDMI: </span>
<span className="text-zinc-200">{rec?.hdmi_player ?? "—"}</span>
</p>
<p>
<span className="text-zinc-600">Browser: </span>
<span className="text-zinc-200">{rec?.browser_hwaccel ?? "—"}</span>
</p>
<p>
<span className="text-zinc-600">{t("稳定模式", "Stability")}: </span>
<span className="text-amber-200/90">{rec?.stability_mode ?? "—"}</span>
</p>
</div>
{(rec?.degradation_reasons || []).length ? (
<ul className="mt-2 list-inside list-disc space-y-1 text-[10px] text-amber-200/80">
{(rec?.degradation_reasons || []).map((r) => (
<li key={r}>{r}</li>
))}
</ul>
) : null}
</div>
);
})()}
</div>
</div>
</div>
) : null}
{deployCheck ? (
<div
className={`rounded-2xl border p-5 ${
deployCheck.ready
? "border-emerald-500/25 bg-gradient-to-br from-emerald-500/[0.08] via-zinc-950/50 to-cyan-500/[0.05]"
: "border-amber-500/30 bg-gradient-to-br from-amber-500/[0.1] via-zinc-950/55 to-rose-500/[0.05]"
}`}
>
<div className="flex flex-wrap items-start justify-between gap-3">
<div>
<h3 className="text-sm font-semibold text-white">{t("安装验收", "Deployment health")}</h3>
<p className="mt-1 text-[11px] text-zinc-500">
{t(
"一键脚本完成后,本机 API、局域网入口、反向代理与 mDNS 的可用性检查。",
"Post-install checks for loopback API, LAN access, reverse proxy, and mDNS.",
)}
</p>
</div>
<span
className={`rounded-full px-3 py-1 text-[10px] font-semibold ${
deployCheck.ready
? "bg-emerald-500/20 text-emerald-100 ring-1 ring-emerald-500/30"
: "bg-amber-500/20 text-amber-100 ring-1 ring-amber-500/30"
}`}
>
{deployCheck.ready ? t("可交付", "Ready") : t("需处理", "Needs attention")}
</span>
</div>
<div className="mt-4 grid gap-4 lg:grid-cols-2">
<div className="rounded-xl border border-white/[0.06] bg-black/30 p-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
{t("验收摘要", "Acceptance summary")}
</p>
<p className="mt-2 font-mono text-sm text-white">
{deployCheck.pass_count ?? 0}/{deployCheck.total_count ?? 0}
<span className="ml-2 text-[11px] text-zinc-500">
{t("已通过", "checks passed")}
</span>
</p>
<p className="mt-1 text-[11px] text-zinc-500">
{t("必需项", "Required")}: {deployCheck.required_total ?? 0} · mDNS{" "}
{deployCheck.mdns_enabled ? t("已启用", "enabled") : t("已关闭", "disabled")} · edge{" "}
{deployCheck.live_edge_enabled ? t("已启用", "enabled") : t("已关闭", "disabled")}
</p>
<div className="mt-3 flex flex-wrap gap-2">
{Object.entries(deployCheck.urls || {})
.filter(([, url]) => !!url)
.slice(0, 4)
.map(([key, url]) => (
<a
key={key}
href={normalizeBrowserReachableHttpUrl(url)}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-white/10 bg-white/5 px-3 py-2 text-[11px] text-zinc-200 ring-1 ring-white/10"
>
{key}
</a>
))}
</div>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/30 p-4">
<p className="text-[10px] font-semibold uppercase tracking-wider text-zinc-500">
{deployCheck.failing_checks?.length ? t("失败项", "Failing checks") : t("当前状态", "Current state")}
</p>
{deployCheck.failing_checks?.length ? (
<ul className="mt-2 space-y-2 text-[11px] text-zinc-300">
{deployCheck.failing_checks.slice(0, 4).map((item) => (
<li key={item.id} className="rounded-lg border border-amber-500/20 bg-amber-500/10 px-3 py-2">
<span className="font-semibold text-amber-100">{item.label}</span>
<span className="ml-2 text-zinc-400">{item.detail || "—"}</span>
</li>
))}
</ul>
) : (
<p className="mt-2 text-[11px] text-emerald-200/90">
{t("必需检查已全部通过,可直接用浏览器面板交付。", "All required checks pass; browser control plane is ready.")}
</p>
)}
{(deployCheck.hints || []).length ? (
<ul className="mt-3 list-inside list-disc space-y-1 text-[10px] text-zinc-400">
{(deployCheck.hints || []).slice(0, 3).map((hint) => (
<li key={hint}>{hint}</li>
))}
</ul>
) : null}
</div>
</div>
</div>
) : null}
{dash?.stack?.neko_login ? (
<div className="rounded-2xl border border-fuchsia-500/25 bg-gradient-to-r from-fuchsia-500/[0.08] to-violet-500/[0.06] p-5">
<h3 className="text-sm font-semibold text-white">Neko {t("登录", "sign-in")}</h3>
<p className="mt-1 text-[11px] text-zinc-500">
{dash.stack.neko_login.note_zh ||
t(
nekoPortsLabel ? `Neko Chromium ${nekoPortsLabel} 使用下列账号策略。` : "Neko Chromium 多实例使用下列账号策略。",
nekoPortsLabel ? `Neko Chromium ${nekoPortsLabel} uses the policy below.` : "Neko Chromium instances use the policy below.",
)}
</p>
<p className="mt-2 text-[11px] text-amber-200/85">
{t(
"重要:两栏分开填——昵称随意,密码必须是环境变量里的口令(默认 12345678)。用错密码会像一直加载;勿把「用户名/密码」写在一行。",
"Use two fields: display name is free-form; password must match NEKO_* (default 12345678). Wrong password looks like infinite loading.",
)}
</p>
{nekoLinks.length ? (
<div className="mt-4 flex flex-wrap gap-2">
{nekoLinks.map((link) => (
<a
key={link.key}
href={link.url}
target="_blank"
rel="noreferrer"
className="rounded-lg border border-fuchsia-400/20 bg-black/25 px-3 py-2 text-[11px] text-fuchsia-100 ring-1 ring-fuchsia-400/20"
>
<span className="font-semibold">{link.label}</span>
<span className="ml-2 rounded-full bg-fuchsia-500/15 px-1.5 py-0.5 text-[10px] text-fuchsia-100">
{link.accessLabel}
</span>
<span className="ml-2 font-mono text-fuchsia-100/75">
{link.host || ""}
{link.port ? `:${link.port}` : ""}
</span>
</a>
))}
</div>
) : null}
<div className="mt-4 grid gap-3 sm:grid-cols-2 font-mono text-sm">
<div className="rounded-xl border border-white/10 bg-black/40 px-4 py-3">
<p className="text-[10px] uppercase text-zinc-500">{t("昵称示例", "Display Name Example")}</p>
<p className="mt-1 text-fuchsia-200">{dash.stack.neko_login.user_login ?? "live"}</p>
<p className="mt-2 text-[10px] uppercase text-zinc-500">{t("连接口令", "Access Password")}</p>
<p className="mt-0.5 text-fuchsia-100">{dash.stack.neko_login.user_password ?? "—"}</p>
</div>
<div className="rounded-xl border border-white/10 bg-black/40 px-4 py-3">
<p className="text-[10px] uppercase text-zinc-500">{t("管理昵称示例", "Admin Display Name Example")}</p>
<p className="mt-1 text-violet-200">{dash.stack.neko_login.admin_login ?? "admin"}</p>
<p className="mt-2 text-[10px] uppercase text-zinc-500">{t("管理口令", "Admin Password")}</p>
<p className="mt-0.5 text-violet-100">{dash.stack.neko_login.admin_password ?? "—"}</p>
</div>
</div>
<p className="mt-3 text-[10px] text-zinc-600">
{t(
"x86 默认使用 Neko 的 Chrome 镜像,ARM 默认使用 Chromium 镜像;默认保留管理员会话、开发者工具和 Tampermonkey 持久化。本栈未启用 Firefox 版 Neko。",
"x86 defaults to Neko’s Chrome image, ARM defaults to Chromium, and admin access, DevTools, plus persistent Tampermonkey stay enabled. This stack does not use Firefox Neko.",
)}
</p>
</div>
) : null}
{dash?.network?.interfaces?.length ? (
<div className="rounded-2xl border border-cyan-500/15 bg-gradient-to-br from-cyan-500/[0.07] to-transparent p-5">
<h3 className="flex items-center gap-2 text-sm font-semibold text-white">
<Wifi className="h-4 w-4 text-cyan-300" />
{t("网络带宽 / 流量", "Network bandwidth / traffic")}
</h3>
<p className="mt-1 text-[11px] text-zinc-500">
{t(
"实时速率由总览自动刷新间隔计算;累计值来自系统网卡计数器。",
"Live rates are calculated from dashboard refresh deltas; totals come from kernel counters.",
)}
</p>
<div className="mt-4 grid gap-3 sm:grid-cols-2">
<div className="rounded-xl border border-white/[0.06] bg-black/25 px-4 py-3 font-mono text-[11px]">
<p className="text-[10px] uppercase tracking-[0.08em] text-cyan-300/70">{t("实时下行", "Live down")}</p>
<p className="mt-1 text-lg font-semibold text-cyan-100">{formatRate(dash.network.total_rx_bps)}</p>
<p className="mt-1 text-zinc-500">{t("累计", "Total")}: {formatBytes(dash.network.total_rx_bytes)}</p>
</div>
<div className="rounded-xl border border-white/[0.06] bg-black/25 px-4 py-3 font-mono text-[11px]">
<p className="text-[10px] uppercase tracking-[0.08em] text-cyan-300/70">{t("实时上行", "Live up")}</p>
<p className="mt-1 text-lg font-semibold text-cyan-100">{formatRate(dash.network.total_tx_bps)}</p>
<p className="mt-1 text-zinc-500">{t("累计", "Total")}: {formatBytes(dash.network.total_tx_bytes)}</p>
</div>
</div>
<div className="mt-4 grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{(dash.network.interfaces || []).slice(0, 6).map((iface) => (
<div
key={iface.name}
className="rounded-xl border border-white/[0.06] bg-black/25 px-4 py-3 font-mono text-[11px]"
>
<p className="text-xs font-semibold text-cyan-200/90">{iface.name}</p>
<p className="mt-2 text-zinc-500">
{t("链路", "Link")}: {iface.operstate || "unknown"} <span className="text-zinc-600">·</span>{" "}
{iface.speed_mbps ? `${iface.speed_mbps} Mbps` : t("未知速率", "unknown speed")}
</p>
<p className="mt-2 text-zinc-500">
↓ {formatRate(iface.rx_bps)} <span className="text-zinc-600">·</span>{" "}
{formatBytes(iface.rx_bytes)} <span className="text-zinc-600">·</span>{" "}
{iface.rx_packets?.toLocaleString() ?? "—"} pkt
</p>
<p className="mt-0.5 text-zinc-500">
↑ {formatRate(iface.tx_bps)} <span className="text-zinc-600">·</span>{" "}
{formatBytes(iface.tx_bytes)} <span className="text-zinc-600">·</span>{" "}
{iface.tx_packets?.toLocaleString() ?? "—"} pkt
</p>
</div>
))}
</div>
</div>
) : null}
{(dash?.live_events?.pm2_tail?.length || dash?.live_events?.process_digest?.length) ? (
<div className="grid gap-4 lg:grid-cols-2">
<div className="rounded-2xl border border-amber-500/15 bg-zinc-950/40 p-5">
<h3 className="text-sm font-semibold text-white">{t("直播 / PM2 事件", "Live / PM2 feed")}</h3>
<p className="mt-1 text-[11px] text-zinc-500">{t("PM2 合并日志尾部", "PM2 merged log tail")}</p>
<pre className="mt-3 max-h-48 overflow-auto whitespace-pre-wrap rounded-lg border border-white/[0.05] bg-black/40 p-3 font-mono text-[10px] leading-relaxed text-zinc-400">
{(dash?.live_events?.pm2_tail || []).join("\n") || t("暂无 PM2 输出", "No PM2 output")}
</pre>
</div>
<div className="rounded-2xl border border-violet-500/15 bg-zinc-950/40 p-5">
<h3 className="text-sm font-semibold text-white">{t("进程快照", "Process digest")}</h3>
<ul className="mt-3 space-y-2">
{(dash?.live_events?.process_digest || []).map((row) => (
<li
key={row.pm2}
className="flex items-center justify-between gap-2 rounded-lg border border-white/[0.05] bg-black/30 px-3 py-2 text-xs"
>
<span className="truncate text-zinc-300">{row.label || row.pm2}</span>
<span
className={`shrink-0 rounded-md px-2 py-0.5 text-[10px] font-medium ${statusPill(row.status || "")}`}
>
{statusLabel(row.status || "", t)}
</span>
</li>
))}
</ul>
</div>
</div>
) : null}
{!HIDE_DASHBOARD_LIVE_PROCESS_CARD ? (
<div className="rounded-2xl border border-violet-500/20 bg-gradient-to-br from-violet-500/[0.12] via-zinc-950/50 to-fuchsia-500/[0.06] p-5 shadow-lg shadow-violet-500/5">
<div className="flex items-center justify-between gap-2">
<h3 className="text-sm font-semibold text-white">{t("直播进程", "Live processes")}</h3>
<span className="rounded-full bg-white/10 px-2 py-0.5 text-[10px] font-medium text-zinc-300">
{dash?.live?.backend_mode || "—"}
</span>
</div>
<ul className="mt-4 space-y-2.5">
{(dash?.live?.processes || []).slice(0, 10).map((p) => (
<li
key={p.pm2}
className="group flex items-center gap-3 rounded-xl border border-white/[0.08] bg-black/35 px-3 py-2.5 transition hover:border-violet-400/25 hover:bg-black/45"
>
<div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-lg bg-gradient-to-br from-violet-500/30 to-fuchsia-500/20 text-[10px] font-bold text-violet-100 ring-1 ring-white/10">
LIVE
</div>
<div className="min-w-0 flex-1">
<p className="truncate text-sm font-medium text-zinc-100">{p.label || p.pm2}</p>
<p className="truncate font-mono text-[10px] text-zinc-600">{p.script || p.pm2}</p>
</div>
<span className={`shrink-0 rounded-lg px-2.5 py-1 text-[10px] font-semibold ${statusPill(p.process_status || "")}`}>
{statusLabel(p.process_status || "", t)}
</span>
</li>
))}
{!dash?.live?.processes?.length ? (
<li className="rounded-xl border border-dashed border-white/10 py-8 text-center text-xs text-zinc-600">
{t("暂无直播进程", "No live processes")}
</li>
) : null}
</ul>
<div className="mt-5 grid grid-cols-2 gap-2">
<button
type="button"
onClick={() => setView("live_youtube")}
className="rounded-xl border border-violet-400/35 bg-violet-500/15 py-2.5 text-[11px] font-semibold text-violet-100 shadow-inner shadow-black/20 transition hover:bg-violet-500/25"
>
YouTube
</button>
<button
type="button"
onClick={() => setView("live_tiktok")}
className="rounded-xl border border-cyan-400/35 bg-cyan-500/15 py-2.5 text-[11px] font-semibold text-cyan-100 shadow-inner shadow-black/20 transition hover:bg-cyan-500/25"
>
TikTok
</button>
</div>
</div>
) : null}
{dash?.probes && showStreamProbes ? (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{dash.probes.srs ? (
(() => {
const sp = dash.probes?.srs as SrsProbe | undefined;
const tcpOk = sp?.tcp?.reachable;
const tcpApiOk = sp?.tcp_api?.reachable;
const httpUi = sp?.http_ui;
const http = sp?.http;
const apiPort = sp?.api_port;
const apiHealthy = sp?.api_ok ?? (http?.http_code === 200);
const uiCode = httpUi?.http_code;
return (
<div className="rounded-2xl border border-white/[0.07] bg-zinc-950/40 p-4 backdrop-blur-sm">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold text-white">SRS</p>
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${
apiHealthy
? "bg-emerald-500/20 text-emerald-200 ring-1 ring-emerald-500/30"
: "bg-rose-500/15 text-rose-200 ring-1 ring-rose-500/25"
}`}
>
{apiHealthy ? t("API 正常", "API OK") : t("API 异常", "API down")}
</span>
</div>
<p className="mt-1 font-mono text-[11px] text-zinc-500">
:{sp?.port ?? "—"} / API :{apiPort ?? "—"} · TCP {tcpOk ? "OK" : "—"} · API TCP{" "}
{tcpApiOk ? "OK" : "—"}
</p>
<p className="mt-1 font-mono text-[11px] text-zinc-500">
API HTTP {http?.http_code ?? "—"} · {t("根路径", "root")} {uiCode ?? "—"}
{uiCode === 404
? t("(无首页不影响推流)", " (no index is OK for streaming)")
: null}
</p>
<p className="mt-1 text-[11px] text-zinc-500">
{t("延迟", "RTT")}{" "}
{http?.latency_ms != null
? `${http.latency_ms} ms`
: sp?.tcp?.latency_ms != null
? `${sp.tcp.latency_ms} ms`
: "—"}
</p>
{!apiHealthy && http?.error ? (
<p className="mt-1 line-clamp-2 text-[10px] text-amber-200/80">{http.error}</p>
) : null}
</div>
);
})()
) : null}
{dash.probes.neko ? (
(() => {
const p = dash.probes?.neko;
const tcpOk = p?.tcp?.reachable;
const http = p?.http;
const instances = p?.instances || [];
const runningCount = p?.running_count ?? instances.filter((item) => item.tcp?.reachable).length;
const requiredCount = p?.required_count ?? instances.length;
return (
<div className="rounded-2xl border border-white/[0.07] bg-zinc-950/40 p-4 backdrop-blur-sm">
<div className="flex items-center justify-between gap-2">
<p className="text-xs font-semibold text-white">Neko Chromium</p>
<span
className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${
runningCount > 0
? "bg-emerald-500/20 text-emerald-200 ring-1 ring-emerald-500/30"
: "bg-rose-500/15 text-rose-200 ring-1 ring-rose-500/25"
}`}
>
{runningCount}/{requiredCount || "—"} {t("在线", "online")}
</span>
</div>
<p className="mt-1 text-[11px] text-zinc-500">
{t(
"Docker 内 Chromium(非 Chrome 品牌);arm64/x86 同一镜像。",
"Chromium in Docker (not Chrome branding); multi-arch.",
)}
</p>
<p className="mt-2 font-mono text-[11px] text-zinc-500">
:{p?.port ?? "—"} · TCP {tcpOk ? "OK" : "—"} · HTTP {http?.http_code ?? "—"}
</p>
<p className="mt-1 text-[11px] text-zinc-500">
{t("延迟", "RTT")}{" "}
{http?.latency_ms != null
? `${http.latency_ms} ms`
: p?.tcp?.latency_ms != null
? `${p.tcp.latency_ms} ms`
: "—"}
</p>
{instances.length ? (
<div className="mt-3 space-y-2">
{instances.map((item) => (
<div
key={`${item.id}-${item.port}`}
className="flex items-center justify-between gap-3 rounded-lg border border-white/[0.05] bg-black/25 px-3 py-2"
>
<div className="min-w-0">
<p className="text-[11px] font-semibold text-zinc-200">
Neko {item.id ?? "?"}
</p>
<p className="font-mono text-[10px] text-zinc-500">
:{item.port ?? "—"} · TCP {item.tcp?.reachable ? "OK" : "—"} · HTTP{" "}
{item.http?.http_code ?? "—"}
</p>
</div>
<span
className={`shrink-0 rounded-full px-2 py-0.5 text-[10px] font-semibold ${
item.tcp?.reachable
? "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-500/25"
: "bg-zinc-500/15 text-zinc-400 ring-1 ring-zinc-500/25"
}`}
>
{item.tcp?.reachable ? t("运行中", "Running") : t("未连通", "Offline")}
</span>
</div>
))}
</div>
) : null}
{!http?.reachable && http?.error ? (
<p className="mt-1 line-clamp-2 text-[10px] text-amber-200/80">{http.error}</p>
) : null}
</div>
);
})()
) : null}
</div>
) : null}
</div>
) : null}
{view === "services" ? (
<div className="grid gap-4 md:grid-cols-2 xl:grid-cols-3">
{(dash?.services || []).map((s, i) => (
<motion.div
key={s.service_id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ delay: i * 0.04 }}
whileHover={{ y: -2 }}
className="rounded-2xl border border-white/[0.07] bg-gradient-to-b from-white/[0.05] to-transparent p-5"
>
<div className="flex items-start justify-between gap-2">
<div>
<h3 className="font-semibold text-white">{s.label}</h3>
<p className="mt-1 text-xs text-zinc-500 line-clamp-2">{s.description}</p>
</div>
<span className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-semibold ${statusPill(s.running ? "online" : s.status)}`}>
{s.running ? t("运行中", "Running") : s.status}
</span>
</div>
{s.detail ? (
<p
className={`mt-2 text-[11px] leading-snug line-clamp-6 ${
s.status === "skipped" ? "text-slate-300/90" : "text-amber-200/85"
}`}
>
{s.detail}
</p>
) : null}
{s.service_id === "shellcrash" && s.available && !s.running ? (
<p className="mt-2 text-[11px] text-zinc-500">
{t(
"stopped 为常态:仅当需要透明代理 / 规则分流时再手动点 Start,不建议设置自启。",
"Stopped is normal; click Start manually only when the proxy is needed. Autostart stays off.",
)}
</p>
) : null}
<div className="mt-4 flex flex-wrap items-center gap-2">
{s.url ? (
<a
href={normalizeBrowserReachableHttpUrl(s.url)}
target="_blank"
rel="noreferrer"
className="rounded-lg bg-violet-500/15 px-3 py-1.5 text-xs font-medium text-violet-200 ring-1 ring-violet-500/25"
>
{t("打开面板", "Open panel")}
</a>
) : null}
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "start")}
className="rounded-lg bg-emerald-500/20 px-3 py-1.5 text-xs font-medium text-emerald-200 ring-1 ring-emerald-500/30 disabled:opacity-30"
>
Start
</button>
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "install")}
className="rounded-lg bg-sky-500/15 px-3 py-1.5 text-xs font-medium text-sky-200 ring-1 ring-sky-500/25 disabled:opacity-30"
>
Install
</button>
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "restart")}
className="rounded-lg bg-amber-500/15 px-3 py-1.5 text-xs font-medium text-amber-200 ring-1 ring-amber-500/25 disabled:opacity-30"
>
Restart
</button>
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "upgrade")}
className="rounded-lg bg-indigo-500/15 px-3 py-1.5 text-xs font-medium text-indigo-200 ring-1 ring-indigo-500/25 disabled:opacity-30"
>
Upgrade
</button>
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "stop")}
className="rounded-lg bg-rose-500/15 px-3 py-1.5 text-xs font-medium text-rose-200 ring-1 ring-rose-500/25 disabled:opacity-30"
>
Stop
</button>
<button
type="button"
disabled={!!busy || !s.available || (s.service_id === "android_gateway" && s.status === "skipped")}
title={
s.service_id === "android_gateway" && s.status === "skipped"
? t("单网口无需网关", "Not needed on single NIC")
: !s.available
? s.detail || t("当前不可操作", "Unavailable")
: undefined
}
onClick={() => void runService(s.service_id, "uninstall")}
className="rounded-lg bg-zinc-500/15 px-3 py-1.5 text-xs font-medium text-zinc-200 ring-1 ring-zinc-500/25 disabled:opacity-30"
>
Uninstall
</button>
</div>
</motion.div>
))}
{!dash?.services?.length ? (
<p className="text-sm text-zinc-500">{t("暂无服务数据", "No services")}</p>
) : null}
</div>
) : null}
{view === "live_youtube" ? (
<LiveYoutubeUnmannedView
t={t}
busy={busy}
entries={entries}
currentProc={currentProc}
setCurrentProc={setCurrentProc}
urlConfig={urlConfig}
setUrlConfig={setUrlConfig}
onRunProcess={(a, pm) => void runProcess(a, pm)}
onSaveUrlConfig={(c, pm) => saveUrlConfig(c, pm)}
fetchJson={fetchJson}
liveProcesses={processRows.length ? processRows : (dash?.live?.processes ?? [])}
notify={notify}
quickLinks={ql}
onNavigate={(target: PortalNavTarget) => setView(target)}
/>
) : null}
{view === "live_tiktok" ? (
<LiveTiktokHdmiView
t={t}
busy={!!busy}
entries={entries}
currentProc={currentProc}
setCurrentProc={setCurrentProc}
urlConfig={urlConfig}
setUrlConfig={setUrlConfig}
onRunProcess={(a) => 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" ? (
<LiveAndroidWorkstation
t={t}
notify={notify}
fetchJson={fetchJson}
apiBase={base}
busy={busy}
androidSerial={androidSerial}
setAndroidSerial={setAndroidSerial}
devices={dash?.android?.devices || []}
adbAvailable={!!dash?.android?.adb_available}
apkPath={apkPath}
setApkPath={setApkPath}
onAndroidAction={(action, payload) => androidAction(action, payload ?? {})}
onCopy={copyText}
onRefreshDevices={() => void refreshDashboard()}
/>
) : null}
{view === "studio" ? (
<div className="mx-auto max-w-7xl space-y-5">
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
<div>
<h3 className={`flex items-center gap-2 text-base font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Home className={`h-5 w-5 ${portalTheme === "light" ? "text-emerald-700" : "text-emerald-300"}`} />
{t("工作室", "Studio")}
</h3>
<p className={`mt-1 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
Home Assistant / Frigate / WOL
</p>
</div>
<span
className={`w-fit rounded-full px-3 py-1 text-[11px] font-semibold ${
portalTheme === "light" ? "bg-emerald-50 text-emerald-800 ring-1 ring-emerald-200" : "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-500/25"
}`}
>
{studioServices.filter((s) => s?.running).length}/{studioServices.length || 4} online
</span>
</div>
<div className="grid gap-4 xl:grid-cols-4">
{[
{
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 (
<motion.div
key={item.id}
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex items-start justify-between gap-3">
<div className="min-w-0">
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Icon className={`h-4 w-4 ${item.iconClass}`} />
{item.label}
</h3>
<p className={`mt-2 line-clamp-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{svc?.description || (item.id === "frigate" ? "Camera NVR and detection console" : "Local automation workspace")}
</p>
</div>
<span className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-semibold ${statusPill(svc?.running ? "online" : svc?.status || "unknown")}`}>
{svc?.running ? t("运行中", "Running") : svc?.status || "unknown"}
</span>
</div>
{svc?.detail ? (
<p className={`mt-3 line-clamp-4 font-mono text-[11px] ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{svc.detail}
</p>
) : null}
<div className="mt-5 flex flex-wrap gap-2">
{openUrl ? (
<a
href={normalizeBrowserReachableHttpUrl(openUrl)}
target="_blank"
rel="noreferrer"
className={`inline-flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold transition ${item.openClass}`}
>
<ArrowUpRight className="h-3.5 w-3.5" />
{t("打开", "Open")}
</a>
) : null}
<button
type="button"
disabled={disabled}
onClick={() => void runService(item.id, "start")}
className="rounded-lg bg-emerald-500/15 px-3 py-2 text-xs font-semibold text-emerald-100 ring-1 ring-emerald-400/25 transition hover:bg-emerald-500/25 disabled:opacity-40"
>
Start
</button>
<button
type="button"
disabled={disabled}
onClick={() => void runService(item.id, "restart")}
className="rounded-lg bg-amber-500/15 px-3 py-2 text-xs font-semibold text-amber-100 ring-1 ring-amber-400/25 transition hover:bg-amber-500/25 disabled:opacity-40"
>
Restart
</button>
<button
type="button"
disabled={disabled}
onClick={() => void runService(item.id, "stop")}
className="rounded-lg bg-rose-500/15 px-3 py-2 text-xs font-semibold text-rose-100 ring-1 ring-rose-400/25 transition hover:bg-rose-500/25 disabled:opacity-40"
>
Stop
</button>
</div>
</motion.div>
);
})}
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Power className={`h-4 w-4 ${portalTheme === "light" ? "text-amber-700" : "text-amber-300"}`} />
{t("WOL 网络唤醒", "WOL Network Wake")}
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{wolService?.detail || "broadcast=255.255.255.255;port=9"}
</p>
</div>
<span className={`shrink-0 rounded-full px-2.5 py-1 text-[10px] font-semibold ${statusPill(wolService?.status || "ready")}`}>
{wolService?.status || "ready"}
</span>
</div>
<div className="mt-5 grid gap-3">
<div className="flex gap-2">
<select
value={wolSelectedMac}
onChange={(e) => {
const mac = e.target.value;
setWolSelectedMac(mac);
const device = wolDevices.find((item) => item.mac === mac);
if (device) {
setWolMac(device.mac);
setWolDeviceName(device.name || "");
setWolDeviceIp(device.ip || "");
}
}}
className={`min-w-0 flex-1 rounded-lg border px-3 py-2 text-xs outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900" : "border-white/10 bg-black/35 text-zinc-100"
}`}
>
<option value="">{t("选择设备", "Select device")}</option>
{wolDevices.map((device) => (
<option key={device.mac} value={device.mac}>
{(device.name || device.ip || device.mac) + (device.reachable ? " · online" : "")}
</option>
))}
</select>
<button
type="button"
disabled={busy === "wol:probe"}
onClick={() => {
setBusy("wol:probe");
void refreshWolDevices(true).finally(() => setBusy(null));
}}
className="inline-flex items-center justify-center rounded-lg bg-cyan-500/15 px-3 py-2 text-xs font-semibold text-cyan-100 ring-1 ring-cyan-400/25 transition hover:bg-cyan-500/25 disabled:opacity-40"
>
<RefreshCw className={`h-3.5 w-3.5 ${busy === "wol:probe" ? "animate-spin" : ""}`} />
</button>
</div>
<div className="grid gap-3 sm:grid-cols-2">
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>{t("名称", "Name")}</span>
<input
value={wolDeviceName}
onChange={(e) => setWolDeviceName(e.target.value)}
placeholder="NAS / PC"
className={`mt-1 w-full rounded-lg border px-3 py-2 text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-amber-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-amber-400/60"
}`}
/>
</label>
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>IP</span>
<input
value={wolDeviceIp}
onChange={(e) => setWolDeviceIp(e.target.value)}
placeholder="10.0.0.10"
inputMode="decimal"
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-amber-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-amber-400/60"
}`}
/>
</label>
</div>
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>MAC</span>
<input
value={wolMac}
onChange={(e) => setWolMac(e.target.value)}
placeholder="AA:BB:CC:DD:EE:FF"
autoCapitalize="characters"
spellCheck={false}
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-amber-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-amber-400/60"
}`}
/>
</label>
<div className="grid gap-3 sm:grid-cols-[minmax(0,1fr)_7rem]">
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>Broadcast</span>
<input
value={wolBroadcast}
onChange={(e) => setWolBroadcast(e.target.value)}
placeholder="255.255.255.255"
inputMode="decimal"
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-amber-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-amber-400/60"
}`}
/>
</label>
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>Port</span>
<input
value={wolPort}
onChange={(e) => setWolPort(e.target.value)}
inputMode="numeric"
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-amber-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-amber-400/60"
}`}
/>
</label>
</div>
<button
type="button"
disabled={busy === "wol:wake" || wolService?.available === false}
onClick={() => void sendWolWake()}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-amber-500/18 px-3 py-2.5 text-xs font-semibold text-amber-100 ring-1 ring-amber-400/30 transition hover:bg-amber-500/28 disabled:opacity-40"
>
{busy === "wol:wake" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Power className="h-3.5 w-3.5" />}
{t("唤醒", "Wake")}
</button>
<div className="grid grid-cols-2 gap-2">
<button
type="button"
disabled={busy === "wol:save"}
onClick={() => void saveWolDevice()}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-emerald-500/15 px-3 py-2 text-xs font-semibold text-emerald-100 ring-1 ring-emerald-400/25 transition hover:bg-emerald-500/25 disabled:opacity-40"
>
{busy === "wol:save" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Send className="h-3.5 w-3.5" />}
{t("保存", "Save")}
</button>
<button
type="button"
disabled={busy === "wol:delete" || !(wolSelectedMac || wolMac)}
onClick={() => void deleteWolDevice()}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-rose-500/15 px-3 py-2 text-xs font-semibold text-rose-100 ring-1 ring-rose-400/25 transition hover:bg-rose-500/25 disabled:opacity-40"
>
{busy === "wol:delete" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Trash2 className="h-3.5 w-3.5" />}
{t("删除", "Delete")}
</button>
</div>
</div>
</motion.div>
</div>
{SHOW_STUDIO_SERIAL_CONTROL ? (
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex flex-col gap-3 sm:flex-row sm:items-start sm:justify-between">
<div className="min-w-0">
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Cable className={`h-4 w-4 ${portalTheme === "light" ? "text-indigo-700" : "text-indigo-300"}`} />
{t("串口控制", "Serial control")}
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{serialPorts.length ? `${serialPorts.length} ${t("个端口", "ports")}` : t("未发现串口,可手动输入路径", "No serial port detected; path can be entered manually")}
</p>
</div>
<button
type="button"
disabled={busy === "serial:refresh"}
onClick={() => {
setBusy("serial:refresh");
void refreshSerialPorts().finally(() => setBusy(null));
}}
className={`inline-flex items-center justify-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold ring-1 transition disabled:opacity-40 ${
portalTheme === "light"
? "bg-white text-slate-700 ring-slate-200 hover:bg-slate-50"
: "bg-white/5 text-zinc-100 ring-white/10 hover:bg-white/10"
}`}
>
<RefreshCw className={`h-3.5 w-3.5 ${busy === "serial:refresh" ? "animate-spin" : ""}`} />
{t("刷新", "Refresh")}
</button>
</div>
<div className="mt-5 grid gap-3 lg:grid-cols-[minmax(0,1fr)_8rem]">
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>{t("串口", "Port")}</span>
<select
value={serialPorts.some((item) => item.path === serialPort) ? serialPort : ""}
onChange={(e) => {
if (e.target.value) setSerialPort(e.target.value);
}}
className={`mt-1 w-full rounded-lg border px-3 py-2 text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-indigo-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-indigo-400/60"
}`}
>
<option value="">{t("选择已发现端口", "Select detected port")}</option>
{serialPorts.map((item) => (
<option key={item.path} value={item.path}>
{item.label || item.path}
</option>
))}
</select>
</label>
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>{t("波特率", "Baudrate")}</span>
<input
value={serialBaudrate}
onChange={(e) => setSerialBaudrate(e.target.value)}
inputMode="numeric"
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-indigo-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-indigo-400/60"
}`}
/>
</label>
</div>
<label className="mt-3 block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>{t("手动端口", "Manual port")}</span>
<input
value={serialPort}
onChange={(e) => setSerialPort(e.target.value)}
placeholder="/dev/ttyUSB0 / /dev/ttyACM0"
spellCheck={false}
className={`mt-1 w-full rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-indigo-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-indigo-400/60"
}`}
/>
</label>
<label className="mt-3 block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>AT</span>
<textarea
value={serialCommand}
onChange={(e) => setSerialCommand(e.target.value)}
rows={3}
spellCheck={false}
className={`mt-1 min-h-24 w-full resize-y rounded-lg border px-3 py-2 font-mono text-sm outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900 focus:border-indigo-400" : "border-white/10 bg-black/35 text-zinc-100 focus:border-indigo-400/60"
}`}
/>
</label>
<div className="mt-3 flex flex-col gap-3 sm:flex-row sm:items-start">
<button
type="button"
disabled={busy === "serial:send" || !serialPort.trim()}
onClick={() => void sendSerialAtCommand()}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-indigo-500/18 px-3 py-2.5 text-xs font-semibold text-indigo-100 ring-1 ring-indigo-400/30 transition hover:bg-indigo-500/28 disabled:opacity-40"
>
{busy === "serial:send" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Send className="h-3.5 w-3.5" />}
{t("发送", "Send")}
</button>
<pre
className={`min-h-16 flex-1 overflow-auto whitespace-pre-wrap break-words rounded-lg border px-3 py-2 font-mono text-xs ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-700" : "border-white/10 bg-black/35 text-zinc-200"
}`}
>
{serialResponse || t("等待响应", "Waiting for response")}
</pre>
</div>
</motion.div>
) : null}
<div className="grid gap-4 xl:grid-cols-4">
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<ShieldCheck className={`h-4 w-4 ${portalTheme === "light" ? "text-emerald-700" : "text-emerald-300"}`} />
System Doctor
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{studioOps?.doctor?.services_running ?? 0}/{studioOps?.doctor?.services_available ?? 0} services
</p>
</div>
<span className={`rounded-full px-2.5 py-1 text-[10px] font-semibold ${statusPill(studioOps?.doctor?.status || "unknown")}`}>
{studioOps?.doctor?.score ?? 0}/100
</span>
</div>
<div className={`mt-4 space-y-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
<p>{t("严重", "Critical")}: {studioOps?.doctor?.critical ?? 0} / {t("警告", "Warnings")}: {studioOps?.doctor?.warnings ?? 0}</p>
{(studioOps?.doctor?.recommendations || []).slice(0, 2).map((item) => (
<p key={item} className="line-clamp-2">- {item}</p>
))}
</div>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<HardDrive className={`h-4 w-4 ${portalTheme === "light" ? "text-cyan-700" : "text-cyan-300"}`} />
{t("设备资产", "Device inventory")}
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
LAN / USB
</p>
</div>
<button
type="button"
disabled={busy === "studio:ops"}
onClick={() => {
setBusy("studio:ops");
void refreshStudioOps(true).finally(() => setBusy(null));
}}
className={`inline-flex items-center justify-center rounded-lg px-2.5 py-2 text-xs font-semibold ring-1 transition disabled:opacity-40 ${
portalTheme === "light" ? "bg-white text-slate-700 ring-slate-200 hover:bg-slate-50" : "bg-white/5 text-zinc-100 ring-white/10 hover:bg-white/10"
}`}
>
<RefreshCw className={`h-3.5 w-3.5 ${busy === "studio:ops" ? "animate-spin" : ""}`} />
</button>
</div>
<div className="mt-4 grid grid-cols-2 gap-2 text-center text-xs">
{[
["WOL", studioOps?.inventory?.counts?.wol ?? 0],
["Video", studioOps?.inventory?.counts?.video ?? 0],
].map(([label, value]) => (
<div key={label} className={`rounded-lg border px-2 py-2 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<p className={`font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>{value}</p>
<p className={portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}>{label}</p>
</div>
))}
</div>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Sparkles className={`h-4 w-4 ${portalTheme === "light" ? "text-amber-700" : "text-amber-300"}`} />
{t("自动化配方", "Automation recipes")}
</h3>
<div className="mt-4 space-y-2">
{(studioOps?.recipes || []).slice(0, 3).map((recipe) => (
<div key={recipe.id || recipe.title} className={`rounded-lg border px-3 py-2 text-xs ${portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-700" : "border-white/10 bg-black/30 text-zinc-300"}`}>
<div className="flex items-center justify-between gap-2">
<span className="line-clamp-1 font-semibold">{recipe.title}</span>
<span className={recipe.status === "ready" ? "text-emerald-400" : "text-amber-300"}>{recipe.status}</span>
</div>
</div>
))}
</div>
</motion.div>
<motion.div
initial={{ opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
className={`rounded-2xl border p-5 shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="flex items-start justify-between gap-3">
<div>
<h3 className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Server className={`h-4 w-4 ${portalTheme === "light" ? "text-violet-700" : "text-violet-300"}`} />
{t("备份快照", "Backup snapshots")}
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{(studioOps?.backups?.snapshots || []).length} snapshots
</p>
</div>
<button
type="button"
disabled={busy === "studio:snapshot"}
onClick={() => void createStudioSnapshot()}
className="inline-flex items-center justify-center gap-2 rounded-lg bg-violet-500/15 px-3 py-2 text-xs font-semibold text-violet-100 ring-1 ring-violet-400/25 transition hover:bg-violet-500/25 disabled:opacity-40"
>
{busy === "studio:snapshot" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileUp className="h-3.5 w-3.5" />}
{t("创建", "Create")}
</button>
</div>
<p className={`mt-4 line-clamp-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{(studioOps?.backups?.snapshots || [])[0]?.name || t("暂无快照", "No snapshots yet")}
</p>
</motion.div>
</div>
</div>
) : null}
{view === "network" ? (
<div className="mx-auto max-w-7xl space-y-6">
<div
className={`rounded-2xl border p-6 shadow-xl ${
portalTheme === "light"
? "border-cyan-200/90 bg-white shadow-cyan-100/50"
: "border-cyan-500/20 bg-zinc-950/55 shadow-black/30"
}`}
>
<div className="flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between">
<div>
<h3
className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}
>
<ShieldCheck className={`h-4 w-4 ${portalTheme === "light" ? "text-cyan-700" : "text-cyan-300"}`} />
WireGuard VPS
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t("导入 VPS wg-quick 配置,保存到受管配置目录,并生成 Windows 端点旁路路由命令。", "Import a VPS wg-quick config, save it under managed config, and generate the Windows endpoint bypass route.")}
</p>
</div>
<div className="flex flex-wrap items-center gap-2">
<span className={`rounded-full px-3 py-1 text-[11px] font-semibold ${wgStatus?.active ? "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-400/25" : "bg-amber-500/15 text-amber-200 ring-1 ring-amber-400/25"}`}>
{wireGuardQualityLabel(wgStatus?.quality?.status, t)}
{typeof wgStatus?.quality?.score === "number" ? ` · ${wgStatus.quality.score}/100` : ""}
</span>
{wgImportResult?.relative_path ? (
<div className={`rounded-lg border px-3 py-2 text-[11px] ${portalTheme === "light" ? "border-cyan-200 bg-cyan-50 text-cyan-900" : "border-cyan-400/20 bg-cyan-500/10 text-cyan-100"}`}>
{wgImportResult.relative_path}
</div>
) : null}
<button
onClick={() => {
void refreshWireGuardStatus();
void refreshSystemNetworkProbe();
}}
disabled={busy === "wg:status" || systemNetworkProbeLoading}
className={`inline-flex items-center gap-2 rounded-lg px-3 py-2 text-xs font-semibold ring-1 transition disabled:opacity-40 ${
portalTheme === "light"
? "bg-white text-slate-700 ring-slate-200 hover:bg-slate-50"
: "bg-white/5 text-zinc-100 ring-white/10 hover:bg-white/10"
}`}
>
<RefreshCw className={`h-3.5 w-3.5 ${systemNetworkProbeLoading ? "animate-spin" : ""}`} />
{systemNetworkProbeLoading ? t("探测中", "Probing") : t("刷新", "Refresh")}
</button>
</div>
</div>
<div className="mt-5 grid gap-3 lg:grid-cols-2 xl:grid-cols-4">
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("当前接口", "Active interfaces")}
</p>
<div className={`mt-2 rounded-lg border px-3 py-2 text-xs ${portalTheme === "light" ? "border-cyan-100 bg-white text-slate-700" : "border-cyan-400/15 bg-cyan-500/10 text-cyan-100"}`}>
<div className="flex items-center justify-between gap-2">
<span className="font-semibold">{wireGuardQualityLabel(wgStatus?.quality?.status, t)}</span>
<span className="font-mono">{typeof wgStatus?.quality?.score === "number" ? `${wgStatus.quality.score}/100` : "—"}</span>
</div>
<p className={`mt-1 text-[11px] ${portalTheme === "light" ? "text-slate-500" : "text-cyan-100/75"}`}>
{t("新鲜握手", "Fresh peers")}: {wgStatus?.quality?.fresh_peer_count ?? 0}/{wgStatus?.quality?.peer_count ?? 0}
{" · "}
{t("最佳握手", "Best handshake")}: {formatDurationSeconds(wgStatus?.quality?.best_handshake_age_seconds)}
</p>
</div>
<div className="mt-2 space-y-2">
{(wgStatus?.interfaces || []).length ? (
(wgStatus?.interfaces || []).map((iface) => (
<div key={iface.name || "wg"} className={`rounded-lg border px-3 py-2 text-xs ${portalTheme === "light" ? "border-slate-200 bg-white text-slate-700" : "border-white/10 bg-zinc-950/60 text-zinc-200"}`}>
<div className="flex items-center justify-between gap-2">
<span className="font-semibold">{iface.name || "wg"}</span>
<span className={iface.systemd?.active === "active" ? "text-emerald-400" : "text-amber-300"}>{iface.systemd?.active || "active"}</span>
</div>
<p className="mt-1 font-mono text-[11px]">{(iface.addresses || []).join(", ") || "—"}</p>
<p className={`mt-1 text-[11px] ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{iface.details_available ? t("运行细节可读", "Runtime details readable") : t("运行细节受限", "Runtime details limited")}
{iface.configured_from?.name ? ` · ${t("配置", "Config")}: ${iface.configured_from.name}` : ""}
</p>
</div>
))
) : (
<p className={`text-xs ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("未发现 wg show 输出", "No wg show output")}
</p>
)}
</div>
</div>
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("对端与流量", "Peer and traffic")}
</p>
{(() => {
const peer = wgDisplayPeer;
const sourceLabel =
peer?.status_source === "wg"
? t("运行态", "Runtime")
: peer?.config_source === "system"
? t("系统配置", "System config")
: peer?.config_source === "repo"
? t("受管配置", "Managed config")
: t("配置态", "Config");
return peer ? (
<div className={`mt-2 space-y-1 font-mono text-[11px] ${portalTheme === "light" ? "text-slate-700" : "text-zinc-300"}`}>
<p>Source: {sourceLabel}</p>
<p>Endpoint: {peer.endpoint || "—"}</p>
<p>AllowedIPs: {(peer.allowed_ips || []).join(", ") || "—"}</p>
<p>
Handshake:{" "}
{peer.status_source === "config"
? t("运行态需 root/CAP_NET_ADMIN", "Runtime details need root/CAP_NET_ADMIN")
: formatDurationSeconds(peer.latest_handshake_age_seconds)}
</p>
<p>RX/TX: {formatBytes(peer.transfer_rx_bytes)} / {formatBytes(peer.transfer_tx_bytes)}</p>
<p>Keepalive: {peer.persistent_keepalive ?? "—"}</p>
</div>
) : (
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("暂无 peer 数据", "No peer data yet")}
</p>
);
})()}
{(wgStatus?.endpoint_routes || []).length ? (
<div className={`mt-3 space-y-1 rounded-lg border px-3 py-2 font-mono text-[10px] ${portalTheme === "light" ? "border-slate-200 bg-white text-slate-600" : "border-white/10 bg-zinc-950/60 text-zinc-400"}`}>
{(wgStatus?.endpoint_routes || []).slice(0, 2).map((route) => (
<p key={route.host || route.route || "endpoint-route"} className={route.uses_wireguard_interface ? "text-amber-300" : ""}>
route {route.host || "endpoint"}: {route.route || (route.ok ? "ok" : "unavailable")}
</p>
))}
</div>
) : null}
</div>
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("Neko 访问模式", "Neko access mode")}
</p>
<div className={`mt-2 grid grid-cols-2 rounded-lg p-1 text-xs font-semibold ${portalTheme === "light" ? "bg-slate-200/70" : "bg-black/40"}`}>
{(["lan", "remote"] as const).map((mode) => {
const active = (wgStatus?.neko_access?.mode || "lan") === mode;
const disabled = busy?.startsWith("wg:neko") || (mode === "remote" && !wgStatus?.neko_access?.remote_ready);
return (
<button
key={mode}
onClick={() => void setWireGuardNekoAccessMode(mode)}
disabled={disabled}
className={`rounded-md px-2.5 py-1.5 transition disabled:opacity-40 ${
active
? portalTheme === "light"
? "bg-white text-cyan-800 shadow-sm"
: "bg-cyan-500/25 text-cyan-100 ring-1 ring-cyan-400/25"
: portalTheme === "light"
? "text-slate-600 hover:bg-white/60"
: "text-zinc-300 hover:bg-white/10"
}`}
>
{mode === "lan" ? t("局域网", "LAN") : t("远控", "Remote")}
</button>
);
})}
</div>
<div className={`mt-2 space-y-1 font-mono text-[11px] ${portalTheme === "light" ? "text-slate-700" : "text-zinc-300"}`}>
<p>NAT1TO1: {wgStatus?.neko_access?.nat1to1 || "-"}</p>
<p>LAN: {wgStatus?.neko_access?.lan_host || "-"}</p>
<p>WG: {wgStatus?.neko_access?.wireguard_host || "-"}</p>
<p>Target: {wgStatus?.neko_access?.target_nat1to1 || "-"}</p>
<p>ShellCrash: {wgStatus?.shellcrash?.running ? `running:${wgStatus?.shellcrash?.mixed_port || "7890"}` : "stopped"}</p>
</div>
{(wgStatus?.neko_access?.remote_urls || []).length ? (
<div className="mt-3 flex flex-wrap gap-2">
{(wgStatus?.neko_access?.remote_urls || []).slice(0, 4).map((item) => (
<a
key={`${item.kind || "remote"}-${item.id || 0}-${item.url || ""}`}
href={item.url}
target="_blank"
rel="noreferrer"
className={`rounded-lg px-2.5 py-1.5 text-[11px] font-semibold ring-1 transition ${
portalTheme === "light"
? "bg-white text-cyan-800 ring-cyan-100 hover:bg-cyan-50"
: "bg-cyan-500/10 text-cyan-100 ring-cyan-400/20 hover:bg-cyan-500/15"
}`}
>
Neko {item.id || 1} · {item.kind || "remote"}
</a>
))}
</div>
) : null}
</div>
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<p className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
Google / Douyin
</p>
<div className="mt-2 space-y-2">
{(["google", "youtube", "douyin"] as const).map((target) => {
const item = (systemNetworkProbe?.direct || []).find((row) => row.target === target);
const ok = Boolean(item?.ok);
const pending = !item;
const probing = systemNetworkProbeLoading && pending;
const targetLabel = item?.label || (target === "google" ? "Google" : target === "youtube" ? "YouTube" : "Douyin");
return (
<div
key={target}
className={`rounded-lg border px-3 py-2 text-xs ${
portalTheme === "light" ? "border-slate-200 bg-white text-slate-700" : "border-white/10 bg-zinc-950/60 text-zinc-200"
}`}
>
<div className="flex items-center justify-between gap-2">
<span className="font-semibold">{targetLabel}</span>
<span
className={`inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-semibold ${
probing
? "bg-cyan-500/15 text-cyan-100 ring-1 ring-cyan-500/25"
: pending
? "bg-zinc-500/15 text-zinc-300 ring-1 ring-zinc-500/25"
: ok
? "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-500/25"
: "bg-rose-500/15 text-rose-200 ring-1 ring-rose-500/25"
}`}
>
{probing ? <Loader2 className="h-3 w-3 animate-spin" /> : null}
{probing ? t("探测中", "Probing") : pending ? t("等待结果", "Waiting") : ok ? "OK" : "FAIL"}
</span>
</div>
<p className={`mt-1 font-mono text-[10px] ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{item?.elapsed_ms != null
? `${item.elapsed_ms} ms`
: probing
? t(`正在连接 ${targetLabel}...`, `Connecting ${targetLabel}...`)
: t("等待探测结果", "Waiting for probe result")}
{item?.status ? ` · HTTP ${item.status}` : ""}
</p>
{!ok && item?.error ? (
<p className="mt-1 line-clamp-2 text-[10px] text-amber-200/80">{item.error}</p>
) : null}
</div>
);
})}
</div>
<div className={`mt-3 space-y-1 font-mono text-[11px] ${portalTheme === "light" ? "text-slate-700" : "text-zinc-300"}`}>
<p>Mode: {systemNetworkProbeLoading ? t("正在探测直连链路与代理链路", "Probing direct/proxy paths") : systemNetworkProbe?.mode || "-"}</p>
<p>ShellCrash: {systemNetworkProbe?.shellcrash?.running ? `running:${systemNetworkProbe?.shellcrash?.mixed_port || "7890"}` : "manual/stopped"}</p>
<p>Autostart: {systemNetworkProbe?.shellcrash_policy?.autostart_on_direct_fail ? "on direct fail" : "off"}</p>
<p>Neko attach: {systemNetworkProbe?.shellcrash_policy?.attach_neko || "auto"}</p>
</div>
{systemNetworkProbeLoading ? (
<p className={`mt-3 inline-flex items-center gap-2 text-xs ${portalTheme === "light" ? "text-cyan-700" : "text-cyan-200"}`}>
<Loader2 className="h-3.5 w-3.5 animate-spin" />
{t("正在探测 Google / YouTube / Douyin,请等待结果返回。", "Probing Google / YouTube / Douyin. Waiting for results.")}
</p>
) : systemNetworkProbe?.summary ? (
<p className={`mt-3 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-500"}`}>{systemNetworkProbe.summary}</p>
) : null}
</div>
</div>
{wgStatus?.recommendations?.length ? (
<div className={`mt-3 rounded-xl border px-4 py-3 text-xs ${portalTheme === "light" ? "border-amber-200 bg-amber-50 text-amber-800" : "border-amber-400/20 bg-amber-500/10 text-amber-100"}`}>
{(wgStatus.recommendations || []).join(" · ")}
</div>
) : null}
{wgStatus?.quality?.reasons?.length ? (
<div className={`mt-3 rounded-xl border px-4 py-3 text-xs ${portalTheme === "light" ? "border-slate-200 bg-white text-slate-700" : "border-white/10 bg-black/25 text-zinc-300"}`}>
{(wgStatus.quality.reasons || []).slice(0, 4).join(" · ")}
</div>
) : null}
<div className="mt-5 grid gap-4 lg:grid-cols-[minmax(0,1fr)_22rem]">
<div className="space-y-3">
<div className="grid gap-3 sm:grid-cols-[14rem_minmax(0,1fr)]">
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t("配置名", "Config name")}
</span>
<input
value={wgConfigName}
onChange={(e) => setWgConfigName(e.target.value)}
className={`mt-1 w-full rounded-lg border px-3 py-2 text-sm outline-none ${
portalTheme === "light"
? "border-slate-200 bg-white text-slate-900 focus:border-cyan-400"
: "border-white/10 bg-black/30 text-zinc-100 focus:border-cyan-400/60"
}`}
/>
</label>
<label className="block">
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t("配置文件", "Config file")}
</span>
<input
type="file"
accept=".conf,.txt,text/plain"
onChange={(e) => void readWireGuardFile(e.target.files?.[0])}
className={`mt-1 w-full rounded-lg border px-3 py-2 text-xs file:mr-3 file:rounded-md file:border-0 file:px-3 file:py-1.5 file:text-xs file:font-semibold ${
portalTheme === "light"
? "border-slate-200 bg-white text-slate-700 file:bg-cyan-50 file:text-cyan-800"
: "border-white/10 bg-black/30 text-zinc-300 file:bg-cyan-500/15 file:text-cyan-100"
}`}
/>
</label>
</div>
<div className={`flex flex-wrap items-center gap-2 rounded-xl border px-3 py-2 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/25"}`}>
<span className={`text-[11px] font-medium ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t("保存模式", "Save mode")}
</span>
{(["overlay", "preserve"] as const).map((mode) => (
<button
key={mode}
onClick={() => setWgRouteMode(mode)}
className={`rounded-md px-2.5 py-1 text-[11px] font-semibold transition ${
wgRouteMode === mode
? "bg-cyan-500/20 text-cyan-100 ring-1 ring-cyan-400/30"
: portalTheme === "light"
? "bg-white text-slate-600 ring-1 ring-slate-200 hover:bg-slate-100"
: "bg-white/5 text-zinc-300 ring-1 ring-white/10 hover:bg-white/10"
}`}
>
{mode === "overlay" ? t("组网不接管默认路由", "Overlay only") : t("保留原路由", "Preserve routes")}
</button>
))}
<button
onClick={() => setWgEditing((v) => !v)}
className={`ml-auto inline-flex items-center gap-2 rounded-lg px-3 py-1.5 text-xs font-semibold ring-1 transition ${
portalTheme === "light" ? "bg-white text-slate-700 ring-slate-200 hover:bg-slate-50" : "bg-white/5 text-zinc-100 ring-white/10 hover:bg-white/10"
}`}
>
{wgEditing ? t("锁定", "Lock") : t("编辑", "Edit")}
</button>
<button
onClick={() => void saveWireGuardConfig(false)}
disabled={busy === "wg:save"}
className="inline-flex items-center gap-2 rounded-lg bg-cyan-500/20 px-3 py-1.5 text-xs font-semibold text-cyan-100 ring-1 ring-cyan-400/30 transition hover:bg-cyan-500/30 disabled:opacity-40"
>
{busy === "wg:save" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileUp className="h-3.5 w-3.5" />}
{t("保存", "Save")}
</button>
<button
onClick={() => void saveWireGuardConfig(true)}
disabled={busy === "wg:apply"}
className="inline-flex items-center gap-2 rounded-lg bg-emerald-500/15 px-3 py-1.5 text-xs font-semibold text-emerald-100 ring-1 ring-emerald-400/25 transition hover:bg-emerald-500/25 disabled:opacity-40"
>
{busy === "wg:apply" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CirclePlay className="h-3.5 w-3.5" />}
{t("保存并应用", "Save & apply")}
</button>
</div>
<textarea
value={wgConfigText}
onChange={(e) => setWgConfigText(e.target.value)}
readOnly={!wgEditing}
spellCheck={false}
placeholder="[Interface]&#10;Address = 10.88.0.6/32&#10;PrivateKey = ...&#10;&#10;[Peer]&#10;Endpoint = 129.204.21.129:51820&#10;AllowedIPs = 10.88.0.0/24"
className={`min-h-56 w-full resize-y rounded-xl border p-3 font-mono text-xs leading-relaxed outline-none ${
portalTheme === "light"
? "border-slate-200 bg-slate-50 text-slate-900 focus:border-cyan-400"
: "border-white/10 bg-black/40 text-zinc-100 focus:border-cyan-400/60"
} ${wgEditing ? "" : "opacity-75"}`}
/>
<div className="flex flex-wrap gap-2">
<button
onClick={() => void importWireGuardConfig()}
disabled={busy === "wg:save"}
className="inline-flex items-center gap-2 rounded-lg bg-cyan-500/20 px-3 py-2 text-xs font-semibold text-cyan-100 ring-1 ring-cyan-400/30 transition hover:bg-cyan-500/30 disabled:opacity-40"
>
{busy === "wg:save" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <FileUp className="h-3.5 w-3.5" />}
{t("解析并保存", "Parse & save")}
</button>
{wgImportResult?.redacted_config ? (
<button
onClick={() => copyText(wgImportResult.redacted_config || "")}
className="inline-flex items-center gap-2 rounded-lg bg-zinc-500/15 px-3 py-2 text-xs font-semibold text-zinc-100 ring-1 ring-white/10 transition hover:bg-zinc-500/25"
>
<Copy className="h-3.5 w-3.5" />
{t("复制脱敏配置", "Copy redacted")}
</button>
) : null}
</div>
</div>
<div className="space-y-3">
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-slate-50" : "border-white/10 bg-black/30"}`}>
<div className="flex items-center justify-between gap-3">
<p className={`text-xs font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
{t("解析结果", "Parsed config")}
</p>
<span className={`rounded-full px-2 py-0.5 text-[10px] font-semibold ${portalTheme === "light" ? "bg-cyan-100 text-cyan-800" : "bg-cyan-500/15 text-cyan-200"}`}>
{wgImportResult?.peer_count ?? 0} peers
</span>
</div>
<div className={`mt-3 space-y-2 font-mono text-[11px] ${portalTheme === "light" ? "text-slate-700" : "text-zinc-300"}`}>
<p>Address: {(wgImportResult?.interface?.addresses || []).join(", ") || "—"}</p>
<p>Endpoint: {wgImportResult?.peers?.[0]?.endpoint || "—"}</p>
<p>AllowedIPs: {(wgImportResult?.peers?.[0]?.allowed_ips || []).join(", ") || "—"}</p>
<p>MTU: {wgImportResult?.interface?.mtu ?? "—"}</p>
</div>
{wgImportResult?.warnings?.length ? (
<ul className={`mt-3 space-y-1 text-[11px] ${portalTheme === "light" ? "text-amber-700" : "text-amber-200"}`}>
{wgImportResult.warnings.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
) : null}
</div>
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-white" : "border-white/10 bg-black/30"}`}>
<p className={`text-xs font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
{t("已保存配置", "Saved configs")}
</p>
<div className="mt-3 flex flex-wrap gap-2">
{(wgStatus?.repo_configs || []).length ? (
(wgStatus?.repo_configs || []).map((cfg) => (
<button
key={cfg.name || cfg.relative_path || "wireguard-config"}
onClick={() => void loadSavedWireGuardConfig(cfg.name)}
className={`rounded-lg px-3 py-1.5 text-[11px] font-semibold ring-1 transition ${
portalTheme === "light"
? "bg-slate-50 text-slate-700 ring-slate-200 hover:bg-slate-100"
: "bg-white/5 text-zinc-200 ring-white/10 hover:bg-white/10"
}`}
>
{cfg.name || cfg.relative_path}
</button>
))
) : (
<span className={`text-[11px] ${portalTheme === "light" ? "text-slate-500" : "text-zinc-500"}`}>
{t("暂无受管配置", "No managed configs")}
</span>
)}
</div>
</div>
<div className={`rounded-xl border p-4 ${portalTheme === "light" ? "border-slate-200 bg-white" : "border-white/10 bg-black/30"}`}>
<p className={`flex items-center gap-2 text-xs font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}>
<Route className="h-3.5 w-3.5" />
{t("Windows 端点路由", "Windows endpoint route")}
</p>
<div className="mt-3 grid gap-2 sm:grid-cols-2 lg:grid-cols-1">
<input
value={wgRouteGateway}
onChange={(e) => setWgRouteGateway(e.target.value)}
placeholder={t("网关,如 192.168.2.1", "Gateway, e.g. 192.168.2.1")}
className={`rounded-lg border px-3 py-2 text-xs outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900" : "border-white/10 bg-black/35 text-zinc-100"
}`}
/>
<input
value={wgRouteIfIndex}
onChange={(e) => setWgRouteIfIndex(e.target.value)}
placeholder={t("接口 ifIndex,如 21", "Interface ifIndex, e.g. 21")}
className={`rounded-lg border px-3 py-2 text-xs outline-none ${
portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-900" : "border-white/10 bg-black/35 text-zinc-100"
}`}
/>
</div>
<code className={`mt-3 block break-all rounded-lg border p-3 text-[11px] ${portalTheme === "light" ? "border-slate-200 bg-slate-50 text-slate-800" : "border-white/10 bg-black/40 text-zinc-200"}`}>
{wgRouteCommand || "route -p add <endpoint> mask 255.255.255.255 <gateway> metric 1 if <ifIndex>"}
</code>
<button
onClick={() => copyText(wgRouteCommand)}
disabled={!wgRouteCommand}
className="mt-3 inline-flex items-center gap-2 rounded-lg bg-emerald-500/15 px-3 py-2 text-xs font-semibold text-emerald-100 ring-1 ring-emerald-400/25 transition hover:bg-emerald-500/25 disabled:opacity-40"
>
<Copy className="h-3.5 w-3.5" />
{t("复制命令", "Copy command")}
</button>
</div>
</div>
</div>
</div>
<div
className={`rounded-2xl border p-6 ${
portalTheme === "light"
? "border-violet-200/90 bg-gradient-to-br from-violet-50 via-white to-fuchsia-50/80"
: "border-violet-500/25 bg-gradient-to-br from-violet-500/10 via-zinc-950/40 to-fuchsia-500/5"
}`}
>
<h3
className={`flex items-center gap-2 text-sm font-semibold ${portalTheme === "light" ? "text-slate-900" : "text-white"}`}
>
<Wifi className={`h-4 w-4 ${portalTheme === "light" ? "text-violet-600" : "text-violet-300"}`} />
{t("ShellCrash 网络面板", "ShellCrash panel")}
</h3>
<p className={`mt-2 text-xs ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t(
"透明代理与规则分流直接在本页完成,无需跳转;流媒体与其它系统服务请在「服务」页管理。",
"Proxy rules and YAML editing are embedded here. Use Services for SRS/Neko/Chromium, etc.",
)}
</p>
<div className="mt-6 flex flex-col items-center gap-4 sm:flex-row sm:justify-center">
{[
{ tx: t("互联网", "Internet"), c: "from-cyan-400 to-blue-500" },
{ tx: "ShellCrash", c: "from-violet-500 to-fuchsia-500" },
{ tx: t("本机 / 安卓", "Host / Android"), c: "from-emerald-400 to-teal-500" },
].map((n, i) => (
<div key={n.tx} className="flex items-center gap-4">
<div
className={`flex h-16 w-28 items-center justify-center rounded-2xl bg-gradient-to-br ${n.c} text-xs font-bold text-white shadow-lg`}
>
{n.tx}
</div>
{i < 2 ? (
<ChevronRight
className={`hidden h-5 w-5 sm:block ${portalTheme === "light" ? "text-slate-400" : "text-zinc-600"}`}
/>
) : null}
</div>
))}
</div>
</div>
<div
className={`overflow-hidden rounded-2xl border shadow-xl ${
portalTheme === "light" ? "border-slate-200/90 bg-white shadow-slate-200/40" : "border-white/[0.08] bg-zinc-950/50 shadow-black/30"
}`}
>
<div className="max-h-[min(78vh,56rem)] min-h-[22rem] overflow-y-auto overflow-x-hidden">
<LiveConsoleWorkspace embeddedShellCrash portalLang={lang} />
</div>
</div>
</div>
) : null}
{view === "settings" ? (
<div className="mx-auto max-w-lg space-y-6">
<p className={`text-sm ${portalTheme === "light" ? "text-slate-600" : "text-zinc-400"}`}>
{t("常用选项(本机偏好);完整文件与 JSON 编辑见下方链接。", "Local preferences; full file/JSON editor via the link below.")}
</p>
<div className="space-y-4 rounded-2xl border border-white/[0.08] bg-zinc-950/50 p-5">
<label className="flex cursor-pointer items-center justify-between gap-4">
<div>
<p className="text-sm font-medium text-white">{t("总览自动刷新", "Auto-refresh dashboard")}</p>
<p className="text-[11px] text-zinc-500">10s</p>
</div>
<input
type="checkbox"
className="h-5 w-5 accent-violet-500"
checked={autoRefreshEnabled}
onChange={(e) => {
const on = e.target.checked;
setAutoRefreshEnabled(on);
try {
localStorage.setItem("livehub.autorefresh", on ? "1" : "0");
} catch {
/* ignore */
}
notify(on ? t("已开启刷新", "Auto refresh on") : t("已暂停刷新", "Paused"));
}}
/>
</label>
<label className="flex cursor-pointer items-center justify-between gap-4 border-t border-white/[0.06] pt-4">
<div>
<p className="text-sm font-medium text-white">{t("总览显示 SRS / Neko 探针", "Show SRS/Neko probes")}</p>
<p className="text-[11px] text-zinc-500">{t("关闭可精简首页", "Hide stream probe cards")}</p>
</div>
<input
type="checkbox"
className="h-5 w-5 accent-violet-500"
checked={showStreamProbes}
onChange={(e) => {
const on = e.target.checked;
setShowStreamProbes(on);
try {
localStorage.setItem("livehub.showStreamProbes", on ? "1" : "0");
} catch {
/* ignore */
}
}}
/>
</label>
</div>
<div className="rounded-2xl border border-white/[0.08] bg-zinc-950/40 p-5">
<p className="text-xs font-semibold uppercase tracking-wider text-zinc-500">{t("配置快照", "Config snapshot")}</p>
<p className="mt-2 font-mono text-[11px] text-zinc-400">
{String((hubCfgSnapshot as { config_root?: string })?.config_root || "—")}
</p>
<p className="mt-3 text-sm text-zinc-300">
{t("主机名", "Hostname")}:{" "}
<span className="font-mono text-violet-200">
{(() => {
const sys = hubCfgSnapshot?.system as { identity?: { hostname_alias?: string } } | undefined;
const a = sys?.identity?.hostname_alias?.trim();
if (a) return a;
const h = dash?.stack?.mdns_host || "";
return h.replace(/\.local$/i, "") || "—";
})()}
</span>
</p>
<div className="mt-4 flex flex-wrap gap-2">
{(hubCfgSnapshot?.services as Array<{ id?: string; enabled?: boolean }> | undefined)?.slice(0, 8).map((svc) => (
<span
key={svc.id}
className={`rounded-full px-2.5 py-1 text-[10px] font-medium ${
svc.enabled ? "bg-emerald-500/15 text-emerald-200 ring-1 ring-emerald-500/25" : "bg-zinc-500/15 text-zinc-400"
}`}
>
{svc.id} {svc.enabled ? "ON" : "off"}
</span>
))}
</div>
</div>
<a
href="/console?tab=config"
className={`inline-flex w-full items-center justify-center gap-2 rounded-xl border py-3 text-sm transition ${
portalTheme === "light"
? "border-slate-200 bg-slate-50 text-violet-700 hover:bg-slate-100"
: "border-white/10 bg-white/[0.05] text-violet-200 hover:bg-white/[0.08]"
}`}
>
{t("完整配置中心(文件 / JSON)", "Full config center (files / JSON)")}
<ArrowUpRight className="h-4 w-4" />
</a>
</div>
) : null}
</motion.div>
</AnimatePresence>
</main>
</div>
</div>
{/* Mobile drawer */}
<AnimatePresence>
{mobileNav ? (
<motion.div
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
className="fixed inset-0 z-50 bg-black/60 backdrop-blur-sm lg:hidden"
onClick={() => setMobileNav(false)}
>
<motion.aside
initial={{ x: -280 }}
animate={{ x: 0 }}
exit={{ x: -280 }}
transition={{ type: "spring", damping: 28, stiffness: 320 }}
className="absolute left-0 top-0 h-full w-[min(88vw,280px)] border-r border-white/10 bg-zinc-950 p-4 shadow-2xl"
onClick={(e) => e.stopPropagation()}
>
<div className="flex justify-end">
<button type="button" onClick={() => setMobileNav(false)} className="rounded-lg p-2">
<X className="h-5 w-5" />
</button>
</div>
<nav className="mt-4 flex flex-col gap-1">
{navItems.map((item) => {
const Icon = item.icon;
const active = view === item.id;
return (
<button
key={item.id}
type="button"
onClick={() => {
setView(item.id);
setMobileNav(false);
}}
aria-current={active ? "page" : undefined}
className={`flex items-center gap-3 rounded-xl px-3 py-3 text-left text-sm transition ${
active ? "bg-white/[0.08] text-white shadow-inner shadow-white/5" : "text-zinc-300 hover:bg-white/[0.04]"
}`}
>
<Icon className={`h-4 w-4 ${active ? "text-violet-300" : "text-violet-400"}`} />
{t(item.labelZh, item.labelEn)}
</button>
);
})}
</nav>
</motion.aside>
</motion.div>
) : null}
</AnimatePresence>
</div>
);
}