diff --git a/README.md b/README.md index db547da..61e2957 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ - 登记已有的 Conda 或 `.venv` Python 解释器、脚本、工作目录、启动参数和环境变量。 - 通过应用卡片启动、停止、重启服务,并读取状态、PID 和 journal 日志。 -- 后端内置本机资源采集,监控 CPU、内存、磁盘、NVIDIA GPU、网络、温度与运行时间;不依赖 Nezha Agent 或远程监控 API。 +- 后端内置本机资源采集,监控 CPU、内存、磁盘、NVIDIA GPU、网络、温度与运行时间;完全自治,不依赖任何远程监控服务。 - 每个应用有独立的 systemd user unit;面板 API 重启后,服务状态仍由 systemd 托管。 - 前端只发送结构化配置和固定操作;后端不接受任意 shell 命令。 @@ -37,7 +37,7 @@ journalctl --user -u compute-service-manager -f 管理密钥保存在 `~/.config/compute-service-manager/manager.env`,权限为 `600`。首次打开面板后,在「设置」页填入部署时显示的密钥。服务进程读取该文件,前端构建产物由后端同源提供。 -资源监控直接运行在本机后端:CPU、内存、磁盘和网络由 `psutil` 读取;NVIDIA GPU 指标在本机存在 `nvidia-smi` 时自动采集,其余 GPU 或不可用的传感器显示为空。指标字段参考 Nezha 的 [`Host` / `HostState`](https://github.com/nezhahq/nezha/blob/master/model/host.go) 语义,采集和展示均由本项目负责,无需部署 Nezha Agent 或配置 Nezha API。 +资源监控直接运行在本机后端:CPU、内存、磁盘和网络由 `psutil` 读取;NVIDIA GPU 指标在本机存在 `nvidia-smi` 时自动采集,其余 GPU 或不可用的传感器显示为空。采集和展示均由本项目负责,无任何外部监控依赖。 如需手动配置 systemd、Nginx,可继续参考 `deploy/compute-service-manager.service.example` 和 `deploy/nginx.conf.example`。 diff --git a/backend/.env.example b/backend/.env.example index da4f6d6..3505e82 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -11,9 +11,3 @@ DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus # Comma-separated browser origins allowed to call the API. PANEL_CORS_ORIGINS=http://localhost:5173 -# Optional Nezha V2 monitor source. Use a read-only PAT with -# nezha:inventory:read and restrict it to the target server ID when possible. -NEZHA_URL=https://nezha.example.com -NEZHA_TOKEN=nzp_replace-with-read-only-token -NEZHA_SERVER_ID=1 - diff --git a/backend/app/main.py b/backend/app/main.py index b85b03a..4391db9 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -3,18 +3,13 @@ from __future__ import annotations import asyncio -import csv import hmac import json import os -import platform import re import shlex -import shutil import sqlite3 -import socket import subprocess -import time import uuid from contextlib import asynccontextmanager from datetime import datetime, timezone @@ -28,6 +23,8 @@ from fastapi.responses import FileResponse from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field, field_validator +from .metrics import LocalSystemMonitor + BASE_DIR = Path(__file__).resolve().parents[1] DATABASE_PATH = Path(os.getenv("PANEL_DATABASE_PATH", str(Path.home() / ".local" / "share" / "compute-service-manager" / "panel.db"))) @@ -89,6 +86,7 @@ class AppRecord(AppInput): id: str status: Literal["running", "stopped", "failed", "unknown"] = "stopped" pid: int | None = None + ports: list[int] = Field(default_factory=list) active_since: str | None = None created_at: str updated_at: str @@ -102,162 +100,6 @@ def utc_now() -> str: return datetime.now(timezone.utc).isoformat() -class LocalSystemMonitor: - """Collect host metrics in-process using local OS counters, not a remote monitor API.""" - - def __init__(self) -> None: - self.latest: dict[str, Any] | None = None - self.error: str | None = None - self._last_network = psutil.net_io_counters() - self._last_network_at = time.monotonic() - - @staticmethod - def _cpu_names() -> list[str]: - name = platform.processor().strip() - if not name and Path("/proc/cpuinfo").exists(): - try: - for line in Path("/proc/cpuinfo").read_text(errors="replace").splitlines(): - if line.lower().startswith(("model name", "hardware")) and ":" in line: - name = line.split(":", 1)[1].strip() - if name: - break - except OSError: - pass - return [name or platform.machine() or "CPU"] - - @staticmethod - def _gpu_metrics() -> tuple[list[str], list[dict[str, Any]]]: - """Read NVIDIA telemetry when the vendor utility is installed; other GPUs stay empty.""" - command = shutil.which("nvidia-smi") - if not command: - return [], [] - try: - result = subprocess.run( - [command, "--query-gpu=index,name,utilization.gpu,memory.used,memory.total", "--format=csv,noheader,nounits"], - check=False, - capture_output=True, - text=True, - encoding="utf-8", - errors="replace", - timeout=3, - ) - except (OSError, subprocess.TimeoutExpired): - return [], [] - if result.returncode != 0: - return [], [] - names: list[str] = [] - gpus: list[dict[str, Any]] = [] - for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True): - if len(row) < 5: - continue - try: - index = int(row[0].strip()) - utilization = float(row[2].strip()) - memory_used = float(row[3].strip()) - memory_total = float(row[4].strip()) - except ValueError: - continue - name = row[1].strip() - names.append(name) - gpus.append({ - "index": index, - "name": name, - "utilization": utilization, - "memory_used_mb": memory_used, - "memory_total_mb": memory_total, - }) - return names, gpus - - def collect(self) -> dict[str, Any]: - """Build a Nezha-shaped local snapshot so the existing dashboard can render it.""" - # A short blocking sample is safe here because collect() runs in a worker thread. - cpu_percent = psutil.cpu_percent(interval=0.25) - captured_at = datetime.now(timezone.utc) - memory = psutil.virtual_memory() - disk_path = Path.home().anchor or os.path.abspath(os.sep) - disk = psutil.disk_usage(disk_path) - network = psutil.net_io_counters() - now = time.monotonic() - elapsed = max(now - self._last_network_at, 0.001) - incoming = max(network.bytes_recv - self._last_network.bytes_recv, 0) - outgoing = max(network.bytes_sent - self._last_network.bytes_sent, 0) - self._last_network, self._last_network_at = network, now - cpu_names = self._cpu_names() - gpu_names, gpus = self._gpu_metrics() - try: - load_1m = os.getloadavg()[0] - except (AttributeError, OSError): - load_1m = None - try: - temperatures = [ - {"name": name, "temperature": entry.current} - for name, entries in psutil.sensors_temperatures(fahrenheit=False).items() - for entry in entries - if entry.current is not None - ] - except (AttributeError, NotImplementedError, OSError): - temperatures = [] - host_name = socket.gethostname() - uptime = max(int(time.time() - psutil.boot_time()), 0) - return { - "source": "local", - "connection_status": "connected", - "captured_at": captured_at.isoformat(), - "server": { - "id": None, - "name": host_name, - "platform": f"{platform.system()} {platform.release()}".strip(), - "cpu_names": cpu_names, - "gpu_names": gpu_names, - "uptime_seconds": uptime, - "last_active": captured_at.isoformat(), - "is_online": True, - }, - "cpu": { - "percent": cpu_percent, - "load_1m": load_1m, - "cores": psutil.cpu_count(logical=True), - "cpu_names": cpu_names, - }, - "memory": {"used_bytes": memory.used, "total_bytes": memory.total, "percent": memory.percent}, - "disk": {"path": disk_path, "used_bytes": disk.used, "total_bytes": disk.total, "percent": disk.percent}, - "gpus": gpus, - "network": {"in_bytes_per_second": incoming / elapsed, "out_bytes_per_second": outgoing / elapsed}, - "temperatures": temperatures, - "error": None, - } - - async def run(self) -> None: - """Sample outside the event loop and refresh the snapshot every five seconds.""" - while True: - try: - self.latest = await asyncio.to_thread(self.collect) - self.error = None - except asyncio.CancelledError: - raise - except Exception as exc: - self.latest = None - self.error = f"本机资源采集失败:{str(exc)[:240]}" - await asyncio.sleep(5) - - def snapshot(self) -> dict[str, Any]: - if self.latest is not None: - return dict(self.latest) - return { - "source": "local", - "connection_status": "unavailable" if self.error else "sampling", - "captured_at": None, - "server": None, - "cpu": None, - "memory": None, - "disk": None, - "gpus": [], - "network": None, - "temperatures": [], - "error": self.error, - } - - system_monitor = LocalSystemMonitor() @@ -325,6 +167,7 @@ def to_record(row: sqlite3.Row, service_state: dict[str, str] | None = None) -> status = "failed" else: status = "unknown" + main_pid = int(state["MainPID"]) if state.get("MainPID", "0").isdigit() and state["MainPID"] != "0" else None return AppRecord( id=row["id"], name=row["name"], @@ -335,13 +178,39 @@ def to_record(row: sqlite3.Row, service_state: dict[str, str] | None = None) -> args=json.loads(row["args_json"]), env=json.loads(row["env_json"]), status=status, - pid=int(state["MainPID"]) if state.get("MainPID", "0").isdigit() and state["MainPID"] != "0" else None, + pid=main_pid, + ports=read_listening_ports(main_pid), active_since=state.get("ActiveEnterTimestamp"), created_at=row["created_at"], updated_at=row["updated_at"], ) +def read_listening_ports(main_pid: int | None) -> list[int]: + """Report TCP listener ports owned by the service process tree.""" + if main_pid is None: + return [] + + try: + root = psutil.Process(main_pid) + processes = [root, *root.children(recursive=False)] + except (psutil.Error, OSError): + return [] + + # Service wrappers often launch the actual server as one child. Limit + # discovery to that first level so worker IPC sockets are not shown as ports. + ports: set[int] = set() + for process in processes: + try: + connections = process.net_connections(kind="inet") + except (psutil.Error, OSError): + continue + for connection in connections: + if connection.status == psutil.CONN_LISTEN and connection.laddr: + ports.add(connection.laddr.port) + return sorted(ports) + + def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]: command = ["systemctl", "--user", *args] try: @@ -384,7 +253,9 @@ def read_unit_state(app_id: str) -> dict[str, str]: def check_runtime(app: AppInput) -> tuple[Path, Path, Path]: - python = Path(app.python_path).expanduser().resolve() + # Keep the configured interpreter path intact: venv Python executables may + # be symlinks, and resolving one can bypass the environment's site-packages. + python = Path(os.path.abspath(Path(app.python_path).expanduser())) script = Path(app.script_path).expanduser().resolve() working_dir = Path(app.working_dir).expanduser().resolve() if not python.is_file() or not os.access(python, os.X_OK): @@ -417,10 +288,16 @@ def write_service_files(app_id: str, app: AppInput) -> None: "[Unit]", f"Description=Managed app: {app.name.replace('%', '%%')}", "After=network.target", + # Stop crash loops after five starts in five minutes; recovery then + # requires an explicit manual start from the service manager. + "StartLimitIntervalSec=5min", + "StartLimitBurst=5", "", "[Service]", "Type=simple", - f"WorkingDirectory={systemd_quote(str(working_dir))}", + # Unlike ExecStart, WorkingDirectory is a single path value; quotes + # are literal here, so escape path characters in systemd syntax. + f"WorkingDirectory={systemd_path(str(working_dir))}", f"ExecStart=/usr/bin/bash {systemd_quote(str(launcher_path))}", "Restart=on-failure", "RestartSec=5s", @@ -442,6 +319,21 @@ def systemd_quote(value: str) -> str: return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"' +def systemd_path(value: str) -> str: + """Encode a path as a systemd setting value, not as an ExecStart argument.""" + # WorkingDirectory does not use ExecStart's quote parser. Encode whitespace + # and backslashes with systemd's C-style escapes, and escape specifiers. + escaped: list[str] = [] + for char in value: + if char == "%": + escaped.append("%%") + elif char == "\\" or char.isspace() or ord(char) < 32 or ord(char) == 127: + escaped.append(f"\\x{ord(char):02x}") + else: + escaped.append(char) + return "".join(escaped) + + def save_app(app_id: str, app: AppInput) -> None: timestamp = utc_now() with connect_db() as connection: @@ -487,11 +379,13 @@ def update_app(app_id: str, app: AppInput) -> None: async def lifespan(_: FastAPI): initialize_database() monitor_task = asyncio.create_task(system_monitor.run()) + process_task = asyncio.create_task(system_monitor.run_processes()) try: yield finally: monitor_task.cancel() - await asyncio.gather(monitor_task, return_exceptions=True) + process_task.cancel() + await asyncio.gather(monitor_task, process_task, return_exceptions=True) app = FastAPI(title="Compute Service Manager API", version="0.1.0", lifespan=lifespan) @@ -521,6 +415,12 @@ def system_metrics() -> dict[str, Any]: return system_monitor.snapshot() +@app.get("/api/system/history", dependencies=[Depends(require_token)]) +def system_history(minutes: int = Query(default=10, ge=1, le=30)) -> dict[str, Any]: + """Return the rolling 1-second sample ring buffer that seeds the detail charts.""" + return {"window_seconds": minutes * 60, "samples": system_monitor.history_snapshot(minutes * 60)} + + @app.get("/api/apps", response_model=list[AppRecord], dependencies=[Depends(require_token)]) def list_apps() -> list[AppRecord]: with connect_db() as connection: diff --git a/backend/app/metrics.py b/backend/app/metrics.py new file mode 100644 index 0000000..37361fe --- /dev/null +++ b/backend/app/metrics.py @@ -0,0 +1,473 @@ +"""Local system metric collection for the compute dashboard. + +The monitor samples every two seconds so sparklines and peak badges stay +smooth, keeps a ten-minute ring buffer to seed the resource detail views, +and degrades every platform-specific source (nvidia-smi, /sys, sensors, +per-process permission) to None/[] instead of failing the whole snapshot. +""" + +from __future__ import annotations + +import asyncio +import csv +import os +import platform +import shutil +import socket +import subprocess +import time +from collections import deque +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +import psutil + +HISTORY_MAXLEN = 600 # 600 samples × 1s ≈ 10 minutes (daozai cadence: one sample per second) +PROCESS_TOP_N = 8 + +_GPU_QUERY_FIELDS = ( + "index,name,utilization.gpu,memory.used,memory.total,temperature.gpu," + "utilization.encoder,utilization.decoder,power.draw,power.limit," + "clocks.current.graphics,clocks.current.memory,uuid" +) + + +def optional_number(value: str) -> float | None: + """Parse an nvidia-smi CSV cell, treating N/A-style placeholders as missing.""" + normalized = value.strip().strip("[]").lower() + if normalized in {"", "n/a", "not supported", "-"}: + return None + try: + return float(normalized) + except ValueError: + return None + + +class LocalSystemMonitor: + """Collect host metrics in-process using local OS counters, not a remote monitor API.""" + + def __init__(self) -> None: + self.latest: dict[str, Any] | None = None + self.error: str | None = None + self.history: deque[dict[str, Any]] = deque(maxlen=HISTORY_MAXLEN) + # Process rankings refresh on a slower loop (process_iter is the only + # expensive collection pass); snapshots always read the last result. + self._processes: dict[str, list[dict[str, Any]]] = {"cpu": [], "memory": []} + self._last_network = psutil.net_io_counters() + self._last_nic = psutil.net_io_counters(pernic=True) + self._last_at = time.monotonic() + self._last_disk_io: Any | None = None + self._last_proc_io: dict[int, int] = {} + self._last_proc_at = time.monotonic() + self._link_speeds: dict[str, int | None] = {} + try: + self._last_disk_io = psutil.disk_io_counters() + except Exception: + self._last_disk_io = None + # Open the CPU diff windows once so the first real sample is meaningful. + try: + psutil.cpu_percent(None) + psutil.cpu_percent(None, percpu=True) + except Exception: + pass + + @staticmethod + def _cpu_split() -> dict[str, float | None]: + """User/kernel split matching the same window as cpu_percent.""" + try: + times = psutil.cpu_times_percent(None) + return {"user_percent": times.user, "system_percent": times.system} + except Exception: + return {"user_percent": None, "system_percent": None} + + @staticmethod + def _cpu_names() -> list[str]: + name = platform.processor().strip() + if not name and Path("/proc/cpuinfo").exists(): + try: + for line in Path("/proc/cpuinfo").read_text(errors="replace").splitlines(): + if line.lower().startswith(("model name", "hardware")) and ":" in line: + name = line.split(":", 1)[1].strip() + if name: + break + except OSError: + pass + return [name or platform.machine() or "CPU"] + + @staticmethod + def _gpu_metrics() -> tuple[list[str], list[dict[str, Any]]]: + """Read NVIDIA telemetry when the vendor utility is installed; other GPUs stay empty.""" + command = shutil.which("nvidia-smi") + if not command: + return [], [] + try: + result = subprocess.run( + [command, f"--query-gpu={_GPU_QUERY_FIELDS}", "--format=csv,noheader,nounits"], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=3, + ) + except (OSError, subprocess.TimeoutExpired): + return [], [] + if result.returncode != 0: + return [], [] + names: list[str] = [] + gpus: list[dict[str, Any]] = [] + for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True): + if len(row) < 3: + continue + try: + index = int(row[0].strip()) + except ValueError: + continue + name = row[1].strip() + if not name: + continue + + # Some integrated GPUs (including GB10) expose utilization but report + # framebuffer memory as N/A; keep the GPU row and leave only memory blank. + cell = lambda i: optional_number(row[i]) if len(row) > i else None + gpus.append({ + "index": index, + "name": name, + "utilization": cell(2), + "memory_used_mb": cell(3), + "memory_total_mb": cell(4), + "temperature_c": cell(5), + "encoder_pct": cell(6), + "decoder_pct": cell(7), + "power_w": cell(8), + "power_limit_w": cell(9), + "graphics_clock_mhz": cell(10), + "memory_clock_mhz": cell(11), + "uuid": row[12].strip() if len(row) > 12 else "", + "processes": [], + }) + LocalSystemMonitor._attach_gpu_processes(command, gpus) + return names, gpus + + @staticmethod + def _attach_gpu_processes(command: str, gpus: list[dict[str, Any]]) -> None: + """Attach CUDA process rows to their GPU entry; desktop processes stay invisible.""" + try: + result = subprocess.run( + [ + command, + "--query-compute-apps=gpu_name,pid,process_name,used_memory", + "--format=csv,noheader,nounits", + ], + check=False, + capture_output=True, + text=True, + encoding="utf-8", + errors="replace", + timeout=3, + ) + except (OSError, subprocess.TimeoutExpired): + return + if result.returncode != 0: + return + by_name = {gpu["name"]: gpu for gpu in gpus} + for row in csv.reader(result.stdout.splitlines(), skipinitialspace=True): + if len(row) < 4: + continue + gpu = by_name.get(row[0].strip()) + if gpu is None: + continue + try: + pid = int(row[1].strip()) + except ValueError: + continue + gpu["processes"].append({ + "pid": pid, + "name": row[2].strip() or f"pid {pid}", + "memory_mb": optional_number(row[3]) or 0.0, + }) + for gpu in gpus: + gpu["processes"].sort(key=lambda entry: entry["memory_mb"], reverse=True) + del gpu["processes"][PROCESS_TOP_N:] + + def _process_ranking(self) -> dict[str, list[dict[str, Any]]]: + """Top CPU, top memory and top disk-IO processes. + + The first pass primes each Process object's cpu counter (psutil caches + instances per pid, so later passes diff against it) and mainly reports + the memory ranking; the second pass reports meaningful CPU and IO rates. + """ + entries: list[dict[str, Any]] = [] + own_pid = os.getpid() + # psutil reports per-logical-core percent (a busy thread can hit 100% x cores); + # normalize to whole-machine share so the ranking sums stay under 100%. + core_count = max(1, psutil.cpu_count(logical=True) or 1) + now = time.monotonic() + elapsed = max(now - getattr(self, "_last_proc_at", now), 0.001) + self._last_proc_at = now + current_io: dict[int, int] = {} + for proc in psutil.process_iter(["pid", "name", "username", "memory_info", "io_counters"]): + try: + info = proc.info + name = info.get("name") or f"pid {info['pid']}" + # Windows' idle task and this panel itself would otherwise top the CPU chart. + if info["pid"] == own_pid or name in {"System Idle Process", "Idle"}: + continue + io = info.get("io_counters") + total_io = int(io.read_bytes + io.write_bytes) if io else 0 + current_io[info["pid"]] = total_io + last_io = self._last_proc_io.get(info["pid"]) + io_rate = max(total_io - last_io, 0) / elapsed if last_io is not None else 0 + entries.append({ + "pid": info["pid"], + "name": name, + "user": info.get("username") or "", + "cpu_percent": proc.cpu_percent(None) / core_count, + "memory_bytes": info["memory_info"].rss if info.get("memory_info") else 0, + "io_bytes_per_second": io_rate, + }) + except (psutil.Error, OSError): + continue + self._last_proc_io = current_io + by_cpu = sorted(entries, key=lambda entry: entry["cpu_percent"], reverse=True)[:PROCESS_TOP_N] + by_mem = sorted(entries, key=lambda entry: entry["memory_bytes"], reverse=True)[:PROCESS_TOP_N] + by_io = sorted(entries, key=lambda entry: entry["io_bytes_per_second"], reverse=True)[:PROCESS_TOP_N] + return {"cpu": by_cpu, "memory": by_mem, "io": by_io} + + @staticmethod + def _disk_volumes() -> list[dict[str, Any]]: + volumes: list[dict[str, Any]] = [] + try: + partitions = psutil.disk_partitions(all=False) + except Exception: + return volumes + for partition in partitions: + try: + usage = psutil.disk_usage(partition.mountpoint) + except (PermissionError, OSError): + continue + volumes.append({ + "path": partition.device, + "mountpoint": partition.mountpoint, + "fstype": partition.fstype, + "percent": usage.percent, + "used_bytes": usage.used, + "total_bytes": usage.total, + }) + volumes.sort(key=lambda volume: volume["total_bytes"], reverse=True) + return volumes + + def _link_speed_mbps(self, nic: str) -> int | None: + if nic in self._link_speeds: + return self._link_speeds[nic] + speed: int | None = None + try: + raw = Path(f"/sys/class/net/{nic}/speed").read_text().strip() + parsed = int(float(raw)) + speed = parsed if parsed > 0 else None + except (OSError, ValueError): + speed = None + self._link_speeds[nic] = speed + return speed + + def _network(self, elapsed: float) -> dict[str, Any]: + counters = psutil.net_io_counters() + incoming = max(counters.bytes_recv - self._last_network.bytes_recv, 0) / elapsed + outgoing = max(counters.bytes_sent - self._last_network.bytes_sent, 0) / elapsed + self._last_network = counters + per_nic: list[dict[str, Any]] = [] + try: + nic_counters = psutil.net_io_counters(pernic=True) + except Exception: + nic_counters = {} + for name, counters_nic in nic_counters.items(): + last = self._last_nic.get(name) + if last is not None: + rx = max(counters_nic.bytes_recv - last.bytes_recv, 0) / elapsed + tx = max(counters_nic.bytes_sent - last.bytes_sent, 0) / elapsed + per_nic.append({ + "name": name, + "rx_bps": rx, + "tx_bps": tx, + "link_mbps": self._link_speed_mbps(name), + }) + self._last_nic = nic_counters + per_nic.sort(key=lambda nic: nic["rx_bps"] + nic["tx_bps"], reverse=True) + return { + "in_bytes_per_second": incoming, + "out_bytes_per_second": outgoing, + "received_bytes_total": counters.bytes_recv, + "sent_bytes_total": counters.bytes_sent, + "per_nic": per_nic, + } + + def _disk_rates(self, elapsed: float) -> dict[str, float | None]: + try: + io = psutil.disk_io_counters() + except Exception: + io = None + rates: dict[str, float | None] = {"read_bps": None, "write_bps": None, "active_percent": None} + if io is not None: + if self._last_disk_io is not None: + rates["read_bps"] = max(io.read_bytes - self._last_disk_io.read_bytes, 0) / elapsed + rates["write_bps"] = max(io.write_bytes - self._last_disk_io.write_bytes, 0) / elapsed + busy_ms = getattr(io, "busy_time", None) + last_busy = getattr(self._last_disk_io, "busy_time", None) + if busy_ms is not None and last_busy is not None: + # busy_time counts milliseconds the device had queued IO. + rates["active_percent"] = min(100.0, max(busy_ms - last_busy, 0) / (elapsed * 1000) * 100) + self._last_disk_io = io + return rates + + def collect(self) -> dict[str, Any]: + """Build the full local snapshot consumed by the compute monitor page.""" + # Every counter here is a non-blocking diff against the previous pass; + # __init__ primed the windows, so the loop never sleeps inside collect(). + cpu_percent = psutil.cpu_percent(None) + percpu = psutil.cpu_percent(None, percpu=True) + captured_at = datetime.now(timezone.utc) + now = time.monotonic() + elapsed = max(now - self._last_at, 0.001) + self._last_at = now + memory = psutil.virtual_memory() + disk_path = Path.home().anchor or os.path.abspath(os.sep) + disk = psutil.disk_usage(disk_path) + cpu_freq = psutil.cpu_freq() + cpu_names = self._cpu_names() + gpu_names, gpus = self._gpu_metrics() + try: + load_1m = os.getloadavg()[0] + except (AttributeError, OSError): + load_1m = None + try: + temperatures = [ + {"name": name, "temperature": entry.current} + for name, entries in psutil.sensors_temperatures(fahrenheit=False).items() + for entry in entries + if entry.current is not None + ] + except (AttributeError, NotImplementedError, OSError): + temperatures = [] + host_name = socket.gethostname() + uptime = max(int(time.time() - psutil.boot_time()), 0) + network = self._network(elapsed) + disk_rates = self._disk_rates(elapsed) + return { + "source": "local", + "connection_status": "connected", + "captured_at": captured_at.isoformat(), + "server": { + "id": None, + "name": host_name, + "platform": f"{platform.system()} {platform.release()}".strip(), + "cpu_names": cpu_names, + "gpu_names": gpu_names, + "uptime_seconds": uptime, + "last_active": captured_at.isoformat(), + "is_online": True, + }, + "cpu": { + "percent": cpu_percent, + "percpu": percpu, + "frequency_mhz": cpu_freq.current if cpu_freq else None, + "load_1m": load_1m, + "cores": psutil.cpu_count(logical=True), + "cores_physical": psutil.cpu_count(logical=False), + "cpu_names": cpu_names, + **self._cpu_split(), + }, + "memory": { + "used_bytes": memory.used, + "total_bytes": memory.total, + "percent": memory.percent, + "available_bytes": memory.available, + "cached_bytes": getattr(memory, "cached", 0), + "buffered_bytes": getattr(memory, "buffers", 0), + "shared_bytes": getattr(memory, "shared", 0), + }, + "disk": { + "path": disk_path, + "used_bytes": disk.used, + "total_bytes": disk.total, + "percent": disk.percent, + **disk_rates, + }, + "disks": self._disk_volumes(), + "gpus": gpus, + "network": network, + "processes": self._processes, + "temperatures": temperatures, + "error": None, + } + + @staticmethod + def history_sample(snapshot: dict[str, Any], epoch: float) -> dict[str, Any]: + """Compact per-cycle series entry shared by the ring buffer and the detail charts.""" + gpus = snapshot.get("gpus") or [] + gpu_values = [gpu.get("utilization") for gpu in gpus if gpu.get("utilization") is not None] + cpu = snapshot.get("cpu") or {} + memory = snapshot.get("memory") or {} + disk = snapshot.get("disk") or {} + network = snapshot.get("network") or {} + return { + "t": epoch, + "cpu": cpu.get("percent"), + "percpu": cpu.get("percpu"), + "gpu": max(gpu_values) if gpu_values else None, + "mem": memory.get("percent"), + "disk_read": disk.get("read_bps"), + "disk_write": disk.get("write_bps"), + "net_in": network.get("in_bytes_per_second"), + "net_out": network.get("out_bytes_per_second"), + } + + async def run(self) -> None: + """Sample on a fixed 1-second grid like the island, skipping time already spent collecting.""" + while True: + started = time.monotonic() + try: + snapshot = await asyncio.to_thread(self.collect) + self.history.append(self.history_sample(snapshot, time.time())) + self.latest = snapshot + self.error = None + except asyncio.CancelledError: + raise + except Exception as exc: + self.latest = None + self.error = f"本机资源采集失败:{str(exc)[:240]}" + await asyncio.sleep(max(0.05, 1.0 - (time.monotonic() - started))) + + async def run_processes(self, interval: float = 6.0) -> None: + """Refresh the process ranking on its own slower loop so the 2s cycle stays cheap.""" + while True: + try: + self._processes = await asyncio.to_thread(self._process_ranking) + except asyncio.CancelledError: + raise + except Exception: + pass # keep the previous ranking; process data is best-effort + await asyncio.sleep(interval) + + def history_snapshot(self, seconds: float) -> list[dict[str, Any]]: + cutoff = time.time() - seconds + return [sample for sample in self.history if sample["t"] >= cutoff] + + def snapshot(self) -> dict[str, Any]: + if self.latest is not None: + return dict(self.latest) + return { + "source": "local", + "connection_status": "unavailable" if self.error else "sampling", + "captured_at": None, + "server": None, + "cpu": None, + "memory": None, + "disk": None, + "disks": [], + "gpus": [], + "network": None, + "processes": {"cpu": [], "memory": []}, + "temperatures": [], + "error": self.error, + } diff --git a/frontend/index.html b/frontend/index.html index 0982178..a489e13 100644 --- a/frontend/index.html +++ b/frontend/index.html @@ -6,6 +6,18 @@ ComputeOS · 算力控制中心 +
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx index fcb96fd..19136dc 100644 --- a/frontend/src/App.tsx +++ b/frontend/src/App.tsx @@ -1,5 +1,6 @@ -import { useCallback, useEffect, useMemo, useState } from "react"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import type { FormEvent, ReactNode } from "react"; +import { applyTheme, hasStoredTheme, rememberTheme, resolveTheme, type Theme } from "./theme"; import { Activity, AlertCircle, @@ -8,11 +9,10 @@ import { Cpu, FileCode2, Gauge, - HardDrive, KeyRound, ListChecks, LoaderCircle, - MemoryStick, + Moon, MoreHorizontal, Play, Plus, @@ -21,10 +21,14 @@ import { Server, Settings2, Square, + Sun, TerminalSquare, Trash2, X, } from "lucide-react"; +import { request } from "./api"; +import ComputePage, { RESOURCE_TITLES } from "./compute/ComputePage"; +import type { ResourceKey, SystemMetrics } from "./compute/types"; type AppStatus = "running" | "stopped" | "failed" | "unknown"; type ManagedApp = { @@ -38,6 +42,7 @@ type ManagedApp = { env: Record; status: AppStatus; pid: number | null; + ports?: number[]; active_since: string | null; created_at: string; updated_at: string; @@ -46,34 +51,20 @@ type AppDraft = Pick; - network: { in_bytes_per_second: number; out_bytes_per_second: number } | null; - temperatures: Array<{ name: string; temperature: number }>; - error: string | null; -}; -type MetricSample = { time: number; cpu: number; memory: number; gpu: number }; type PageKey = "compute" | "services" | "runtime" | "settings"; +type RouteState = { page: PageKey; resource: ResourceKey | null }; -function pageFromHash(): PageKey { - const page = window.location.hash.slice(1); - return page === "compute" || page === "runtime" || page === "services" || page === "settings" ? page : "compute"; +const PAGE_KEYS: PageKey[] = ["compute", "runtime", "services", "settings"]; +const RESOURCE_KEYS: ResourceKey[] = ["cpu", "gpu", "memory", "disk", "network"]; + +function routeFromHash(): RouteState { + const [page, sub] = window.location.hash.slice(1).split("/"); + const known = PAGE_KEYS.includes(page as PageKey); + const pageKey: PageKey = known ? (page as PageKey) : "compute"; + const resource = pageKey === "compute" && RESOURCE_KEYS.includes(sub as ResourceKey) ? (sub as ResourceKey) : null; + return { page: pageKey, resource }; } -const API_BASE = import.meta.env.VITE_API_BASE_URL ?? ""; const TOKEN_KEY = "compute-service-manager-token"; const emptyDraft: AppDraft = { name: "", @@ -85,99 +76,12 @@ const emptyDraft: AppDraft = { env_text: "{}", }; -async function request(path: string, token: string, init?: RequestInit): Promise { - const response = await fetch(`${API_BASE}${path}`, { - ...init, - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - ...init?.headers, - }, - }); - if (!response.ok) { - const body = await response.json().catch(() => ({})); - throw new Error(body.detail ?? `请求失败 (${response.status})`); - } - if (response.status === 204) return undefined as T; - return response.json() as Promise; -} - function formatTime(value: string | null): string { if (!value) return "—"; const date = new Date(value); return Number.isNaN(date.getTime()) ? value : date.toLocaleString("zh-CN", { hour12: false }); } -function formatBytes(value: number): string { - const units = ["B", "KB", "MB", "GB", "TB"]; - let size = value; - let unit = 0; - while (size >= 1024 && unit < units.length - 1) { - size /= 1024; - unit += 1; - } - return `${size.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`; -} - -function boundedPercent(value: number | null | undefined): number { - return Math.min(100, Math.max(0, value ?? 0)); -} - -function formatUptime(seconds: number | null | undefined): string { - if (!seconds) return "—"; - const days = Math.floor(seconds / 86400); - const hours = Math.floor((seconds % 86400) / 3600); - return days ? `${days} 天 ${hours} 小时` : `${hours} 小时 ${Math.floor((seconds % 3600) / 60)} 分钟`; -} - -function MetricTrend({ samples }: { samples: MetricSample[] }) { - const line = (field: "cpu" | "memory" | "gpu") => samples.map((sample, index) => { - const x = samples.length < 2 ? 50 : (index / (samples.length - 1)) * 100; - const y = 38 - boundedPercent(sample[field]) * 0.34; - return `${x},${y}`; - }).join(" "); - return ( -
-
RESOURCE ACTIVITY

资源使用趋势

{samples.length ? `最近 ${samples.length * 5} 秒` : "暂无数据"}
-
CPU内存GPU
-
-
100%50%0%
- - {[4, 21, 38].map((y) => )} - {samples.length > 1 && <> - - - - } - - {samples.length < 2 &&
暂无本机监控数据
} -
-
约 2 分钟滚动窗口{samples.length ? new Date(samples[samples.length - 1].time).toLocaleTimeString("zh-CN", { hour12: false }) : "等待数据"}
-
- ); -} - -function ResourceCard({ icon, label, value, detail, percent, tone }: { - icon: ReactNode; - label: string; - value: string; - detail: string; - percent: number; - tone: "green" | "violet" | "blue" | "amber"; -}) { - return ( -
-
-
{icon}
- {label} - {value} -
-
- {detail} -
- ); -} - function RuntimeStatusTable({ apps }: { apps: ManagedApp[] }) { const statusLabels: Record = { running: "运行中", @@ -195,11 +99,12 @@ function RuntimeStatusTable({ apps }: { apps: ManagedApp[] }) { {apps.length ? (
- + {apps.map((item) => ( + @@ -213,31 +118,61 @@ function RuntimeStatusTable({ apps }: { apps: ManagedApp[] }) { } function App() { - const [activePage, setActivePage] = useState(pageFromHash); + const [route, setRoute] = useState(routeFromHash); const [token, setToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) ?? ""); const [apps, setApps] = useState([]); const [metrics, setMetrics] = useState(null); - const [metricSamples, setMetricSamples] = useState([]); const [loading, setLoading] = useState(false); const [notice, setNotice] = useState(""); const [error, setError] = useState(""); + const [theme, setTheme] = useState(() => resolveTheme()); const [search, setSearch] = useState(""); const [modal, setModal] = useState<"add" | "edit" | "logs" | null>(null); const [selected, setSelected] = useState(null); const [draft, setDraft] = useState(emptyDraft); const [busyId, setBusyId] = useState(""); const [logLines, setLogLines] = useState([]); + const [logError, setLogError] = useState(""); + const [logsLoading, setLogsLoading] = useState(false); + const [logRefreshKey, setLogRefreshKey] = useState(0); + const logOutputRef = useRef(null); + + // 成功提示限时 4 秒自动消失;错误提示保持到手动关闭。 + useEffect(() => { + if (!notice) return; + const timer = window.setTimeout(() => setNotice(""), 4000); + return () => window.clearTimeout(timer); + }, [notice]); + + // 主题:CSS 分支与 canvas 调色板同步;未手动选择过时持续跟随系统。 + useEffect(() => { + applyTheme(theme); + }, [theme]); + useEffect(() => { + const mq = window.matchMedia("(prefers-color-scheme: dark)"); + const onSystem = () => { + if (!hasStoredTheme()) setTheme(mq.matches ? "dark" : "light"); + }; + mq.addEventListener("change", onSystem); + return () => mq.removeEventListener("change", onSystem); + }, []); + function toggleTheme() { + const next: Theme = theme === "dark" ? "light" : "dark"; + rememberTheme(next); + setTheme(next); + } useEffect(() => { // Keep the visible page in sync with browser back/forward navigation. - const syncPage = () => setActivePage(pageFromHash()); - window.addEventListener("hashchange", syncPage); - return () => window.removeEventListener("hashchange", syncPage); + const syncRoute = () => setRoute(routeFromHash()); + window.addEventListener("hashchange", syncRoute); + return () => window.removeEventListener("hashchange", syncRoute); }, []); - function navigateTo(page: PageKey) { - if (window.location.hash === `#${page}`) setActivePage(page); - else window.location.hash = page; + function navigateTo(page: PageKey, resource: ResourceKey | null = null) { + const target = `#${page}${page === "compute" && resource ? `/${resource}` : ""}`; + if (window.location.hash === target) setRoute(routeFromHash()); + else window.location.hash = target; } const loadApps = useCallback(async () => { @@ -274,12 +209,54 @@ function App() { useEffect(() => { if (!token) return; // 定时刷新卡片状态,后端仍由 systemd 负责进程托管。 - const timer = window.setInterval(() => { - void loadApps(); - void loadMetrics(); - }, 5000); - return () => window.clearInterval(timer); - }, [token, loadApps, loadMetrics]); + const appsTimer = window.setInterval(() => void loadApps(), 5000); + return () => window.clearInterval(appsTimer); + }, [token, loadApps]); + + useEffect(() => { + if (!token) return; + // 资源采样与后端 1 秒节奏一致(岛仔同款),驱动算力监控页的曲线、峰值和进程排行。 + const metricsTimer = window.setInterval(() => void loadMetrics(), 1000); + return () => window.clearInterval(metricsTimer); + }, [token, loadMetrics]); + + useEffect(() => { + if (modal !== "logs" || !selected || !token) return; + let disposed = false; + let inFlight = false; + + const refreshLogs = async () => { + if (inFlight) return; + inFlight = true; + setLogsLoading(true); + try { + const result = await request<{ lines: string[]; error: string | null }>(`/api/apps/${selected.id}/logs`, token); + if (!disposed) { + setLogLines(result.lines); + setLogError(result.error ?? ""); + } + } catch (reason) { + if (!disposed) setLogError(reason instanceof Error ? reason.message : "读取日志失败"); + } finally { + inFlight = false; + if (!disposed) setLogsLoading(false); + } + }; + + // Poll only while the log modal is open, avoiding background journal requests. + void refreshLogs(); + const timer = window.setInterval(() => void refreshLogs(), 2000); + return () => { + disposed = true; + window.clearInterval(timer); + }; + }, [modal, selected?.id, token, logRefreshKey]); + + useEffect(() => { + if (modal === "logs" && logOutputRef.current) { + logOutputRef.current.scrollTop = logOutputRef.current.scrollHeight; + } + }, [modal, logLines]); const filteredApps = useMemo(() => { const needle = search.trim().toLowerCase(); @@ -288,23 +265,6 @@ function App() { }, [apps, search]); const runningCount = apps.filter((item) => item.status === "running").length; const failedCount = apps.filter((item) => item.status === "failed").length; - const primaryGpu = metrics?.gpus[0]; - const gpuPercent = primaryGpu?.utilization ?? null; - const gpuMemoryText = primaryGpu?.memory_used_mb != null && primaryGpu.memory_total_mb != null - ? `${primaryGpu.memory_used_mb.toFixed(0)} / ${primaryGpu.memory_total_mb.toFixed(0)} MiB` - : primaryGpu ? "本机采集未提供显存数据" : "暂无 GPU 数据"; - - useEffect(() => { - if (!metrics?.cpu || !metrics.memory || !metrics.captured_at) { - setMetricSamples([]); - return; - } - const now = new Date(metrics.captured_at).getTime(); - setMetricSamples((previous) => [ - ...previous.filter((sample) => now - sample.time < 120_000), - { time: now, cpu: metrics.cpu.percent, memory: metrics.memory.percent, gpu: gpuPercent ?? 0 }, - ].slice(-24)); - }, [metrics, gpuPercent]); async function runAction(item: ManagedApp, action: "start" | "stop" | "restart") { setBusyId(item.id); @@ -325,6 +285,8 @@ function App() { } function openAdd() { + // 未配置管理密钥时禁止登记服务(写入类接口全部需要密钥)。 + if (!token) return; setSelected(null); setDraft(emptyDraft); setModal("add"); @@ -372,17 +334,10 @@ function App() { } } - async function showLogs(item: ManagedApp) { - setSelected(item); + function showLogs(item: ManagedApp) { setSelected(item); setLogLines([]); + setLogError(""); setModal("logs"); - try { - const result = await request<{ lines: string[]; error: string | null }>(`/api/apps/${item.id}/logs`, token); - setLogLines(result.lines); - if (result.error) setError(result.error); - } catch (reason) { - setError(reason instanceof Error ? reason.message : "读取日志失败"); - } } async function deleteApp(item: ManagedApp) { @@ -410,7 +365,6 @@ function App() { setToken(""); setApps([]); setMetrics(null); - setMetricSamples([]); setNotice("已清除当前浏览器会话中的管理密钥"); } @@ -422,18 +376,27 @@ function App() {
ComputeOSCONTROL PLANE
工作空间 - - - + + +
- +
本机节点{metrics?.server ? "本机采集在线" : "等待本机采集"}
-
工作空间/{pageTitles[activePage]}
+
工作空间/{pageTitles[route.page]}{route.page === "compute" && route.resource ? ` / ${RESOURCE_TITLES[route.resource]}` : ""}
+ + {route.page === "compute" && ( +
+ + {!token ? "请在设置中配置管理密钥" : metrics?.connection_status === "connected" ? `本机采集正常${metrics.captured_at ? ` · ${new Date(metrics.captured_at).toLocaleTimeString("zh-CN", { hour12: false })}` : ""}` : metrics?.connection_status === "unavailable" ? "本机采集不可用" : "正在采集"} +
+ )}
{metrics?.server?.name ?? "本机节点"}
@@ -444,44 +407,24 @@ function App() { {error &&
{error}
} {notice &&
{notice}
} - {activePage === "services" && <> +
+ {route.page === "services" && <>
SERVICE CONTROL

服务管理

管理已登记的服务,按需启动、停止或查看日志。

} - {activePage === "compute" && <> -
-
COMPUTE MONITORING

算力监控

查看节点资源占用、硬件信息与近期变化趋势。

-
{!token ? "请在设置中配置管理密钥" : metrics?.connection_status === "connected" ? "本机采集正常" : metrics?.connection_status === "unavailable" ? "本机采集不可用" : "正在采集"}
-
-
- } label="CPU 利用率" value={metrics?.cpu ? `${metrics.cpu.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.cpu ? `1 分钟负载 ${metrics.cpu.load_1m?.toFixed(2) ?? "—"}` : "等待本机采集"} percent={metrics?.cpu?.percent ?? 0} tone="green" /> - } label="系统内存" value={metrics?.memory ? `${metrics.memory.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.memory ? `${formatBytes(metrics.memory.used_bytes)} / ${formatBytes(metrics.memory.total_bytes)}` : "等待本机采集"} percent={metrics?.memory?.percent ?? 0} tone="violet" /> - } label={primaryGpu ? `GPU ${primaryGpu.index} · ${primaryGpu.name}` : "GPU 利用率"} value={gpuPercent == null ? "暂无数据" : `${gpuPercent.toFixed(1)}%`} detail={gpuMemoryText} percent={gpuPercent ?? 0} tone="blue" /> - } label="系统磁盘" value={metrics?.disk ? `${metrics.disk.percent.toFixed(1)}%` : "暂无数据"} detail={metrics?.disk ? `${formatBytes(metrics.disk.used_bytes)} / ${formatBytes(metrics.disk.total_bytes)}` : "等待本机采集"} percent={metrics?.disk?.percent ?? 0} tone="amber" /> -
-
数据来源 · 本机系统采集·每 5 秒刷新{metrics?.captured_at ? ` · 更新于 ${new Date(metrics.captured_at).toLocaleTimeString("zh-CN", { hour12: false })}` : ""}
- {metrics?.error &&
{metrics.error}
} -
- -
-
NODE PROFILE

节点概况

{metrics?.server ? "本机在线" : "暂无数据"}
- {metrics?.server ? <> -
{metrics.server.name}{metrics.server.platform || "Linux compute node"}{metrics.server.id ? ` · ID ${metrics.server.id}` : ""}
-
-
处理器{metrics.server.cpu_names[0] ?? "暂无数据"}
-
加速器{metrics.server.gpu_names.join(" · ") || "暂无数据"}
-
运行时间{formatUptime(metrics.server.uptime_seconds)}
-
网络吞吐{metrics.network ? `↓ ${formatBytes(metrics.network.in_bytes_per_second)}/s ↑ ${formatBytes(metrics.network.out_bytes_per_second)}/s` : "暂无数据"}
-
- :
暂无本机采集数据
} -
-
- } + {route.page === "compute" && ( + navigateTo("compute", resource)} + /> + )} - {activePage === "services" && <> + {route.page === "services" && <>
MANAGED SERVICES

已登记服务

{apps.length.toString().padStart(2, "0")}{runningCount} 运行中 · {failedCount} 异常
@@ -489,15 +432,16 @@ function App() {
- {!token ? null : loading && apps.length === 0 ? ( +
+ {loading && apps.length === 0 ? (
正在读取本机服务…
) : filteredApps.length ? (
{filteredApps.map((item) => )} -
) : ( @@ -505,12 +449,19 @@ function App() {

{search ? "没有匹配的应用" : "还没有登记应用"}

{search ? "试试其他应用名称或目录。" : "添加已有的 Python 服务,即可从卡片快捷启停。"}

- {!search && } + {!search && ( + token ? ( + + ) : ( + + ) + )}
)} +
} - {activePage === "runtime" && <> + {route.page === "runtime" && <>
RUNTIME STATUS

运行状态

集中查看登记服务的 systemd 进程状态与启动信息。

@@ -524,12 +475,13 @@ function App() { {token ? loading && apps.length === 0 ?
正在读取本机服务…
: : null} } - {activePage === "settings" && <> + {route.page === "settings" && <>
PANEL SETTINGS

设置

配置本机管理服务的访问密钥。

} +
COMPUTE SERVICE MANAGER · LOCAL CONTROL PLANE
@@ -560,8 +512,9 @@ function App() {
setModal(null)}>
event.stopPropagation()}>
JOURNAL OUTPUT

{selected.name} 最近日志

-
systemd journal
-
{logLines.length ? logLines.join("\n") : "暂无日志输出"}
+
systemd journal 实时同步 · 每 2 秒
+ {logError &&
{logError}
} +
{logLines.length ? logLines.join("\n") : logsLoading ? "正在读取日志…" : "暂无日志输出"}
) : null} diff --git a/frontend/src/api.ts b/frontend/src/api.ts new file mode 100644 index 0000000..ed287b9 --- /dev/null +++ b/frontend/src/api.ts @@ -0,0 +1,18 @@ +const API_BASE = import.meta.env.VITE_API_BASE_URL ?? ""; + +export async function request(path: string, token: string, init?: RequestInit): Promise { + const response = await fetch(`${API_BASE}${path}`, { + ...init, + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${token}`, + ...init?.headers, + }, + }); + if (!response.ok) { + const body = await response.json().catch(() => ({})); + throw new Error(body.detail ?? `请求失败 (${response.status})`); + } + if (response.status === 204) return undefined as T; + return response.json() as Promise; +} diff --git a/frontend/src/compute/ComputePage.tsx b/frontend/src/compute/ComputePage.tsx new file mode 100644 index 0000000..b5b92ad --- /dev/null +++ b/frontend/src/compute/ComputePage.tsx @@ -0,0 +1,572 @@ +import { useEffect, useMemo, useRef, useState } from "react"; +import type { CSSProperties, ReactNode } from "react"; +import { Activity, AlertCircle, Cpu, HardDrive, LayoutDashboard, MemoryStick, Network, Server } from "lucide-react"; +import { request } from "../api"; +import { formatBytes, formatLinkSpeed, formatRate, formatUptime } from "./format"; +import { C, RESOURCE_HEX, alpha, mix, secondary, temperatureColor } from "./palette"; +import type { HistoryResponse, HistorySample, ProcessInfo, ResourceKey, SystemMetrics } from "./types"; +import { CoreBars, GlassBar, MirrorTrend, NeonTrend, ProgramRows, RankPanel, RingGauge, Tank } from "./widgets"; +import type { RankRow } from "./widgets"; +import { useSmoothed } from "./dynamics"; + +export const RESOURCE_TITLES: Record = { cpu: "CPU", gpu: "显卡", memory: "内存", disk: "磁盘", network: "网络" }; +const RESOURCE_ORDER: ResourceKey[] = ["cpu", "gpu", "memory", "disk", "network"]; + +function seriesOf(history: HistorySample[], pick: (sample: HistorySample) => number | null): (number | null)[] { + return history.map(pick); +} + +/** 最近一分钟窗口(岛仔所有曲线与峰值都用 60s)。 */ +function window60(history: HistorySample[]): HistorySample[] { + const last = history[history.length - 1]?.t ?? Date.now() / 1000; + return history.filter((sample) => sample.t > last - 60); +} + +function peakOf(values: (number | null)[]): number | null { + let peak: number | null = null; + for (const value of values) if (value != null && (peak == null || value > peak)) peak = value; + return peak; +} + +/** throughput_scale:一分钟峰值 ×1.15,留出下限,空闲时曲线贴底。 */ +function rateScale(values: (number | null)[], floor: number): number { + return Math.max((peakOf(values) ?? 0) * 1.15, floor); +} + +function percentText(value: number | null | undefined): string { + return value == null ? "—" : `${Math.round(value)}%`; +} + +function speedParts(rate: number | null | undefined): [string, string] { + if (rate == null) return ["—", ""]; + const text = formatRate(rate); + const [num, unit] = text.split(" "); + return [num ?? text, unit ?? ""]; +} + +function deriveSample(t: number, metrics: SystemMetrics): HistorySample { + const gpuValues = metrics.gpus.map((gpu) => gpu.utilization).filter((v): v is number => v != null); + return { + t, + cpu: metrics.cpu?.percent ?? null, + percpu: metrics.cpu?.percpu ?? null, + gpu: gpuValues.length ? Math.max(...gpuValues) : null, + mem: metrics.memory?.percent ?? null, + disk_read: metrics.disk?.read_bps ?? null, + disk_write: metrics.disk?.write_bps ?? null, + net_in: metrics.network?.in_bytes_per_second ?? null, + net_out: metrics.network?.out_bytes_per_second ?? null, + }; +} + +function processRanks(processes: ProcessInfo[] | undefined, pick: (item: ProcessInfo) => number, text: (item: ProcessInfo) => string): RankRow[] { + if (!processes?.length) return []; + const top = Math.max(pick(processes[0]), 0.0001); + return processes.map((item) => ({ + name: item.name, + sub: item.user ? `${item.user} · pid ${item.pid}` : `pid ${item.pid}`, + text: text(item), + share: pick(item) / top, + })); +} + +/** 每核最近 10 秒峰值(core_bars 里的短横线)。 */ +function perCorePeaks(history: HistorySample[]): number[] | null { + const last = history[history.length - 1]; + if (!last?.percpu) return null; + const peaks = new Array(last.percpu.length).fill(0); + for (const sample of history) { + if (last.t - sample.t > 10 || !sample.percpu || sample.percpu.length !== peaks.length) continue; + sample.percpu.forEach((value, index) => { + if (value > peaks[index]) peaks[index] = value; + }); + } + return peaks; +} + +type Props = { + token: string; + metrics: SystemMetrics | null; + resource: ResourceKey | null; + onNavigate: (resource: ResourceKey | null) => void; +}; + +export default function ComputePage({ token, metrics, resource, onNavigate }: Props) { + const [history, setHistory] = useState([]); + const lastSampleRef = useRef(0); + + // Seed charts with the rolling buffer once per session token. + useEffect(() => { + let disposed = false; + setHistory([]); + lastSampleRef.current = 0; + if (!token) return; + request("/api/system/history", token) + .then((result) => { + if (!disposed) setHistory(result.samples.filter((sample) => Number.isFinite(sample.t))); + }) + .catch(() => { + // History is an enhancement; charts keep their placeholder state without it. + }); + return () => { + disposed = true; + }; + }, [token]); + + // Extend the buffer from the shell's 2-second metrics poll instead of a second timer. + useEffect(() => { + if (!metrics?.captured_at || !metrics.cpu || !metrics.memory) return; + const t = Date.parse(metrics.captured_at) / 1000; + if (!Number.isFinite(t) || t === lastSampleRef.current) return; + lastSampleRef.current = t; + setHistory((previous) => [...previous.filter((sample) => t - sample.t <= 660), deriveSample(t, metrics)]); + }, [metrics]); + + const short = useMemo(() => window60(history), [history]); + const series = useMemo(() => ({ + cpu: seriesOf(short, (sample) => sample.cpu), + gpu: seriesOf(short, (sample) => sample.gpu), + mem: seriesOf(short, (sample) => sample.mem), + read: seriesOf(short, (sample) => sample.disk_read), + write: seriesOf(short, (sample) => sample.disk_write), + diskTotal: short.map((sample) => (sample.disk_read == null && sample.disk_write == null ? null : (sample.disk_read ?? 0) + (sample.disk_write ?? 0))), + in: seriesOf(short, (sample) => sample.net_in), + out: seriesOf(short, (sample) => sample.net_out), + netTotal: short.map((sample) => (sample.net_in == null && sample.net_out == null ? null : (sample.net_in ?? 0) + (sample.net_out ?? 0))), + }), [short]); + + // DGX Spark's GB10 uses unified CPU/GPU memory, so host memory is the shared GPU pool. + const unified = metrics?.gpus.some((gpu) => /GB10/i.test(gpu.name)) ?? false; + + return ( +
+ +
+ {resource == null ? ( + + ) : ( + + )} +
+
+ ); +} + +/** 顶部常规分页页签:图标 + 文字,读数留给下方内容区,避免信息重复。 */ +function ResourceTabs({ resource, onNavigate }: { + resource: ResourceKey | null; + onNavigate: (key: ResourceKey | null) => void; +}) { + const tabs: { key: ResourceKey | null; label: string; color: string; icon: ReactNode }[] = [ + { key: null, label: "总览", color: C.cpu, icon: }, + { key: "cpu", label: RESOURCE_TITLES.cpu, color: RESOURCE_HEX.cpu, icon: }, + { key: "gpu", label: RESOURCE_TITLES.gpu, color: RESOURCE_HEX.gpu, icon: }, + { key: "memory", label: RESOURCE_TITLES.memory, color: RESOURCE_HEX.memory, icon: }, + { key: "disk", label: RESOURCE_TITLES.disk, color: RESOURCE_HEX.disk, icon: }, + { key: "network", label: RESOURCE_TITLES.network, color: RESOURCE_HEX.network, icon: }, + ]; + const activeIndex = resource == null ? 0 : RESOURCE_ORDER.indexOf(resource) + 1; + const accent = resource == null ? C.cpu : RESOURCE_HEX[resource]; + return ( +
+
+ ); +} + +type SeriesBundle = { + cpu: (number | null)[]; gpu: (number | null)[]; mem: (number | null)[]; + read: (number | null)[]; write: (number | null)[]; diskTotal: (number | null)[]; + in: (number | null)[]; out: (number | null)[]; netTotal: (number | null)[]; +}; + +/* ---------------- 总览 ---------------- */ + +function Overview({ metrics, series, unified, onNavigate }: { metrics: SystemMetrics | null; series: SeriesBundle; unified: boolean; onNavigate: (key: ResourceKey) => void }) { + const cpu = metrics?.cpu ?? null; + const memory = metrics?.memory ?? null; + const disk = metrics?.disk ?? null; + const network = metrics?.network ?? null; + const gpu = metrics?.gpus[0] ?? null; + const nicTop = network?.per_nic?.find((nic) => nic.link_mbps) ?? null; + + const gpuName = (gpu?.name ?? "").replace("(R)", "").replace("Intel ", "").replace("NVIDIA ", "").replace("AMD ", "").trim(); + const integrated = unified || (gpu != null && (gpu.memory_total_mb ?? 0) < 512); + const vramUsed = integrated ? memory?.used_bytes ?? null : gpu?.memory_used_mb != null ? gpu.memory_used_mb * 1048576 : null; + const vramTotal = integrated ? memory?.total_bytes ?? null : gpu?.memory_total_mb != null ? gpu.memory_total_mb * 1048576 : null; + const vramShare = vramUsed != null && vramTotal ? Math.min(1, vramUsed / vramTotal) : 0; + const gpuSubColor = gpu?.temperature_c != null ? temperatureColor(gpu.temperature_c) : C.muted; + const frequencyGhz = cpu?.frequency_mhz ? `${(cpu.frequency_mhz / 1000).toFixed(2)} GHz` : ""; + + const topCards: { key: ResourceKey; value: number | null; sub: ReactNode; subColor?: string; series: (number | null)[]; row: [string, string]; strip: ReactNode; foot?: ReactNode }[] = [ + { + key: "cpu", + value: cpu?.percent ?? null, + sub: frequencyGhz || "等待本机采集", + series: series.cpu, + row: ["逻辑处理器", cpu?.cores != null ? String(cpu.cores) : "—"], + strip: , + foot: cpu?.cpu_names?.[0] ? {cpu.cpu_names[0]} : null, + }, + { + key: "gpu", + value: gpu?.utilization ?? null, + sub: gpu ? (gpu.temperature_c != null ? `${gpu.temperature_c.toFixed(0)} °C` : gpuName || "显卡") : "等待本机采集", + subColor: gpu ? gpuSubColor : undefined, + series: series.gpu, + row: [integrated ? "共享显存" : "专用显存", vramUsed != null && vramTotal != null ? `${formatBytes(vramUsed)} / ${formatBytes(vramTotal)}` : "—"], + strip: , + }, + { + key: "memory", + value: memory?.percent ?? null, + sub: memory ? `${formatBytes(memory.used_bytes)} / ${formatBytes(memory.total_bytes)}` : "等待本机采集", + series: series.mem, + row: ["可用", memory ? formatBytes(memory.available_bytes ?? memory.total_bytes - memory.used_bytes) : "—"], + strip: memory ? ( + + ) : null, + }, + ]; + + const ioCards: { key: ResourceKey; note: string; values: [string, string, number | null][]; series: (number | null)[]; scale: number }[] = [ + { + key: "disk", + note: disk?.active_percent != null ? `活动 ${disk.active_percent.toFixed(0)}%` : "活动 —", + values: [["读", formatRate(disk?.read_bps), 1], ["写", formatRate(disk?.write_bps), 0]], + series: series.diskTotal, + scale: rateScale(series.diskTotal, 1e6) * 2, + }, + { + key: "network", + note: nicTop?.link_mbps ? formatLinkSpeed(nicTop.link_mbps) : "链路 —", + values: [["↓", formatRate(network?.in_bytes_per_second), 1], ["↑", formatRate(network?.out_bytes_per_second), 0]], + series: series.netTotal, + scale: rateScale(series.netTotal, 64e3) * 2, + }, + ]; + + return ( + <> + {metrics?.error &&
{metrics.error}
} + +
+ {topCards.map((card) => ( + + ))} + {ioCards.map((card) => ( +
onNavigate(card.key)} onKeyDown={(event) => { if (event.key === "Enter" || event.key === " ") { event.preventDefault(); onNavigate(card.key); } }}> +
+ +
+
+ + {RESOURCE_TITLES[card.key]} + {card.note} +
+
+ {card.values.map(([label, value, primary]) => ( + {label}{value} + ))} +
+
+ ))} +
+ +
+
+ item.cpu_percent, (item) => `${item.cpu_percent.toFixed(1)}%`)} color={RESOURCE_HEX.cpu} empty="正在统计…" /> + item.memory_bytes, (item) => formatBytes(item.memory_bytes))} color={RESOURCE_HEX.memory} empty="正在统计…" /> +
+ +
+ + ); +} + +/** 硬件卡:大数字 0.5s 连续滑移(岛仔 animate_value),配液位舱与 60s 霓虹线。 */ +function HardwareCard({ card, onNavigate }: { + card: { key: ResourceKey; value: number | null; sub: ReactNode; subColor?: string; series: (number | null)[]; row: [string, string]; strip: ReactNode; foot?: ReactNode }; + series?: (number | null)[]; + onNavigate: (key: ResourceKey) => void; +}) { + const shown = useSmoothed(card.value, 0.5); + return ( +
onNavigate(card.key)} + onKeyDown={(event) => { + if (event.key === "Enter" || event.key === " ") { + event.preventDefault(); + onNavigate(card.key); + } + }} + > +
+ + {RESOURCE_TITLES[card.key]} + 峰值 {percentText(peakOf(card.series))} +
+
+
+ {shown == null ? "—" : String(Math.round(shown))}{card.value != null && %} + {card.sub} + +
{card.row[0]}{card.row[1]}
+
{card.strip}
+
+ +
+ {card.foot &&
{card.foot}
} +
+ ); +} + +function HostPanel({ metrics }: { metrics: SystemMetrics | null }) { + return ( +
+
+
NODE PROFILE

节点概况

+ {metrics?.server ? "本机在线" : "暂无数据"} +
+ {metrics?.server ? ( + <> +
+
+
{metrics.server.name}{metrics.server.platform || "Linux compute node"}
+
+
+
处理器{metrics.server.cpu_names[0] ?? "暂无数据"}
+
加速器{metrics.server.gpu_names.join(" · ") || "暂无数据"}
+
运行时间{formatUptime(metrics.server.uptime_seconds)}
+
网络吞吐{metrics.network ? `↓ ${formatBytes(metrics.network.in_bytes_per_second)}/s ↑ ${formatBytes(metrics.network.out_bytes_per_second)}/s` : "暂无数据"}
+
+ + ) : ( +
暂无本机采集数据
+ )} +
+ ); +} + +/* ---------------- 详情页 ---------------- */ + +type DetailProps = { + resource: ResourceKey; + metrics: SystemMetrics | null; + series: SeriesBundle; + unified: boolean; + peaks: number[] | null; +}; + +function DetailView({ resource, metrics, series, unified, peaks }: DetailProps) { + const [hoverProg, setHoverProg] = useState(null); + const color = RESOURCE_HEX[resource]; + const cpu = metrics?.cpu ?? null; + const memory = metrics?.memory ?? null; + const disk = metrics?.disk ?? null; + const network = metrics?.network ?? null; + const gpu = metrics?.gpus[0] ?? null; + const volumes = metrics?.disks ?? []; + + const diskScale = rateScale(series.diskTotal, 1e6); + const netScale = rateScale(series.in.map((v, i) => Math.max(v ?? 0, series.out[i] ?? 0)), 64e3); + const dial = network ? (Math.log10(Math.max(network.in_bytes_per_second, 1e3) / 1e3) / 6) * 100 : null; + const linkMax = Math.max(0, ...(network?.per_nic ?? []).map((nic) => nic.link_mbps ?? 0)); + const linkBusy = linkMax && network ? Math.min(100, ((network.in_bytes_per_second + network.out_bytes_per_second) * 8 * 100) / (linkMax * 1e6)) : null; + const [netBig, netUnit] = speedParts(network?.in_bytes_per_second); + const peak60 = (values: (number | null)[]) => percentText(peakOf(values)); + + const gauge: { value: number | null; big?: ReactNode; unit: ReactNode } = + resource === "cpu" ? { value: cpu?.percent ?? null, unit: "占用" } + : resource === "gpu" ? { value: gpu?.utilization ?? null, unit: "占用" } + : resource === "memory" ? { value: memory?.percent ?? null, unit: "已用" } + : resource === "disk" ? { value: disk?.active_percent ?? null, unit: "活动时间" } + : { value: dial, big: netBig, unit: `${netUnit} 下载`.trim() }; + + const rows: [string, string, string?][] = + resource === "cpu" ? [["频率", cpu?.frequency_mhz ? `${(cpu.frequency_mhz / 1000).toFixed(2)} GHz` : "—"], ["用户态", percentText(cpu?.user_percent)], ["内核态", percentText(cpu?.system_percent)], ["一分钟峰值", peak60(series.cpu)]] + : resource === "gpu" ? [["温度", gpu?.temperature_c != null ? `${gpu.temperature_c.toFixed(0)} °C` : "—", gpu?.temperature_c != null ? temperatureColor(gpu.temperature_c) : undefined], ["专用显存", gpu?.memory_used_mb != null ? formatBytes(gpu.memory_used_mb * 1048576) : "—"], ["共享显存", unified && memory ? formatBytes(memory.used_bytes) : "—"], ["一分钟峰值", peak60(series.gpu)]] + : resource === "memory" ? [["已用", memory ? formatBytes(memory.used_bytes) : "—"], ["可用", memory ? formatBytes(memory.available_bytes ?? memory.total_bytes - memory.used_bytes) : "—"], ["缓存", memory ? formatBytes((memory.cached_bytes ?? 0) + (memory.buffered_bytes ?? 0)) : "—"], ["总量", memory ? formatBytes(memory.total_bytes) : "—"]] + : resource === "disk" ? [["读取", formatRate(disk?.read_bps)], ["写入", formatRate(disk?.write_bps)], ["合计", formatRate(sumOrNull(disk?.read_bps, disk?.write_bps))], ["一分钟峰值", formatRate(peakOf(series.diskTotal))]] + : [["上传", formatRate(network?.out_bytes_per_second)], ["链路", linkMax ? formatLinkSpeed(linkMax) : "—"], ["链路占用", percentText(linkBusy)], ["一分钟峰值", formatRate(peakOf(series.in))]]; + + return ( + <> +
+
+ +
+ {rows.map(([label, value, tone]) => ( +
{label}{value}
+ ))} +
+
+ +
+ {resource === "cpu" && ( + <> + + + + + + )} + {resource === "gpu" && ( + <> + + + + {[["核心", gpu?.utilization], ["编码", gpu?.encoder_pct], ["解码", gpu?.decoder_pct]].map(([label, value], i) => ( +
+ {label} + + {percentText(value as number | null | undefined)} +
+ ))} +
{gpu?.name || "显卡型号未知"}
+
+ {unified ? "共享" : "专用"} + + {unified && memory ? `${formatBytes(memory.used_bytes)} / ${formatBytes(memory.total_bytes)}` : gpu?.memory_used_mb != null && gpu.memory_total_mb != null ? `${formatBytes(gpu.memory_used_mb * 1048576)} / ${formatBytes(gpu.memory_total_mb * 1048576)}` : "—"} +
+ + )} + {resource === "memory" && memory && } + {resource === "memory" && !memory &&
等待本机采集
} + {resource === "disk" && ( + <> + + + 3 ? `另有 ${volumes.length - 3} 个分区` : ""} /> + {volumes.slice(0, 3).map((volume) => ( +
+ {volume.mountpoint} + = 90 ? C.hot : color }]} energy={(disk?.active_percent ?? 0) / 100} seed={23} height={14} /> + {formatBytes(volume.used_bytes)} / {formatBytes(volume.total_bytes)} +
+ ))} + + )} + {resource === "network" && ( + <> + + + +
+
已接收{formatBytes(network?.received_bytes_total ?? 0)}
+
已发送{formatBytes(network?.sent_bytes_total ?? 0)}
+
合计{formatBytes((network?.received_bytes_total ?? 0) + (network?.sent_bytes_total ?? 0))}
+
+ + )} +
+ +
+ {resource === "cpu" && <>
item.cpu_percent, (item) => `${item.cpu_percent.toFixed(1)}%`)} color={color} empty="正在统计…" />
} + {resource === "gpu" && <>
} + {resource === "memory" && <>
item.memory_bytes, (item) => formatBytes(item.memory_bytes))} color={color} empty="正在统计…" onHover={setHoverProg} />
} + {resource === "disk" && <>
item.io_bytes_per_second ?? 0, (item) => formatRate(item.io_bytes_per_second ?? 0))} color={color} empty="正在统计…" />
} + {resource === "network" && <>
} +
+
+ + ); +} + +function sumOrNull(a: number | null | undefined, b: number | null | undefined): number | null { + return a == null && b == null ? null : (a ?? 0) + (b ?? 0); +} + +function SectionTitle({ title, note }: { title: string; note: string }) { + return
{title}{note && {note}}
; +} + +function gpuProcessRows(gpu: SystemMetrics["gpus"][number] | null): RankRow[] { + const processes = gpu?.processes ?? []; + const top = Math.max(processes[0]?.memory_mb ?? 1, 0.001); + return processes.map((item) => ({ name: item.name, sub: `pid ${item.pid}`, text: `${item.memory_mb.toFixed(0)} MB`, share: item.memory_mb / top })); +} + +function nicRows(network: SystemMetrics["network"]): RankRow[] { + const nics = network?.per_nic ?? []; + const top = Math.max(nics[0] ? nics[0].rx_bps + nics[0].tx_bps : 1, 0.001); + return nics + .filter((nic) => nic.rx_bps + nic.tx_bps > 256) + .slice(0, 8) + .map((nic) => ({ name: nic.name, sub: nic.link_mbps ? formatLinkSpeed(nic.link_mbps) : undefined, text: `↓${formatRate(nic.rx_bps)} ↑${formatRate(nic.tx_bps)}`, share: (nic.rx_bps + nic.tx_bps) / top })); +} + +/** 内存构成条:悬停右侧程序列表点亮它在「程序」段中的那一截;图例 + 可用括号。 */ +function MemoryMain({ memory, series, color, hoverProg, processes }: { + memory: NonNullable; + series: SeriesBundle; + color: string; + hoverProg: number | null; + processes: ProcessInfo[]; +}) { + const total = Math.max(memory.total_bytes, 1); + const cached = (memory.cached_bytes ?? 0) + (memory.buffered_bytes ?? 0); + const usedShare = memory.used_bytes / total; + const cacheColor = mix(mix(color, RESOURCE_HEX.network, 0.75), C.surface, 0.5); + const freeColor = C.free; + const hovered = hoverProg != null ? processes[hoverProg] : undefined; + const note = hovered ? `${hovered.name} ${formatBytes(hovered.memory_bytes)}` : `可用 ${formatBytes(memory.available_bytes ?? total - memory.used_bytes)}`; + // 悬停程序的亮块:在「程序」段内按排行顺序累计摆放。 + let span: { left: number; width: number } | null = null; + if (hovered && hoverProg != null) { + let before = 0; + for (let i = 0; i < hoverProg && i < processes.length; i += 1) before += processes[i].memory_bytes; + const from = Math.min(before / total, usedShare); + const to = Math.min(from + hovered.memory_bytes / total, usedShare); + span = { left: from * 100, width: Math.max(to - from, 0.002) * 100 }; + } + return ( + <> + +
+ + {span && ( + + )} + +
+
+ 程序{formatBytes(memory.used_bytes)} + 缓存{formatBytes(cached)} + 空闲{formatBytes(Math.max(0, (memory.available_bytes ?? total - memory.used_bytes) - cached))} +
+ + + + ); +} diff --git a/frontend/src/compute/dynamics.ts b/frontend/src/compute/dynamics.ts new file mode 100644 index 0000000..d33d673 --- /dev/null +++ b/frontend/src/compute/dynamics.ts @@ -0,0 +1,402 @@ +import { useEffect, useRef, useState } from "react"; +import { alpha, C, loadColor, mix, parseColor } from "./palette"; + +/** + * 岛仔 dynamics 移植层:颗粒闪烁的哈希、共享帧调度器、数值平滑和画布画法, + * 公式与 performance_ui.rs 的 hash/cells/tank/glass_bar/core_bars 一一对应。 + */ + +const PITCH = 3.0; +const DOT = 1.6; + +/** 岛仔 SHIMMER 常量:静止时颗粒闪烁的最低重绘节奏。 */ +export const SHIMMER_MS = 90; + +/** hash(a,b):整数哈希到 0..1,同一格每帧一致(Rust 版逐位移植)。 */ +export function hash(a: number, b: number): number { + const rot = (v: number, n: number) => ((v << n) | (v >>> (32 - n))) | 0; + let x = (Math.imul(a, 0x9e3779b1) ^ rot(Math.imul(b, 0x85ebca77), 13)) | 0; + x ^= x >>> 15; + x = Math.imul(x, 0x2c1b3c6d); + x ^= x >>> 12; + return (x & 0xffff) / 65535; +} + +const reducedMotion = () => typeof matchMedia !== "undefined" && matchMedia("(prefers-reduced-motion: reduce)").matches; + +/** + * Shared rAF dispatcher — one loop drives every canvas. + * Full frame rate while the page is visible; subscribers receive seconds so + * exponential smoothing is frame-rate independent (岛仔 animate_value 的 Web 等价物). + */ +type FrameSub = (dt: number, t: number) => void; +const frameSubs = new Set(); +let frameRaf = 0; +let lastFrame = 0; + +function pumpFrame(now: number) { + if (!frameSubs.size) { + frameRaf = 0; + return; + } + frameRaf = requestAnimationFrame(pumpFrame); + if (document.hidden) return; + const dt = Math.min(0.25, (now - lastFrame) / 1000) || 0.016; + lastFrame = now; + const reduce = reducedMotion(); + const t = now / 1000; + for (const sub of frameSubs) { + try { + // 减少动效时:dt 拉满让插值一步到位,闪烁相位走慢速保持画面不死。 + sub(reduce ? Math.max(dt, 1) : dt, reduce ? 7.77 + Math.floor(t / 4) : t); + } catch { + frameSubs.delete(sub); + } + } +} + +export function subscribeFrame(cb: FrameSub): () => void { + frameSubs.add(cb); + lastFrame = performance.now(); + if (!frameRaf) frameRaf = requestAnimationFrame(pumpFrame); + return () => { + frameSubs.delete(cb); + }; +} + +/** egui animate_value_with_time 的等价物:数值朝目标指数滑移(共享帧调度器)。 */ +export function useSmoothed(value: number | null, duration = 0.45): number | null { + const [shown, setShown] = useState(value); + const current = useRef(value); + const target = useRef(value); + target.current = value; + useEffect(() => { + if (reducedMotion()) { + current.current = target.current; + setShown(target.current); + return; + } + return subscribeFrame((dt) => { + const goal = target.current; + const at = current.current; + if (goal == null || at == null) { + if (at !== goal) { + current.current = goal; + setShown(goal); + } + return; + } + const k = 1 - Math.exp(-(dt / Math.max(0.05, duration)) * 3); + const next = at + (goal - at) * k; + if (Math.abs(goal - next) < 0.02) { + if (current.current !== goal) { + current.current = goal; + setShown(goal); + } + } else { + current.current = next; + setShown(next); + } + }); + }, [duration]); + return shown; +} + +export interface Rect { + x: number; + y: number; + w: number; + h: number; +} + +export function roundRect(ctx: CanvasRenderingContext2D, x: number, y: number, w: number, h: number, r: number) { + const rad = Math.min(r, w / 2, h / 2); + ctx.beginPath(); + ctx.moveTo(x + rad, y); + ctx.arcTo(x + w, y, x + w, y + h, rad); + ctx.arcTo(x + w, y + h, x, y + h, rad); + ctx.arcTo(x, y + h, x, y, rad); + ctx.arcTo(x, y, x + w, y, rad); + ctx.closePath(); +} + +function insideRound(shape: Rect, r: number, px: number, py: number, pad: number): boolean { + const l = shape.x + pad; + const t = shape.y + pad; + const rr = shape.x + shape.w - pad; + const b = shape.y + shape.h - pad; + if (px < l || px > rr || py < t || py > b) return false; + const rad = Math.max(0, r - pad); + const cx = Math.min(Math.max(px, l + rad), rr - rad); + const cy = Math.min(Math.max(py, t + rad), b - rad); + return (px - cx) ** 2 + (py - cy) ** 2 <= rad * rad; +} + +/** cells():玻璃里的颗粒网格;lit 时越靠底越密,能量越高越密、闪得越快。 */ +export function paintCells( + ctx: CanvasRenderingContext2D, + shape: Rect, + radius: number, + area: Rect, + span: [number, number], + color: string, + energy: number, + t: number, + seed: number, + k: number, + lit: boolean, +) { + const cols = Math.max(0, Math.floor((shape.w - 1.4) / PITCH)); + const rows = Math.max(0, Math.floor((shape.h - 1.4) / PITCH)); + const ox = shape.x + (shape.w - cols * PITCH) / 2 + (PITCH - DOT) / 2; + const oy = shape.y + (shape.h - rows * PITCH) / 2 + (PITCH - DOT) / 2; + const e = Math.min(1, Math.max(0, energy)); + const speed = 1.2 + 3.2 * e; + const top = area.y; + const bottom = area.y + area.h; + for (let i = 0; i < cols; i += 1) { + const px = ox + i * PITCH; + if (px + DOT / 2 < Math.max(span[0], area.x) || px + DOT / 2 > Math.min(span[1], area.x + area.w)) continue; + for (let j = 0; j < rows; j += 1) { + const py = oy + j * PITCH; + if (py + DOT / 2 < top || py + DOT / 2 > bottom) continue; + if (!insideRound(shape, radius, px + DOT / 2, py + DOT / 2, 0.9)) continue; + if (!lit) { + ctx.fillStyle = alpha(color, 0.05 * k); + ctx.fillRect(px, py, DOT, DOT); + continue; + } + const depth = Math.min(1, Math.max(0, (py + DOT - top) / Math.max(1, area.h))); + const chance = (0.16 + 0.6 * e) * (0.12 + 0.88 * Math.pow(depth, 1.6)); + if (hash(seed + i, j) > chance) { + ctx.fillStyle = alpha(color, 0.07 * k); + ctx.fillRect(px, py, DOT, DOT); + continue; + } + const phase = hash(j * 31 + seed, i); + const twinkle = 0.5 + 0.5 * Math.sin(t * speed * (0.6 + phase) + phase * Math.PI * 2); + const tint = mix(color, "#ffffff", 0.2 + 0.6 * twinkle * hash(i, j + seed)); + ctx.fillStyle = alpha(tint, (0.4 + 0.6 * twinkle) * k); + ctx.fillRect(px, py, DOT, DOT); + } + } +} + +function glassBody(ctx: CanvasRenderingContext2D, rect: Rect, radius: number, color: string, k: number) { + const grad = ctx.createLinearGradient(0, rect.y, 0, rect.y + rect.h); + grad.addColorStop(0, alpha(color, 0.04 * k)); + grad.addColorStop(1, alpha(color, 0.2 * k)); + ctx.fillStyle = grad; + roundRect(ctx, rect.x, rect.y, rect.w, rect.h, radius); + ctx.fill(); +} + +function glassRim(ctx: CanvasRenderingContext2D, rect: Rect, radius: number, color: string, k: number) { + ctx.strokeStyle = alpha(mix(color, "#ffffff", 0.1), 0.85 * k); + ctx.lineWidth = 1; + roundRect(ctx, rect.x + 0.5, rect.y + 0.5, rect.w - 1, rect.h - 1, radius); + ctx.stroke(); + const inset = Math.max(radius, 1.5); + if (rect.w > inset * 2) { + ctx.strokeStyle = alpha(mix(color, "#ffffff", 0.4), k); + ctx.lineWidth = 1.4; + ctx.beginPath(); + ctx.moveTo(rect.x + inset, rect.y + rect.h - 0.9); + ctx.lineTo(rect.x + rect.w - inset, rect.y + rect.h - 0.9); + ctx.stroke(); + ctx.strokeStyle = alpha("#ffffff", 0.1 * k); + ctx.lineWidth = 0.8; + ctx.beginPath(); + ctx.moveTo(rect.x + inset, rect.y + 1.1); + ctx.lineTo(rect.x + rect.w - inset, rect.y + 1.1); + ctx.stroke(); + } +} + +function glowDot(ctx: CanvasRenderingContext2D, cx: number, cy: number, r: number, color: string) { + const grad = ctx.createRadialGradient(cx, cy, 0, cx, cy, r); + grad.addColorStop(0, color); + grad.addColorStop(1, alpha(color, 0)); + ctx.fillStyle = grad; + ctx.beginPath(); + ctx.arc(cx, cy, r, 0, Math.PI * 2); + ctx.fill(); +} + +/** tank():竖向玻璃液位舱——底纹颗粒、液面亮线、舱底光晕。 */ +export function paintTank(ctx: CanvasRenderingContext2D, rect: Rect, value: number | null, color: string, t: number, seed: number) { + const { x, y, w, h } = rect; + const radius = Math.min(w * 0.2, 3); + ctx.fillStyle = alpha(color, 0.04); + roundRect(ctx, x, y, w, h, radius); + ctx.fill(); + ctx.strokeStyle = alpha(color, 0.2); + ctx.lineWidth = 1; + roundRect(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius); + ctx.stroke(); + paintCells(ctx, rect, radius, rect, [x, x + w], color, 0, t, seed, 1, false); + const f = value == null ? 0 : Math.min(1, Math.max(0, value / 100)); + if (f <= 0.004) return; + const top = y + h - Math.max(h * f, 1.5); + glowDot(ctx, x + w / 2, y + h, w * 1.6, alpha(color, 0.08 + 0.12 * f)); + ctx.save(); + ctx.beginPath(); + ctx.rect(x - 2, top, w + 4, y + h - top + 3); + ctx.clip(); + glassBody(ctx, rect, radius, color, 1); + paintCells(ctx, rect, radius, { x, y: top, w, h: y + h - top }, [x, x + w], color, f, t, seed, 1, true); + glassRim(ctx, rect, radius, color, 1); + ctx.restore(); + if (f < 0.995) { + glowDot(ctx, x + w / 2, top + 1, w * 0.8, alpha(color, 0.3)); + ctx.strokeStyle = mix(color, "#ffffff", 0.55); + ctx.lineWidth = 1.4; + ctx.beginPath(); + ctx.moveTo(x + 1.2, top + 0.7); + ctx.lineTo(x + w - 1.2, top + 0.7); + ctx.stroke(); + } +} + +export interface BarPart { + share: number; + color: string; +} + +/** glass_bar():分段构成条——跨段连续颗粒、段间断缝、已用末端亮边。 */ +export function paintGlassBar(ctx: CanvasRenderingContext2D, rect: Rect, parts: BarPart[], focus: number | null | "none", energy: number, t: number, seed: number) { + const { x, y, w, h } = rect; + const radius = Math.min(h * 0.2, 3); + ctx.fillStyle = C.surface; + roundRect(ctx, x, y, w, h, radius); + ctx.fill(); + ctx.strokeStyle = C.grid; + ctx.lineWidth = 1; + roundRect(ctx, x + 0.5, y + 0.5, w - 1, h - 1, radius); + ctx.stroke(); + paintCells(ctx, rect, radius, rect, [x, x + w], C.muted, 0, t, seed, 1, false); + let left = x; + const cuts: Array<{ at: number; prev: string; next: string; k: number }> = []; + let last: { color: string; k: number } | null = null; + for (let i = 0; i < parts.length; i += 1) { + const part = parts[i]; + const target = Math.min(1, Math.max(0, part.share)) * w; + const width = Math.min(Math.max(target, 0), x + w - left); + if (width < 0.5) continue; + const dim = focus !== null && focus !== "none" && focus !== i; + const k = dim ? 0.3 : 1; + ctx.save(); + ctx.beginPath(); + ctx.rect(left, y - 3, width, h + 6); + ctx.clip(); + glassBody(ctx, rect, radius, part.color, k); + paintCells(ctx, rect, radius, rect, [left, left + width], part.color, energy, t, seed + i * 97, k, true); + glassRim(ctx, rect, radius, part.color, k); + ctx.restore(); + if (last) cuts.push({ at: left, prev: last.color, next: part.color, k: Math.min(last.k, k) }); + last = { color: part.color, k }; + left += width; + } + for (const cut of cuts) { + const { at, prev, next, k } = cut; + const blend = Math.min(5, Math.max(2, h * 0.3)); + const grad = ctx.createLinearGradient(at - blend, 0, at + blend, 0); + grad.addColorStop(0, alpha(next, 0)); + grad.addColorStop(0.5, alpha(mix(prev, next, 0.5), 0.22 * k)); + grad.addColorStop(1, alpha(prev, 0)); + ctx.fillStyle = grad; + ctx.fillRect(at - blend, y + 1.5, blend * 2, h - 3); + ctx.strokeStyle = alpha(C.faint, 0.9 * Math.max(k, 0.6)); + ctx.lineWidth = 2.4; + ctx.beginPath(); + ctx.moveTo(at, y + 1); + ctx.lineTo(at, y + h - 1); + ctx.stroke(); + for (const [dx, col] of [[-1.7, prev], [1.7, next]] as const) { + ctx.strokeStyle = alpha(mix(col, "#ffffff", 0.5), 0.8 * k); + ctx.lineWidth = 1; + ctx.beginPath(); + ctx.moveTo(at + dx, y + 2); + ctx.lineTo(at + dx, y + h - 2); + ctx.stroke(); + } + } + // 已用部分末端的带光亮边。 + const tail = last as { color: string; k: number } | null; + if (tail && left < x + w - Math.max(radius, 1.5) && left > x + radius) { + glowDot(ctx, left, y + h / 2, h * 0.7, alpha(tail.color, 0.22 * tail.k)); + ctx.strokeStyle = alpha(mix(tail.color, "#ffffff", 0.55), tail.k); + ctx.lineWidth = 1.4; + ctx.beginPath(); + ctx.moveTo(left, y + 1.5); + ctx.lineTo(left, y + h - 1.5); + ctx.stroke(); + } +} + +/** core_bars(rich):每核一只迷你液位 + 最近 10 秒峰值横线 + 高温过渡。 */ +export function paintCoreBars( + ctx: CanvasRenderingContext2D, + rect: Rect, + loads: number[], + peaks: number[], + shown: number[], + t: number, + maxCols: number, +) { + const { x, y, w, h } = rect; + const group = Math.max(1, Math.ceil(loads.length / maxCols)); + const cols: number[] = []; + const colPeaks: number[] = []; + for (let g = 0; g < loads.length; g += group) { + const chunk = loads.slice(g, g + group); + cols.push(chunk.reduce((s, v) => s + v, 0) / chunk.length); + } + for (let g = 0; g < loads.length; g += group) { + const chunk = peaks.slice(g, g + group); + colPeaks.push(chunk.length ? Math.max(...chunk) : 0); + } + const values = cols.length ? cols : new Array(8).fill(0); + const peakValues = cols.length ? colPeaks : new Array(8).fill(0); + const slot = w / values.length; + const bar = Math.max(slot * 0.62, 1.5); + values.forEach((load, i) => { + const bx = x + slot * i + (slot - bar) / 2; + const value = shown[i] ?? load; + paintTank(ctx, { x: bx, y, w: bar, h }, value, loadColor(C.cpu, value), t, 11 + i * 7); + const peak = Math.max(peakValues[i] ?? 0, value); + if (peak - value > 3 && h > 12) { + const py = y + h - Math.min(Math.max((h * peak) / 100, 1.5), h - 1.5); + ctx.strokeStyle = alpha(mix(loadColor(C.cpu, value), "#ffffff", 0.5), 0.75); + ctx.lineWidth = 1.2; + ctx.beginPath(); + ctx.moveTo(bx + 1.2, py); + ctx.lineTo(bx + bar - 1.2, py); + ctx.stroke(); + } + }); +} + +/** 共享画布挂点:尺寸自适应 + 每帧 clear + dpr。 */ +export function setupCanvas(canvas: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; w: number; h: number } | null { + const parent = canvas.parentElement; + if (!parent) return null; + const w = parent.clientWidth; + const h = parent.clientHeight; + if (w < 2 || h < 2) return null; + const dpr = Math.min(2, window.devicePixelRatio || 1); + if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { + canvas.width = Math.round(w * dpr); + canvas.height = Math.round(h * dpr); + canvas.style.width = `${w}px`; + canvas.style.height = `${h}px`; + } + const ctx = canvas.getContext("2d"); + if (!ctx) return null; + ctx.setTransform(dpr, 0, 0, dpr, 0, 0); + ctx.clearRect(0, 0, w, h); + return { ctx, w, h }; +} + +export const PALETTE = C; +export { parseColor }; diff --git a/frontend/src/compute/format.ts b/frontend/src/compute/format.ts new file mode 100644 index 0000000..cb87270 --- /dev/null +++ b/frontend/src/compute/format.ts @@ -0,0 +1,41 @@ +export function formatBytes(value: number): string { + const units = ["B", "KB", "MB", "GB", "TB"]; + let size = value; + let unit = 0; + while (size >= 1024 && unit < units.length - 1) { + size /= 1024; + unit += 1; + } + return `${size.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`; +} + +export function formatRate(bytesPerSecond: number | null | undefined): string { + if (bytesPerSecond == null) return "—"; + return `${formatBytes(bytesPerSecond)}/s`; +} + +export function formatUptime(seconds: number | null | undefined): string { + if (!seconds) return "—"; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + return days ? `${days} 天 ${hours} 小时` : `${hours} 小时 ${Math.floor((seconds % 3600) / 60)} 分钟`; +} + +export function formatLinkSpeed(mbps: number | null | undefined): string { + if (!mbps) return "—"; + return mbps >= 1000 ? `${(mbps / 1000).toFixed(1)} Gbps` : `${mbps} Mbps`; +} + +export function formatClock(epochSeconds: number): string { + return new Date(epochSeconds * 1000).toLocaleTimeString("zh-CN", { hour12: false }); +} + +/** Round a data maximum up to a 1/2/5×10^n axis ceiling. */ +export function niceCeil(value: number): number { + if (value <= 0) return 1; + const exponent = Math.floor(Math.log10(value)); + const base = Math.pow(10, exponent); + const unit = value / base; + const step = unit <= 1 ? 1 : unit <= 2 ? 2 : unit <= 5 ? 5 : 10; + return step * base; +} diff --git a/frontend/src/compute/palette.ts b/frontend/src/compute/palette.ts new file mode 100644 index 0000000..2198de6 --- /dev/null +++ b/frontend/src/compute/palette.ts @@ -0,0 +1,102 @@ +import type { ResourceKey } from "./types"; + +export type ThemeMode = "light" | "dark"; + +/** 岛仔原色(深底霓虹):每类硬件一种主色,次级读数取主色的浅色(mix with INK)。 */ +const DARK_PALETTE = { + cpu: "#63dacf", + gpu: "#ab9cf5", + ram: "#e9bd75", + net: "#6eb2fa", + disk: "#f092aa", + ink: "#ecf0f4", + muted: "#969ea8", + faint: "#626872", + grid: "#2c3037", + surface: "#181a1e", + raised: "#24272d", + hot: "#ff8066", + kernel: "#f68a68", + free: "#3a3e46", +}; + +/** 浅底翻色:主色压深两档保持「深霓虹」质感,中性色走 slate 阶梯。与 styles.css 浅色 token 块一一对应。 */ +const LIGHT_PALETTE = { + cpu: "#0f9e8e", + gpu: "#7c5cd6", + ram: "#c88a1f", + net: "#3b82f6", + disk: "#db5a8a", + ink: "#101a2c", + muted: "#64748b", + faint: "#94a3b8", + grid: "#d9dfe9", + surface: "#eef2f7", + raised: "#ffffff", + hot: "#e5484d", + kernel: "#e8590c", + free: "#dde4ee", +}; + +/** 活动调色板:canvas 每帧实时读取,主题切换即全局换色。 */ +export const C: Record = { ...DARK_PALETTE }; + +export const RESOURCE_HEX: Record = { + cpu: C.cpu, + gpu: C.gpu, + memory: C.ram, + disk: C.disk, + network: C.net, +}; + +/** 主题切换时同步换色(对象原地变异,import 方无需感知)。 */ +export function setPalette(mode: ThemeMode) { + Object.assign(C, mode === "light" ? LIGHT_PALETTE : DARK_PALETTE); + RESOURCE_HEX.cpu = C.cpu; + RESOURCE_HEX.gpu = C.gpu; + RESOURCE_HEX.memory = C.ram; + RESOURCE_HEX.disk = C.disk; + RESOURCE_HEX.network = C.net; +} + +/** 解析 #hex 或 rgb()/rgba() 串——mix 的结果还能再进 mix。 */ +export function parseColor(color: string): [number, number, number] { + if (color.startsWith("#")) { + const clean = color.replace("#", ""); + return [parseInt(clean.slice(0, 2), 16), parseInt(clean.slice(2, 4), 16), parseInt(clean.slice(4, 6), 16)]; + } + const nums = color.match(/[\d.]+/g)?.map(Number) ?? [0, 0, 0]; + return [nums[0], nums[1], nums[2]]; +} + +/** paint::mix —— 岛仔所有过渡色都由它生成。 */ +export function mix(colorA: string, colorB: string, k: number): string { + const t = Math.min(1, Math.max(0, k)); + const [r1, g1, b1] = parseColor(colorA); + const [r2, g2, b2] = parseColor(colorB); + return `rgb(${Math.round(r1 + (r2 - r1) * t)}, ${Math.round(g1 + (g2 - g1) * t)}, ${Math.round(b1 + (b2 - b1) * t)})`; +} + +export function alpha(color: string, a: number): string { + const [r, g, b] = parseColor(color); + return `rgba(${r}, ${g}, ${b}, ${Math.min(1, Math.max(0, a)).toFixed(3)})`; +} + +/** 次级读数色(上传、写入)。 */ +export function secondary(color: string): string { + return mix(color, C.ink, 0.5); +} + +/** 温度着色:≥85 热红、≥75 琥珀、其余墨色。 */ +export function temperatureColor(temp: number | null | undefined): string { + if (temp == null) return C.muted; + if (temp >= 85) return C.hot; + if (temp >= 75) return C.ram; + return C.ink; +} + +/** 负载着色:≥85% 起向热红过渡(岛仔 core_bars)。 */ +export function loadColor(base: string, load: number): string { + if (load < 85) return base; + return mix(base, C.hot, Math.min(1, (load - 85) / 15)); +} diff --git a/frontend/src/compute/types.ts b/frontend/src/compute/types.ts new file mode 100644 index 0000000..eaccbcc --- /dev/null +++ b/frontend/src/compute/types.ts @@ -0,0 +1,95 @@ +export type ResourceKey = "cpu" | "gpu" | "memory" | "disk" | "network"; + +export type SystemMetrics = { + source: "local"; + connection_status: "connected" | "unavailable" | "sampling"; + captured_at: string | null; + server: { + id: number | null; + name: string; + platform: string; + cpu_names: string[]; + gpu_names: string[]; + uptime_seconds: number | null; + last_active: string | null; + is_online: boolean; + } | null; + cpu: { + percent: number; + percpu?: number[]; + frequency_mhz?: number | null; + cores: number | null; + cores_physical?: number | null; + cpu_names?: string[]; + load_1m: number | null; + user_percent?: number | null; + system_percent?: number | null; + } | null; + memory: { + used_bytes: number; + total_bytes: number; + percent: number; + available_bytes?: number; + cached_bytes?: number; + buffered_bytes?: number; + shared_bytes?: number; + } | null; + disk: { + path: string; + used_bytes: number; + total_bytes: number; + percent: number; + read_bps?: number | null; + write_bps?: number | null; + active_percent?: number | null; + } | null; + disks?: Array<{ path: string; mountpoint: string; fstype: string; percent: number; used_bytes: number; total_bytes: number }>; + gpus: Array<{ + index: number; + name: string; + utilization: number | null; + memory_used_mb?: number | null; + memory_total_mb?: number | null; + temperature_c?: number | null; + encoder_pct?: number | null; + decoder_pct?: number | null; + power_w?: number | null; + power_limit_w?: number | null; + graphics_clock_mhz?: number | null; + memory_clock_mhz?: number | null; + processes?: Array<{ pid: number; name: string; memory_mb: number }>; + }>; + network: { + in_bytes_per_second: number; + out_bytes_per_second: number; + received_bytes_total?: number; + sent_bytes_total?: number; + per_nic?: Array<{ name: string; rx_bps: number; tx_bps: number; link_mbps: number | null }>; + } | null; + processes?: { cpu: ProcessInfo[]; memory: ProcessInfo[]; io?: ProcessInfo[] }; + temperatures: Array<{ name: string; temperature: number }>; + error: string | null; +}; + +export type ProcessInfo = { + pid: number; + name: string; + user: string; + cpu_percent: number; + memory_bytes: number; + io_bytes_per_second?: number; +}; + +export type HistorySample = { + t: number; + cpu: number | null; + percpu: number[] | null; + gpu: number | null; + mem: number | null; + disk_read: number | null; + disk_write: number | null; + net_in: number | null; + net_out: number | null; +}; + +export type HistoryResponse = { window_seconds: number; samples: HistorySample[] }; diff --git a/frontend/src/compute/widgets.tsx b/frontend/src/compute/widgets.tsx new file mode 100644 index 0000000..9edb93a --- /dev/null +++ b/frontend/src/compute/widgets.tsx @@ -0,0 +1,332 @@ +import { useEffect, useId, useRef } from "react"; +import type { CSSProperties, MouseEvent as ReactMouseEvent, ReactNode } from "react"; +import { alpha, C, mix, parseColor } from "./palette"; +import { SHIMMER_MS, paintCoreBars, paintGlassBar, paintTank, setupCanvas, subscribeFrame, useSmoothed } from "./dynamics"; +import type { BarPart } from "./dynamics"; + +export function bounded(value: number | null | undefined): number { + return Math.min(100, Math.max(0, value ?? 0)); +} + +/** + * 画布基座:挂到共享 rAF 帧调度器。液面/宽度仍在滑移时满帧重绘(顺滑插值), + * 静止后退回 90ms 颗粒闪烁节奏(岛仔 SHIMMER),隐藏标签页时由调度器暂停。 + */ +function CellCanvas({ draw, className, style, ariaLabel, onMouseMove, onMouseLeave }: { + draw: (ctx: CanvasRenderingContext2D, w: number, h: number, dt: number, t: number) => boolean; + className?: string; + style?: CSSProperties; + ariaLabel?: string; + onMouseMove?: (event: ReactMouseEvent, width: number) => void; + onMouseLeave?: () => void; +}) { + const ref = useRef(null); + const drawRef = useRef(draw); + drawRef.current = draw; + useEffect(() => { + const canvas = ref.current; + if (!canvas) return; + let moving = true; + let lastPaint = 0; + return subscribeFrame((dt, t) => { + const now = performance.now(); + if (!moving && now - lastPaint < SHIMMER_MS) return; + lastPaint = now; + const prepared = setupCanvas(canvas); + if (!prepared) return; + moving = drawRef.current(prepared.ctx, prepared.w, prepared.h, dt, t); + }); + }, []); + return ( +
onMouseMove(event, event.currentTarget.clientWidth) : undefined} + onMouseLeave={onMouseLeave} + > + +
+ ); +} + +/** 岛仔大环:主色淡轨道 + 进度弧 + 细亮芯 + 末端收在轨道宽内的光点。 */ +export function RingGauge({ value, label, color, big, unit }: { value: number | null; label: string; color: string; big?: ReactNode; unit?: ReactNode }) { + const shown = useSmoothed(value, 0.45); + const radius = 44; + const circumference = 2 * Math.PI * radius; + const percent = shown == null ? 0 : bounded(shown); + const width = 7; + const endAngle = -Math.PI / 2 + (percent / 100) * Math.PI * 2; + const tipX = 55 + radius * Math.cos(endAngle); + const tipY = 55 + radius * Math.sin(endAngle); + return ( +
+ + + {percent > 0.4 && ( + <> + + + + + + )} + +
+ {big ?? (value == null ? "—" : `${Math.round(percent)}%`)} + {unit && {unit}} +
+
+ ); +} + +function linePoints(values: (number | null)[], yOf: (f: number) => number, count: number): string[] { + const out: string[] = []; + values.forEach((value, index) => { + if (value == null || count < 2) return; + const f = Math.min(1, Math.max(0, value)); + out.push(`${((index / (count - 1)) * 100).toFixed(2)},${yOf(f).toFixed(2)}`); + }); + return out; +} + +/** + * 60 秒霓虹面积图(岛仔 trend):宽淡→中亮→白芯三层、向基线渐隐填充、 + * 50% 参考线 + 底线,末端「现在」光点呼吸。values 传入已按 max 归一前的原值。 + */ +export function NeonTrend({ values, max, color, height = 56, fill = 0.3, midline = false, now = true, width = 1.5 }: { + values: (number | null)[]; + max: number; + color: string; + height?: number; + fill?: number; + midline?: boolean; + now?: boolean; + width?: number; +}) { + const gradientId = useId(); + const scale = (value: number | null) => (value == null ? null : value / (max || 1)); + const scaled = values.map(scale); + const points = linePoints(scaled as (number | null)[], (f) => 2 + (1 - f) * (height - 4), values.length); + const tip = points.length ? points[points.length - 1].split(",").map(Number) : null; + return ( +
+ + + + + + + + {midline && } + + {fill > 0 && points.length > 1 && ( + + )} + {points.length > 1 && ( + <> + + + + + )} + + {now && tip && } +
+ ); +} + +function secondaryOf(color: string): string { + const [r1, g1, b1] = parseColor(color); + const [r2, g2, b2] = parseColor(C.ink); + return `rgb(${Math.round((r1 + r2) / 2)}, ${Math.round((g1 + g2) / 2)}, ${Math.round((b1 + b2) / 2)})`; +} + +/** 上下镜像图(岛仔 mirror):上半主读数向上、下半次读数向下,共用中轴。 */ +export function MirrorTrend({ up, down, max, color, height = 96 }: { up: (number | null)[]; down: (number | null)[]; max: number; color: string; height?: number }) { + const gradientId = useId(); + const half = (height - 4) / 2; + const midY = 2 + half; + const upPts = linePoints(up.map((v) => (v == null ? null : v / (max || 1))), (f) => midY - f * (half - 2), up.length); + const downPts = linePoints(down.map((v) => (v == null ? null : v / (max || 1))), (f) => midY + 2 + f * (half - 2), down.length); + const upTip = upPts.length ? upPts[upPts.length - 1].split(",").map(Number) : null; + const secondaryColor = secondaryOf(color); + return ( +
+ + + + + + + + + {upPts.length > 1 && ( + <> + + + + + )} + {downPts.length > 1 && ( + <> + + + + )} + + {upTip && } +
+ ); +} + +/** 竖向玻璃液位舱(连续滑移,满帧插值)。 */ +export function Tank({ value, color, seed, label }: { value: number | null; color: string; seed: number; label: string }) { + const current = useRef(value ?? 0); + const target = useRef(value ?? 0); + target.current = value ?? 0; + return ( + { + const gap = target.current - current.current; + const moving = Math.abs(gap) > 0.08; + current.current += gap * (1 - Math.exp(-(dt / 0.5) * 4)); + paintTank(ctx, { x: 0, y: 0, w, h }, current.current, color, t, seed); + return moving; + }} + /> + ); +} + +/** 分段玻璃构成条:宽度逐帧生长、跨段连续颗粒、悬停回调供聚焦。 */ +export function GlassBar({ parts, energy, seed, height = 22, focus, onHover }: { + parts: BarPart[]; + energy: number; + seed: number; + height?: number; + focus?: number | null; + onHover?: (index: number | null) => void; +}) { + const targets = parts.map((part) => Math.min(1, Math.max(0, part.share))); + const current = useRef(targets.slice()); + if (current.current.length !== targets.length) current.current = targets.slice(); + const total = targets.reduce((s, v) => s + v, 0); + return ( + { + const k = 1 - Math.exp(-(dt / 0.5) * 4); + let moving = false; + current.current = current.current.map((v, i) => { + const goal = targets[i] ?? 0; + if (Math.abs(goal - v) > 0.0008) moving = true; + return v + (goal - v) * k; + }); + paintGlassBar(ctx, { x: 0.5, y: (h - Math.min(h, height)) / 2, w: w - 1, h: Math.min(h, height) }, parts.map((part, i) => ({ share: current.current[i] ?? 0, color: part.color })), focus ?? null, energy, t, seed); + return moving; + }} + onMouseMove={onHover ? (event, width) => { + const at = event.clientX - event.currentTarget.getBoundingClientRect().left; + const share = total > 0 ? at / width : 0; + let acc = 0; + for (let i = 0; i < targets.length; i += 1) { + acc += targets[i]; + if (share <= acc / Math.max(total, 1)) { + onHover(i); + return; + } + } + onHover(targets.length - 1); + } : undefined} + onMouseLeave={onHover ? () => onHover(null) : undefined} + /> + ); +} + +/** 逐核迷你液位阵:满帧滑移 + 每核峰值横线 + ≥85% 转热。 */ +export function CoreBars({ values, peaks, height = 26, maxCols = 32 }: { values: number[] | null; peaks: number[] | null; height?: number; maxCols?: number }) { + const loads = values ?? []; + const current = useRef(loads.slice()); + if (current.current.length !== loads.length) current.current = loads.slice(); + return ( + { + const k = 1 - Math.exp(-(dt / 0.45) * 4); + let moving = false; + current.current = current.current.map((v, i) => { + const goal = loads[i] ?? 0; + if (Math.abs(goal - v) > 0.4) moving = true; + return v + (goal - v) * k; + }); + paintCoreBars(ctx, { x: 0, y: 0, w, h }, loads, peaks ?? [], current.current, t, maxCols); + return moving; + }} + /> + ); +} + +export interface RankRow { + name: string; + sub?: string; + text: string; + share: number; +} + +/** 详情页程序列表(program_rows):字母位 + 名称 + 发光细条带亮点端 + 数值;行悬停回调。 */ +export function ProgramRows({ rows, color, empty, onHover }: { rows: RankRow[]; color: string; empty: string; onHover?: (index: number | null) => void }) { + if (!rows.length) return
{empty}
; + const top = Math.max(rows[0].share, 0.0001); + return ( +
+ {rows.map((row, index) => { + const tint = mix(color, C.surface, Math.min(0.56, index * 0.14)); + const len = Math.min(1, Math.max(0.04, row.share / top)) * 100; + return ( +
onHover?.(index)} onMouseLeave={() => onHover?.(null)}> + {(row.name.trim()[0] ?? "?").toUpperCase()} + {row.name} + + + + + + {row.text} +
+ ); + })} +
+ ); +} + +/** 总览底部程序表(programs_table):整行液位条、名次渐淡、末端亮边。 */ +export function RankPanel({ title, rows, color, empty }: { title: string; rows: RankRow[]; color: string; empty: string }) { + const top = Math.max(rows[0]?.share ?? 1, 0.0001); + return ( +
+
{title}
+ {!rows.length ?
{empty}
: rows.slice(0, 4).map((row, index) => { + const share = Math.min(1, Math.max(0.04, row.share / top)); + const k = 1 - index * 0.16; + return ( +
+ + + + {(row.name.trim()[0] ?? "?").toUpperCase()} + {row.name} + {row.text} +
+ ); + })} +
+ ); +} diff --git a/frontend/src/main.tsx b/frontend/src/main.tsx index 46ce20d..454831a 100644 --- a/frontend/src/main.tsx +++ b/frontend/src/main.tsx @@ -2,6 +2,10 @@ import React from "react"; import ReactDOM from "react-dom/client"; import App from "./App"; import "./styles.css"; +import { applyTheme, resolveTheme } from "./theme"; + +// 首帧前定色:CSS 分支与 canvas 调色板先于任何渲染就位,避免主题闪烁。 +applyTheme(resolveTheme()); ReactDOM.createRoot(document.getElementById("root")!).render( diff --git a/frontend/src/styles.css b/frontend/src/styles.css index f3df9ef..aa40690 100644 --- a/frontend/src/styles.css +++ b/frontend/src/styles.css @@ -117,7 +117,8 @@ h2 { margin: 0; font: 600 17px Manrope, sans-serif; letter-spacing: -.02em; } .restart-button { width: 34px; height: 33px; display: grid; place-items: center; border: 1px solid var(--line); border-radius: 6px; background: #151e26; color: #87959e; } .restart-button:hover { color: var(--green); border-color: rgba(114,224,180,.28); } .add-card { min-height: 280px; padding: 24px; display: flex; align-items: center; justify-content: center; flex-direction: column; gap: 9px; border: 1px dashed rgba(144,163,177,.2); border-radius: 11px; background: rgba(14,21,28,.42); color: #9aa8b1; transition: .18s ease; } -.add-card:hover { border-color: rgba(114,224,180,.42); background: rgba(57,172,128,.045); } +.add-card:hover:not(:disabled) { border-color: rgba(114,224,180,.42); background: rgba(57,172,128,.045); } +.add-card:disabled { opacity: .55; cursor: not-allowed; } .add-card-icon { width: 39px; height: 39px; margin-bottom: 3px; display: grid; place-items: center; border: 1px solid rgba(114,224,180,.22); border-radius: 11px; color: var(--green); background: rgba(57,172,128,.09); } .add-card strong { font-size: 11px; font-weight: 600; } .add-card>span:last-child { color: #71808a; font-size: 9px; } @@ -239,6 +240,17 @@ h1 { color: #182234; margin: 12px 0 7px; font-size: clamp(29px, 3vw, 37px); lett .connection-badge.connected { border-color: #d5efe4; color: #12845f; background: #f2fbf7; } .online-dot { background: #19ad7d; box-shadow: 0 0 0 3px rgba(25,173,125,.1); } .offline-dot { background: #e59b49; box-shadow: 0 0 0 3px rgba(229,155,73,.11); } +/* A slow halo makes live/offline states visible without drawing attention from the data. */ +.online-dot:not(.offline-dot), .host-state.online span, .log-live i { animation: status-pulse 2s ease-out infinite; } +.online-dot.offline-dot { animation: status-pulse-wait 2.4s ease-out infinite; } +@keyframes status-pulse { + 0%, 100% { box-shadow: 0 0 0 0 rgba(20, 163, 119, .24); } + 55% { box-shadow: 0 0 0 5px rgba(20, 163, 119, 0); } +} +@keyframes status-pulse-wait { + 0%, 100% { box-shadow: 0 0 0 0 rgba(229, 155, 73, .22); } + 55% { box-shadow: 0 0 0 5px rgba(229, 155, 73, 0); } +} .primary-button { min-height: 38px; padding: 0 14px; border-color: #14966d; border-radius: 8px; background: linear-gradient(130deg, #16ad7c, #0c916a); color: #fff; font-size: 11px; box-shadow: 0 5px 13px rgba(17,151,107,.18); } .primary-button:hover { background: #087e5a; } .metrics-row { gap: 14px; margin: 27px 0 8px; } @@ -277,7 +289,8 @@ h1 { color: #182234; margin: 12px 0 7px; font-size: clamp(29px, 3vw, 37px); lett .chart-axis { position: absolute; inset: 4px auto 0 0; display: flex; flex-direction: column; justify-content: space-between; color: #a1a9b4; font: 8px var(--mono); } .trend-chart { width: 100%; height: 100%; overflow: visible; } .chart-gridline { stroke: #edf0f4; stroke-width: .35; stroke-dasharray: 1.5 1.5; } -.chart-line { fill: none; stroke-width: 1.3; vector-effect: non-scaling-stroke; stroke-linecap: round; stroke-linejoin: round; } +.chart-line { fill: none; stroke-width: 1.3; vector-effect: non-scaling-stroke; stroke-linecap: round; stroke-linejoin: round; animation: chart-refresh .35s ease-out both; } +@keyframes chart-refresh { from { opacity: .55; } to { opacity: 1; } } .cpu-line { stroke: #13a879; } .memory-line { stroke: #9273eb; } .gpu-line { stroke: #5797ed; } @@ -481,3 +494,701 @@ h2 { font-family: inherit; font-size: 16px; } .runtime-kpi-icon { width: 30px; height: 30px; } .runtime-table th, .runtime-table td { padding: 10px 12px; } } + +/* Keep the application shell in the viewport and scroll long page content locally. */ +html, body, #root { width: 100%; height: 100%; overflow: hidden; } +body { min-height: 0; } +.shell { width: 100%; height: 100dvh; min-height: 0; overflow: hidden; } +.rail { height: 100%; min-height: 0; } +.workspace { height: 100%; min-height: 0; display: flex; flex-direction: column; overflow: hidden; } +.topbar { flex: 0 0 64px; } +.content { width: min(1360px, 100%); height: auto; min-height: 0; flex: 1; margin: 0 auto; display: flex; flex-direction: column; overflow: hidden; } +.page-body { min-height: 0; flex: 1; overflow: hidden; display: flex; flex-direction: column; } +.footer { flex: 0 0 auto; margin-top: auto; } + +/* Keep service controls visible while only the growing card collection scrolls. */ +.page-body-services .page-hero, +.page-body-services .section-heading { flex: 0 0 auto; } +.service-list-scroll { min-height: 0; flex: 1; overflow: auto; padding: 0 2px 8px; scrollbar-gutter: stable; } +.service-list-scroll .app-grid { padding-bottom: 4px; } + +/* The runtime table scrolls inside its panel when the service list grows. */ +.page-body-runtime .page-hero, +.page-body-runtime .runtime-kpis { flex: 0 0 auto; } +.page-body-runtime .runtime-panel { min-height: 0; flex: 1; display: flex; flex-direction: column; } +.page-body-runtime .runtime-table-wrap { min-height: 0; flex: 1; overflow: auto; } +.runtime-table th:nth-child(3), .runtime-table td:nth-child(3) { min-width: 90px; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; } + +/* 算力页一页式布局:压缩外层留白,把页签占掉的高度还回来。 */ +.content:has(.page-body-compute) { display: flex; flex-direction: column; flex: 1; min-height: 0; padding-top: 18px; padding-bottom: 14px; } +.page-body-compute .page-hero, +.page-body-compute .metrics-row, +.page-body-compute .monitor-caption { flex: 0 0 auto; } +.page-body-compute .monitor-grid { + min-height: 0; + /* Size the row to its content, then keep both panels aligned to that row. */ + flex: 0 0 auto; + align-items: stretch; + margin-bottom: 0; +} +.page-body-compute .trend-panel, +.page-body-compute .host-panel { min-height: 0; } +.log-live { margin-left: auto; display: inline-flex; align-items: center; gap: 6px; color: #0f766e; font: 10px system-ui, sans-serif; white-space: nowrap; } +.log-live i { width: 6px; height: 6px; border-radius: 50%; background: #14b8a6; } +.terminal-head .log-live + button { margin-left: 4px; } +.log-error { padding: 8px 14px; color: #b91c1c; background: #fef2f2; font-size: 11px; } +.logs-modal { height: min(76vh, 760px); max-height: calc(100dvh - 36px); display: flex; flex-direction: column; overflow: hidden; } +.logs-modal .log-output { flex: 1; min-height: 0; max-height: none; } + +@media (prefers-reduced-motion: reduce) { + .online-dot, .host-state.online span, .log-live i, .chart-line { animation: none; } + .resource-track span { transition: none; } +} + +@media (max-width: 680px) { + .topbar { flex-basis: 56px; } + .content { padding: 20px 14px 12px; } + .page-body-services .page-hero { margin-bottom: 15px; } + .page-body-services .section-heading { margin-bottom: 10px; } + .page-body-runtime .runtime-panel { overflow: hidden; } + .terminal-head { flex-wrap: wrap; } + .terminal-head .log-live { margin-left: auto; } + .terminal-head .log-live + button { margin-left: 0; } +} + +/* ============================================================ + Compute monitor — dark glass surface borrowing the xiaotang-daozai + performance island: overview cards open per-resource detail views + with ring gauges, neon sparklines, per-core bars and process ranks. + Scoped entirely to .cmp-* so the light control plane is untouched. + ============================================================ */ +:root { + /* 岛仔原色板:hardware accent + neutral ink ramp. */ + --c-cpu: #63dacf; + --c-gpu: #ab9cf5; + --c-mem: #e9bd75; + --c-disk: #f092aa; + --c-net: #6eb2fa; + --cmp-line: rgba(236, 240, 244, .09); + --cmp-muted: #969ea8; + --cmp-faint: #626872; + /* 语义化主题 token:深色为默认值,html[data-theme=light] 在文件尾整组翻转。 */ + --cmp-ink: #ecf0f4; + --cmp-label: #aab2bc; + --cmp-dim: #6f8299; + --cmp-value: #b9c9dc; + --cmp-gridline: #2c3037; + --cmp-fill-1: rgba(255, 255, 255, .035); + --cmp-fill-2: rgba(255, 255, 255, .055); + --cmp-fill-3: rgba(255, 255, 255, .085); + --cmp-plate: rgba(36, 39, 45, .92); + --cmp-shadow: rgba(3, 9, 20, .38); + --cmp-edge: rgba(148, 180, 220, .14); + --cmp-edge-strong: rgba(148, 180, 220, .25); + --cmp-scroll: rgba(150, 158, 168, .3); + --cmp-ok-text: #9fe6cf; + --cmp-ok-icon: #7fd4b8; + --cmp-ok-dot: #4ade9e; + --cmp-ok-edge: rgba(84, 220, 175, .3); + --cmp-ok-soft: rgba(84, 220, 175, .1); + --cmp-ok-bg: rgba(40, 190, 140, .08); + --cmp-ok-glow: rgba(74, 222, 158, .8); + --cmp-warn-text: #f2cd93; + --cmp-warn-dot: #f0b45c; + --cmp-warn-edge: rgba(240, 180, 92, .28); + --cmp-warn-glow: rgba(240, 180, 92, .7); + --cmp-warn-bg: rgba(240, 180, 92, .07); +} + +.cmp-surface { + position: relative; + flex: 1; + min-height: 0; + /* 一页式监控屏:桌面视口内不滚动(窄屏在下方 media 恢复滚动)。 */ + overflow: hidden; + border-radius: 18px; + padding: 14px clamp(14px, 2.2vw, 26px) 20px; + color: var(--cmp-ink); + background: + radial-gradient(52% 58% at 8% -6%, rgba(38, 84, 148, .5), transparent 62%), + radial-gradient(44% 50% at 96% 2%, rgba(122, 74, 190, .32), transparent 58%), + radial-gradient(60% 58% at 58% 110%, rgba(14, 122, 130, .38), transparent 60%), + linear-gradient(168deg, #0b1322, #0a111d 48%, #0c1424); + border: 1px solid var(--cmp-edge); + box-shadow: 0 24px 60px var(--cmp-shadow), inset 0 1px 0 var(--cmp-fill-2); + scrollbar-width: thin; + scrollbar-color: var(--cmp-edge-strong) transparent; +} + +/* Shared glass material for every card and panel on the surface. */ +.cmp-card, .cmp-panel { + position: relative; + min-width: 0; + border: 1px solid var(--cmp-line); + border-radius: 16px; + background: linear-gradient(155deg, var(--cmp-fill-3), var(--cmp-fill-1) 55%, var(--cmp-fill-2)); + backdrop-filter: blur(16px) saturate(140%); + -webkit-backdrop-filter: blur(16px) saturate(140%); + box-shadow: 0 14px 34px var(--cmp-shadow), inset 0 1px 0 var(--cmp-fill-3); +} + +.cmp-kicker { display: block; margin-bottom: 4px; color: var(--cmp-dim); font: 9px var(--mono); letter-spacing: .12em; text-transform: uppercase; } +/* 采集状态胶囊:挂在全局顶栏(top-actions),算力页专属。 */ +.collect-pill { display: inline-flex; align-items: center; gap: 7px; padding: 6px 11px; border: 1px solid var(--cmp-edge); border-radius: 9px; color: var(--cmp-label); background: var(--cmp-fill-1); font-size: 11px; } +.collect-pill .cd { width: 7px; height: 7px; flex: 0 0 7px; border-radius: 50%; background: var(--cmp-warn-dot); box-shadow: 0 0 8px var(--cmp-warn-glow); } +.collect-pill.online { color: var(--cmp-ok-text); border-color: var(--cmp-ok-edge); background: var(--cmp-ok-bg); } +.collect-pill.online .cd { background: var(--cmp-ok-dot); box-shadow: 0 0 8px var(--cmp-ok-glow); } +.cmp-warning { display: flex; align-items: center; gap: 8px; margin-bottom: 14px; padding: 9px 12px; border: 1px solid var(--cmp-warn-edge); border-radius: 10px; color: var(--cmp-warn-text); background: var(--cmp-warn-bg); font-size: 11px; } + +/* 总览卡片:三张玻璃液位卡 + 两张霓虹吞吐窄卡(岛仔 overview 同构)。 */ +.cmp-cards { display: grid; grid-template-columns: repeat(6, minmax(0, 1fr)); gap: 11px; margin-bottom: 14px; } +.cmp-card.top { grid-column: span 2; grid-template-rows: auto minmax(0, 1fr) auto; align-content: stretch; } +.cmp-card.io { grid-column: span 3; } +.cmp-card { padding: 13px 14px 12px; display: grid; gap: 7px; align-content: start; cursor: pointer; transition: transform .18s ease, border-color .22s ease, box-shadow .22s ease, background .22s ease; } +.cmp-card.r-cpu { --card-color: var(--c-cpu); } +.cmp-card.r-gpu { --card-color: var(--c-gpu); } +.cmp-card.r-memory { --card-color: var(--c-mem); } +.cmp-card.r-disk { --card-color: var(--c-disk); } +.cmp-card.r-network { --card-color: var(--c-net); } +/* hover:浮起 + 主色描边 + 底边一道亮光(overview_card_frame)。 */ +.cmp-card:hover, .cmp-card:focus-visible { + transform: translateY(-2px); + outline: none; + border-color: color-mix(in srgb, var(--card-color) 52%, transparent); + box-shadow: 0 18px 40px var(--cmp-shadow), inset 0 1px 0 var(--cmp-fill-3); +} +.cmp-card::after { + content: ""; + position: absolute; + left: 14px; + right: 14px; + bottom: 1px; + height: 1.4px; + border-radius: 2px; + background: var(--card-color); + opacity: 0; + filter: blur(.4px); + box-shadow: 0 0 12px var(--card-color); + transition: opacity .22s ease; + pointer-events: none; +} +.cmp-card:hover::after, .cmp-card:focus-visible::after { opacity: .7; } +.cmp-card header { position: relative; display: flex; align-items: center; gap: 7px; min-width: 0; } +.cmp-card header b { font-size: 12px; font-weight: 500; color: var(--cmp-label); transition: color .2s ease; } +.cmp-card:hover header b { color: var(--cmp-ink); } +.cmp-card header em { + margin-left: auto; + color: var(--cmp-faint); + font-style: normal; + font-size: 9.5px; + white-space: nowrap; + font-variant-numeric: tabular-nums; +} +.cmp-dot { width: 5px; height: 5px; flex: 0 0 5px; border-radius: 50%; } +.cmp-big { overflow: hidden; color: var(--cmp-ink); font-size: 28px; line-height: 1.05; font-weight: 700; letter-spacing: -.03em; font-variant-numeric: tabular-nums; white-space: nowrap; } +.cmp-big small { margin-left: 2px; color: var(--cmp-muted); font-size: 11px; font-weight: 600; letter-spacing: 0; } +.cmp-sub { overflow: hidden; color: var(--cmp-muted); font-size: 10.5px; white-space: nowrap; font-variant-numeric: tabular-nums; } +.cmp-clip { display: inline-block; max-width: 100%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; vertical-align: bottom; } +.cmp-card-foot { overflow: hidden; color: var(--cmp-faint); font-size: 9.5px; white-space: nowrap; text-overflow: ellipsis; } +/* 卡体:左信息列 + 右竖向液位舱(tank 高 65→100%)。 */ +.cmp-card-main { position: relative; display: flex; gap: 12px; align-items: stretch; min-width: 0; } +/* 信息列纵向排布,底部条阵用 margin-top:auto 压到底——与右侧液位舱底边平齐,不悬空。 */ +.cmp-card-info { flex: 1; min-width: 0; display: flex; flex-direction: column; gap: 6px; } +.cmp-card-info .cmp-card-strip { padding-top: 2px; } +/* 曲线吃掉卡内剩余高度(Y 轴加高),下方文本与条阵自然沉到卡片底边。 */ +.cmp-card-info .cmp-trend { flex: 1 1 auto; min-height: 22px; } +.cmp-card-row { display: flex; justify-content: space-between; align-items: baseline; gap: 8px; } +.cmp-card-row span { color: var(--cmp-muted); font-size: 9.5px; } +.cmp-card-row b { color: var(--cmp-ink); font-size: 9.5px; font-weight: 700; font-variant-numeric: tabular-nums; } +.cmp-card-strip { min-width: 0; } +/* IO 窄卡:加高,读数一行压在一分钟曲线上方,曲线吃满卡片下半区。 */ +.cmp-card.io { padding: 12px 14px 0; gap: 4px; overflow: hidden; } +.cmp-io-chart { position: absolute; left: 10px; right: 10px; bottom: 4px; top: 52px; opacity: .9; pointer-events: none; } +.cmp-io-chart .cmp-trend { height: 100% !important; } +.cmp-io-values { position: relative; display: flex; gap: 26px; padding-top: 2px; } +.cmp-io-values span { display: inline-flex; align-items: baseline; gap: 5px; font-size: 12.5px; font-weight: 700; color: var(--cmp-ink); font-variant-numeric: tabular-nums; } +.cmp-io-values i { font-style: normal; font-size: 10px; font-weight: 700; } + +/* Panels (trend / host / process ranks). */ +.cmp-panels { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(300px, 1fr); gap: 14px; margin-bottom: 12px; align-items: stretch; } +.cmp-rank-row { grid-template-columns: repeat(2, minmax(0, 1fr)); } +.cmp-panel { padding: 12px 16px 13px; } +.cmp-panel-head { display: flex; justify-content: space-between; align-items: flex-start; gap: 10px; margin-bottom: 12px; } +.cmp-panel-head h3 { margin: 0; color: var(--cmp-ink); font-size: 14px; font-weight: 600; } +.cmp-panel-note { color: var(--cmp-dim); font-size: 10px; white-space: nowrap; } +.cmp-legend { display: flex; gap: 14px; margin: 2px 0 10px 58px; flex-wrap: wrap; } +.cmp-legend span { display: inline-flex; align-items: center; gap: 6px; color: var(--cmp-label); font-size: 10px; } +.cmp-legend i { width: 7px; height: 7px; border-radius: 50%; } + +.cmp-host-state { display: inline-flex; align-items: center; gap: 6px; color: var(--cmp-label); font-size: 10px; } +.cmp-host-state i { width: 6px; height: 6px; border-radius: 50%; background: var(--cmp-warn-dot); } +.cmp-host-state.online { color: var(--cmp-ok-text); } +.cmp-host-state.online i { background: var(--cmp-ok-dot); box-shadow: 0 0 7px var(--cmp-ok-glow); } +.cmp-host-identity { display: flex; align-items: center; gap: 10px; margin: 0 0 8px; padding: 8px 10px; border: 1px solid var(--cmp-line); border-radius: 12px; background: var(--cmp-fill-1); } +.cmp-host-symbol { width: 30px; height: 30px; flex: 0 0 30px; display: grid; place-items: center; border-radius: 9px; color: var(--cmp-ok-icon); background: var(--cmp-ok-soft); } +.cmp-host-identity>div { min-width: 0; display: grid; gap: 3px; } +.cmp-host-identity strong { overflow: hidden; color: var(--cmp-ink); font-size: 12px; text-overflow: ellipsis; white-space: nowrap; } +.cmp-host-identity span { overflow: hidden; color: var(--cmp-muted); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } +.cmp-host-details { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 14px; } +.cmp-host-details>div { min-width: 0; display: grid; gap: 3px; } +.cmp-host-details span { color: var(--cmp-dim); font-size: 10px; } +.cmp-host-details b { overflow: hidden; color: var(--cmp-value); font-size: 10px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; } +.cmp-empty-inline { padding: 18px 8px; color: var(--cmp-dim); font-size: 12px; text-align: center; } + +/* 顶部常规分页页签:图标 + 文字,选中底板滑动。 */ +.cmp-tabbar { flex: none; margin-bottom: 10px; } +.cmp-tabs { position: relative; min-width: 0; display: flex; gap: 6px; scrollbar-width: none; } +.cmp-tab-plate { + position: absolute; + top: 0; + bottom: 0; + left: 0; + width: calc((100% - 30px) / 6); + /* translateX 的 100% 是底板自身宽 = (容器-30)/6,一步 = 自身宽 + 间距。 */ + transform: translateX(calc(var(--tab-index, 0) * (100% + 6px))); + border: 1px solid; + border-radius: 10px; + background: var(--cmp-plate); + pointer-events: none; + transition: transform .22s ease; +} +.cmp-tab { + position: relative; /* 抬到 absolute 底板之上,避免文字被滑移底板盖住 */ + flex: 1; + min-width: 0; + height: 38px; + padding: 0 8px; + display: grid; + place-items: center; + border: 0; + border-radius: 10px; + background: transparent; + color: var(--cmp-label); + transition: color .18s ease; +} +.cmp-tab:hover { color: var(--cmp-ink); } +.cmp-tab.active { color: var(--cmp-ink); } +.cmp-tab-top { display: flex; align-items: center; gap: 6px; font-size: 12px; font-weight: 500; white-space: nowrap; } +.cmp-tab-top i { width: 4.5px; height: 4.5px; flex: 0 0 4.5px; border-radius: 50%; } +.cmp-tab-top svg { opacity: .85; } + +.cmp-detail-grid { display: grid; grid-template-columns: minmax(216px, 280px) minmax(0, 1fr); grid-template-areas: "left main" "left list"; gap: 14px; } +.cmp-col-left { grid-area: left; display: grid; gap: 16px; align-content: center; } +.cmp-col-main { grid-area: main; display: flex; flex-direction: column; min-height: 0; } +.cmp-col-list { grid-area: list; } +.cmp-rows { display: grid; gap: 6px; } +.cmp-row { display: flex; justify-content: space-between; align-items: center; gap: 10px; padding: 7px 10px; border: 1px solid var(--cmp-line); border-radius: 9px; background: var(--cmp-fill-1); } +.cmp-row span { flex: 0 0 auto; color: var(--cmp-label); font-size: 11px; } +.cmp-row b { overflow: hidden; color: var(--cmp-ink); font-size: 12px; font-weight: 600; text-overflow: ellipsis; white-space: nowrap; font-variant-numeric: tabular-nums; } +.cmp-main-label { display: flex; align-items: baseline; gap: 8px; margin: 15px 0 8px; } +.cmp-main-label:first-child { margin-top: 0; } +.cmp-main-label span { color: var(--cmp-label); font-size: 12px; font-weight: 600; } +.cmp-main-label small { color: var(--cmp-dim); font-size: 10px; } + +/* 大环仪表(hero + gauge):中心数字 + 单位行,末端光点呼吸。 */ +.cmp-gauge { position: relative; width: min(180px, 74%); margin: 4px auto 2px; aspect-ratio: 1; } +.cmp-gauge svg { width: 100%; height: 100%; } +.cmp-gauge-center { position: absolute; inset: 0; display: grid; place-content: center; justify-items: center; text-align: center; } +.cmp-gauge-center strong { color: var(--cmp-ink); font-size: 34px; font-weight: 700; letter-spacing: -.03em; line-height: 1; font-variant-numeric: tabular-nums; } +.cmp-gauge-unit { margin-top: 5px; color: var(--cmp-muted); font-size: 10.5px; } +.cmp-gauge-tip { animation: gauge-breathe 1.6s ease-in-out infinite; } +@keyframes gauge-breathe { 0%, 100% { opacity: 1; } 50% { opacity: .55; } } + +/* ---------- 岛仔元素:画布颗粒件、霓虹趋势、构成条、程序列表 ---------- */ + +/* 画布基座(液位舱 / 构成条 / 核心条阵共用)。 */ +.cmp-canvas { position: relative; width: 100%; } +.cmp-canvas canvas { display: block; } +.cmp-canvas.cmp-tankv { width: 24px; flex: 0 0 24px; align-self: stretch; min-height: 96px; } +.cmp-canvas.cmp-glassbar, .cmp-canvas.cmp-corebars { min-height: 10px; } +/* 详情主视图:曲线与核心条阵吃掉面板剩余高度,文本行沉到面板底,不悬空。 */ +.cmp-col-main > .cmp-trend { flex: 1.5 1 0; min-height: 80px; } +.cmp-col-main > .cmp-canvas.cmp-corebars { flex: 1 1 0; min-height: 62px; } + +/* 趋势区(trend / mirror / 迷你曲线共用):SVG 满铺 + 「现在」光点。 */ +.cmp-trend { position: relative; width: 100%; } +.cmp-trend svg { display: block; width: 100%; height: 100%; overflow: visible; } +.cmp-trend-mid { stroke: var(--cmp-gridline); stroke-width: .6; vector-effect: non-scaling-stroke; } +.cmp-trend-base { stroke: var(--cmp-gridline); stroke-width: 1; vector-effect: non-scaling-stroke; } +.cmp-now { + position: absolute; + width: 5.5px; + height: 5.5px; + margin: -2.75px 0 0 -2.75px; + border-radius: 50%; + animation: now-breathe 1.6s ease-in-out infinite; + pointer-events: none; +} +@keyframes now-breathe { 0%, 100% { filter: brightness(1); } 50% { filter: brightness(.55); } } + +/* 构成条容器:玻璃条 + 悬停程序的亮块 + 「可用」括号。 */ +.cmp-bar-wrap { position: relative; padding-bottom: 12px; } +.cmp-bar-span { + position: absolute; + top: 0; + height: 26px; + border: 1.2px solid; + border-radius: 3px; + background: var(--cmp-fill-2); + transition: left .14s ease, width .14s ease; + pointer-events: none; +} +.cmp-bracket { + position: absolute; + right: 0; + bottom: 4px; + height: 6px; + border-top: 1px solid; + border-left: 1px solid; + border-right: 1px solid; + border-radius: 2px 2px 0 0; + pointer-events: none; +} + +/* 详情页小节标题:左名称右淡色说明(section)。 */ +.cmp-sec-title { display: flex; justify-content: space-between; align-items: baseline; gap: 10px; margin: 11px 0 6px; } +.cmp-sec-title:first-child { margin-top: 0; } +.cmp-sec-title span { color: var(--cmp-muted); font-size: 10px; font-weight: 600; letter-spacing: .02em; } +.cmp-sec-title small { overflow: hidden; color: var(--cmp-faint); font-size: 10px; text-overflow: ellipsis; white-space: nowrap; } + +/* GPU 引擎/显存、磁盘分区行:标签 + 玻璃构成条 + 读数。 */ +.cmp-engine-row { display: grid; grid-template-columns: 74px minmax(0, 1fr) auto; gap: 10px; align-items: center; margin: 5px 0; } +.cmp-engine-row>span { overflow: hidden; color: var(--cmp-muted); font-size: 10.5px; text-overflow: ellipsis; white-space: nowrap; } +.cmp-engine-row b { color: var(--cmp-ink); font-size: 10.5px; font-weight: 700; font-variant-numeric: tabular-nums; white-space: nowrap; } +.cmp-gpu-model { margin: 12px 0 2px; color: var(--c-gpu); font-size: 10.5px; font-weight: 600; } + +/* 网卡启用以来的累计清单。 */ +.cmp-net-totals { display: grid; gap: 6px; } +.cmp-net-totals>div { display: flex; align-items: center; gap: 9px; } +.cmp-net-totals i { width: 3px; height: 9px; flex: 0 0 3px; border-radius: 1.5px; } +.cmp-net-totals span { color: var(--cmp-ink); font-size: 11px; } +.cmp-net-totals b { margin-left: auto; color: var(--cmp-ink); font-size: 11px; font-weight: 700; font-variant-numeric: tabular-nums; } + +/* 程序列表(program_rows):字母位 + 名称 + 发光细条(末端亮点)+ 数值。 */ +.cmp-procs { display: grid; gap: 3px; } +.cmp-proc { display: flex; align-items: center; gap: 9px; min-width: 0; padding: 4px 6px; border-radius: 6px; transition: background .15s ease; } +.cmp-proc:hover { background: var(--cmp-plate); } +.cmp-proc-mono { width: 14px; height: 14px; flex: 0 0 14px; display: grid; place-items: center; border-radius: 3px; font-size: 8.5px; font-weight: 700; } +.cmp-proc-name { flex: 0 1 130px; overflow: hidden; color: var(--cmp-ink); font-size: 11px; font-weight: 400; text-overflow: ellipsis; white-space: nowrap; } +.cmp-proc-bar { flex: 1; min-width: 40px; height: 3px; border-radius: 1.5px; background: var(--cmp-line); position: relative; } +.cmp-proc-bar i { position: absolute; inset: 0 auto 0 0; display: block; height: 100%; min-width: 2px; border-radius: 1.5px; transition: width .45s ease; } +.cmp-proc-bar u { position: absolute; right: -1px; top: 50%; width: 3px; height: 3px; margin-top: -1.5px; border-radius: 50%; display: block; } +.cmp-proc>em { margin-left: auto; color: var(--cmp-ink); font-style: normal; font-size: 11px; font-weight: 700; white-space: nowrap; font-variant-numeric: tabular-nums; } +.cmp-list-scroll { max-height: 158px; overflow: auto; margin: 0 -6px; padding: 0 6px; scrollbar-width: thin; scrollbar-color: var(--cmp-scroll) transparent; } +/* 列表内容不足一屏时均匀铺满面板,不留底部空洞。 */ +.cmp-list-scroll .cmp-procs { min-height: 100%; align-content: space-evenly; } + +/* 程序表(programs_table):整行液位条 + 末端亮边;与节点概况同一行。 */ +.cmp-programs { display: grid; grid-template-columns: 1fr 1fr; gap: 0; padding: 10px 14px 10px; } +.cmp-rank-col { min-width: 0; display: grid; gap: 5px; align-content: start; padding: 0 6px; } +.cmp-rank-col:last-child { border-left: 1px solid var(--cmp-gridline); } +.cmp-rank-title { display: flex; align-items: center; gap: 6px; margin-bottom: 3px; color: var(--cmp-muted); font-size: 10px; } +.cmp-rank-title i { width: 5px; height: 5px; border-radius: 50%; } +.cmp-rank-empty { padding: 14px 2px; color: var(--cmp-faint); font-size: 10.5px; } +.cmp-rank-row { position: relative; display: flex; align-items: center; gap: 8px; height: 20px; min-width: 0; } +.cmp-rank-fill { position: absolute; left: -3px; top: 1px; bottom: 1px; border-radius: 5px; transition: width .5s ease; } +.cmp-rank-fill u { position: absolute; right: -0.5px; top: 3px; bottom: 3px; width: 1.4px; border-radius: 2px; display: block; } +.cmp-rank-row .cmp-proc-mono { position: relative; width: 13px; height: 13px; flex: 0 0 13px; font-size: 8px; } +.cmp-rank-row b { position: relative; flex: 1; min-width: 0; overflow: hidden; color: var(--cmp-ink); font-size: 10.5px; font-weight: 400; text-overflow: ellipsis; white-space: nowrap; } +.cmp-rank-row em { position: relative; color: var(--cmp-ink); font-style: normal; font-size: 10.5px; font-weight: 700; white-space: nowrap; font-variant-numeric: tabular-nums; } + +/* 内存图例(legend):淡点 + 名称 + 字节数。 */ +.cmp-memory-legend { margin: 8px 0 0; display: grid; grid-template-columns: 1fr 1fr; gap: 5px 18px; } +.cmp-memory-legend span { display: inline-flex; align-items: center; gap: 6px; color: var(--cmp-muted); font-size: 10px; } +.cmp-memory-legend i { width: 5px; height: 5px; border-radius: 50%; } +.cmp-memory-legend b { margin-left: auto; color: var(--cmp-ink); font-weight: 700; font-variant-numeric: tabular-nums; } + +/* 总览 ↔ 详情切换:交叉淡入 + 轻微推进缩放(page_performance depth)。 + 一屏三行按 flex 比例分配纵向空间:卡片区最大、IO 次之、排行区托底,填满不留黑。 */ +.cmp-view { display: flex; flex-direction: column; min-height: 100%; } +/* 卡片区可随空间生长但封顶 52vh,绝不把排行/概况区挤到贴死界面底边; + 排行区按内容取高,底部圆角与余边始终完整可见。 */ +.cmp-view .cmp-cards { flex: 1 1 auto; min-height: 180px; max-height: 52vh; grid-template-rows: 1.7fr 1fr; margin-bottom: 10px; } +.cmp-view .cmp-panels { flex: 0 1 auto; min-height: 140px; margin-bottom: 4px; } +/* 详情页同样吃满剩余高度:主视图与程序列表按比例分行,列表内部滚动。 */ +/* 详情网格不铺满表面:首排封顶 44vh、列表行按内容取高,剩余高度留在页面底部, + 整组面板浮起、底边圆角与余边完整可见(同总览收回策略)。 */ +.cmp-view .cmp-detail-grid { flex: 0 1 auto; min-height: 0; grid-template-rows: minmax(200px, 44vh) auto; margin-bottom: 8px; } +.cmp-view .cmp-col-list { min-height: 0; display: flex; flex-direction: column; } +/* min-height:0 是关键:flex 子项默认 min-height:auto,列表会把面板撑穿流到页脚上。 */ +.cmp-view .cmp-col-list .cmp-list-scroll { flex: 1 1 auto; min-height: 0; max-height: 32vh; } +@keyframes view-in { from { opacity: 0; transform: scale(.985); } to { opacity: 1; transform: scale(1); } } +.cmp-view { animation: view-in .26s ease both; } + +@media (max-width: 980px) { + /* 窄屏回到可滚动的一列布局。 */ + .cmp-surface { overflow: auto; } + .cmp-panels { grid-template-columns: 1fr; } + .cmp-programs { gap: 14px; } + .cmp-rank-col:last-child { border-left: 0; } + .cmp-detail-grid { grid-template-columns: 1fr; grid-template-areas: "left" "main" "list"; } + .cmp-card.top { grid-column: span 3; } + .cmp-card.io { grid-column: span 6; } +} +@media (max-width: 560px) { + .cmp-cards { gap: 9px; } + .cmp-card.top { grid-column: span 6; } + .cmp-big { font-size: 24px; } + .cmp-hero h2 { font-size: 21px; } +} +@media (prefers-reduced-motion: reduce) { + .cmp-card, .cmp-back, .cmp-tab, .cmp-tab-plate { transition: none; } + .cmp-view, .cmp-gauge-tip, .cmp-now { animation: none; } + .cmp-proc-bar i, .cmp-rank-fill, .cmp-bar-span { transition: none; } +} + +/* ============================================================ + Dark glass skin (daozai "毛玻璃·深") across the whole shell, so + the compute surface no longer floats as a dark island inside a + light control plane. This final block intentionally overrides + the earlier light refresh blocks; keep it at the end of file. + ============================================================ */ +html[data-theme="dark"] { + color-scheme: dark; + color: #dbe4f0; + --line: rgba(148, 163, 184, .14); + --muted: #93a2b8; + --green: #2dd4bf; + --surface: rgba(15, 23, 42, .62); + --surface-raised: rgba(21, 31, 52, .6); +} +html[data-theme="dark"] body, html[data-theme="dark"] .shell, html[data-theme="dark"] .workspace { + background: + radial-gradient(52% 42% at 6% -8%, rgba(52, 66, 92, .4), transparent 60%), + radial-gradient(40% 38% at 98% 0%, rgba(84, 68, 110, .26), transparent 55%), + radial-gradient(55% 45% at 55% 112%, rgba(24, 96, 104, .2), transparent 60%), + #0a0c10; + background-attachment: fixed; + color: #dbe4f0; +} + +/* Rail + topbar */ +html[data-theme="dark"] .rail { background: rgba(10, 16, 29, .72); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); border-right-color: var(--line); } +html[data-theme="dark"] .brand-copy strong { color: #eef3fa; } +html[data-theme="dark"] .brand-copy strong span { color: #2dd4bf; } +html[data-theme="dark"] .brand-copy small { color: #5b6b83; } +html[data-theme="dark"] .brand-mark { background: linear-gradient(145deg, #2dd4bf, #0d9488); box-shadow: 0 6px 18px rgba(45, 212, 191, .28); color: #04211c; } +html[data-theme="dark"] .rail-divider { background: rgba(148, 163, 184, .12); } +html[data-theme="dark"] .rail-caption { color: #5b6b83; } +html[data-theme="dark"] .rail-button { color: #93a2b8; } +html[data-theme="dark"] .rail-button:hover { color: #2dd4bf; background: rgba(45, 212, 191, .07); } +html[data-theme="dark"] .rail-button.active { color: #43e6c8; background: rgba(45, 212, 191, .1); box-shadow: inset 0 0 0 1px rgba(45, 212, 191, .16), 0 0 18px rgba(45, 212, 191, .08); } +html[data-theme="dark"] .rail-button b { color: #64748b; } +html[data-theme="dark"] .rail-node { border-color: var(--line); background: rgba(255, 255, 255, .03); } +html[data-theme="dark"] .rail-node b { color: #cbd5e1; } +html[data-theme="dark"] .rail-node small { color: #64748b; } +html[data-theme="dark"] .topbar { border-bottom-color: var(--line); background: rgba(9, 14, 25, .72); backdrop-filter: blur(18px); -webkit-backdrop-filter: blur(18px); } +html[data-theme="dark"] .breadcrumbs { color: #64748b; } +html[data-theme="dark"] .breadcrumbs strong { color: #dbe4f0; } +html[data-theme="dark"] .server-pill, html[data-theme="dark"] .icon-button { border-color: var(--line); background: rgba(255, 255, 255, .04); color: #93a2b8; } +html[data-theme="dark"] .server-pill { backdrop-filter: blur(10px); } +html[data-theme="dark"] .icon-button:hover { color: #2dd4bf; border-color: rgba(45, 212, 191, .4); background: rgba(45, 212, 191, .08); } +@media (max-width: 680px) { html[data-theme="dark"] .topbar { background: rgba(9, 14, 25, .9); } } + +/* Typography + shared chrome */ +html[data-theme="dark"] h1 { color: #f1f5fb; } +html[data-theme="dark"] h2, html[data-theme="dark"] .section-heading h2 { color: #e6edf6; } +html[data-theme="dark"] .title-dot, html[data-theme="dark"] .eyebrow-line { background: #2dd4bf; color: #2dd4bf; } +html[data-theme="dark"] .eyebrow, html[data-theme="dark"] .modal-kicker { color: #64748b; } +html[data-theme="dark"] .subtitle { color: #93a2b8; } +html[data-theme="dark"] .online-dot { background: #2dd4bf; box-shadow: 0 0 0 3px rgba(45, 212, 191, .12); } +html[data-theme="dark"] .offline-dot { background: #f59e0b; box-shadow: 0 0 0 3px rgba(245, 158, 11, .12); } +html[data-theme="dark"] .primary-button { border-color: rgba(45, 212, 191, .7); background: linear-gradient(130deg, #14b8a6, #0d9488); box-shadow: 0 4px 18px rgba(20, 184, 166, .3); color: #04211c; } +html[data-theme="dark"] .primary-button:hover { background: #2dd4bf; box-shadow: 0 6px 22px rgba(45, 212, 191, .4); } +html[data-theme="dark"] .secondary-button { border-color: var(--line); background: rgba(255, 255, 255, .05); color: #b7c3d4; } +html[data-theme="dark"] .secondary-button:hover { background: rgba(255, 255, 255, .08); } +html[data-theme="dark"] .connection-badge { border-color: var(--line); background: rgba(255, 255, 255, .04); color: #93a2b8; } +html[data-theme="dark"] .connection-badge.connected { border-color: rgba(45, 212, 191, .35); color: #43e6c8; background: rgba(45, 212, 191, .08); } +html[data-theme="dark"] .search-box, html[data-theme="dark"] .filter-button { border-color: var(--line); background: rgba(255, 255, 255, .04); color: #93a2b8; } +html[data-theme="dark"] .search-box input { color: #dbe4f0; } +html[data-theme="dark"] .search-box input::placeholder { color: #5b6b83; } +html[data-theme="dark"] .filter-button:hover { color: #2dd4bf; border-color: rgba(45, 212, 191, .4); background: rgba(45, 212, 191, .07); } +html[data-theme="dark"] .section-count { border-color: var(--line); color: #93a2b8; background: rgba(255, 255, 255, .04); } +html[data-theme="dark"] .service-summary { color: #93a2b8; } +html[data-theme="dark"] .footer { border-top-color: var(--line); color: #5b6b83; } +html[data-theme="dark"] .footer button { color: #64748b; } +html[data-theme="dark"] .footer i, html[data-theme="dark"] .footer em { color: #2dd4bf; } +html[data-theme="dark"] .alert.error-alert { border-color: rgba(248, 113, 113, .3); background: rgba(190, 40, 40, .14); color: #fda4a4; } +html[data-theme="dark"] .alert.success-alert { border-color: rgba(45, 212, 191, .3); background: rgba(20, 184, 166, .1); color: #6ee7d4; } + +/* Service cards */ +html[data-theme="dark"] .service-card { border-color: var(--line); background: linear-gradient(155deg, rgba(255,255,255,.055), rgba(255,255,255,.022) 55%, rgba(255,255,255,.04)); backdrop-filter: blur(14px); -webkit-backdrop-filter: blur(14px); box-shadow: 0 12px 30px rgba(2, 8, 20, .3), inset 0 1px 0 rgba(255,255,255,.06); } +html[data-theme="dark"] .service-card:hover { border-color: rgba(45, 212, 191, .35); box-shadow: 0 16px 36px rgba(2, 8, 20, .4), 0 0 22px rgba(45, 212, 191, .1), inset 0 1px 0 rgba(255,255,255,.07); } +html[data-theme="dark"] .service-card.is-running { border-color: rgba(45, 212, 191, .32); box-shadow: inset 0 0 0 1px rgba(45, 212, 191, .07), 0 12px 30px rgba(2, 8, 20, .3); } +html[data-theme="dark"] .service-icon { border-color: var(--line); color: #93a2b8; background: rgba(255, 255, 255, .04); } +html[data-theme="dark"] .service-icon.running { border-color: rgba(45, 212, 191, .3); color: #2dd4bf; background: rgba(45, 212, 191, .1); } +html[data-theme="dark"] .service-icon.failed { color: #fda4a4; background: rgba(248, 113, 113, .1); } +html[data-theme="dark"] .card-title-row h3 { color: #e6edf6; } +html[data-theme="dark"] .card-title-row p { color: #7c8ca3; } +html[data-theme="dark"] .service-path { border-color: var(--line); background: rgba(2, 8, 18, .45); } +html[data-theme="dark"] .service-path span { color: #93a2b8; } +html[data-theme="dark"] .runtime-row span { color: #64748b; } +html[data-theme="dark"] .runtime-row b { color: #b7c3d4; } +html[data-theme="dark"] .card-meta, html[data-theme="dark"] .meta-dot { color: #64748b; } +html[data-theme="dark"] .card-meta button { color: #7c8ca3; } +html[data-theme="dark"] .card-meta button:hover { color: #2dd4bf; } +html[data-theme="dark"] .status-badge.stopped { color: #93a2b8; border-color: rgba(148, 163, 184, .18); background: rgba(148, 163, 184, .08); } +html[data-theme="dark"] .status-badge.running { color: #43e6c8; border-color: rgba(45, 212, 191, .3); background: rgba(45, 212, 191, .1); } +html[data-theme="dark"] .status-badge.failed { color: #fda4a4; border-color: rgba(248, 113, 113, .3); background: rgba(248, 113, 113, .1); } +html[data-theme="dark"] .card-menu { border-color: rgba(148, 163, 184, .2); background: #111b2e; box-shadow: 0 14px 32px rgba(2, 8, 20, .5); } +html[data-theme="dark"] .card-menu button { color: #b7c3d4; } +html[data-theme="dark"] .card-menu button:hover { background: rgba(255, 255, 255, .06); } +html[data-theme="dark"] .card-menu .danger-menu { color: #fda4a4; } +html[data-theme="dark"] .more-button { color: #64748b; } +html[data-theme="dark"] .more-button:hover { color: #e6edf6; background: rgba(255, 255, 255, .07); } +html[data-theme="dark"] .start-button, html[data-theme="dark"] .stop-button { border-color: rgba(45, 212, 191, .35); background: rgba(45, 212, 191, .1); color: #43e6c8; } +html[data-theme="dark"] .start-button:hover { background: rgba(45, 212, 191, .18); } +html[data-theme="dark"] .stop-button { border-color: rgba(248, 113, 113, .3); background: rgba(248, 113, 113, .08); color: #fda4a4; } +html[data-theme="dark"] .stop-button:hover { background: rgba(248, 113, 113, .14); } +html[data-theme="dark"] .restart-button { border-color: var(--line); background: rgba(255, 255, 255, .04); color: #93a2b8; } +html[data-theme="dark"] .restart-button:hover { color: #2dd4bf; border-color: rgba(45, 212, 191, .35); } +html[data-theme="dark"] .add-card { border-color: rgba(148, 163, 184, .22); background: rgba(255, 255, 255, .02); color: #93a2b8; } +html[data-theme="dark"] .add-card:hover { border-color: rgba(45, 212, 191, .4); background: rgba(45, 212, 191, .05); } +html[data-theme="dark"] .add-card-icon { border-color: rgba(45, 212, 191, .3); color: #2dd4bf; background: rgba(45, 212, 191, .08); } +html[data-theme="dark"] .add-card>span:last-child { color: #64748b; } +html[data-theme="dark"] .empty-state { border-color: rgba(148, 163, 184, .2); background: rgba(255, 255, 255, .02); } +html[data-theme="dark"] .empty-state h3 { color: #dbe4f0; } +html[data-theme="dark"] .empty-state p { color: #7c8ca3; } +html[data-theme="dark"] .empty-icon { border-color: rgba(45, 212, 191, .3); color: #2dd4bf; background: rgba(45, 212, 191, .08); } +html[data-theme="dark"] .loading-state { color: #7c8ca3; } + +/* Runtime page */ +html[data-theme="dark"] .runtime-kpis>div { border-color: var(--line); background: linear-gradient(155deg, rgba(255,255,255,.055), rgba(255,255,255,.022)); backdrop-filter: blur(14px); box-shadow: 0 12px 30px rgba(2, 8, 20, .28); } +html[data-theme="dark"] .runtime-kpis small { color: #7c8ca3; } +html[data-theme="dark"] .runtime-kpis strong { color: #f1f5fb; } +html[data-theme="dark"] .runtime-kpis strong span { color: #7c8ca3; } +html[data-theme="dark"] .runtime-kpi-icon.green { color: #2dd4bf; background: rgba(45, 212, 191, .12); } +html[data-theme="dark"] .runtime-kpi-icon.amber { color: #fbbf24; background: rgba(251, 191, 36, .12); } +html[data-theme="dark"] .runtime-kpi-icon.blue { color: #60a5fa; background: rgba(96, 165, 250, .12); } +html[data-theme="dark"] .runtime-kpi-icon.violet { color: #a78bfa; background: rgba(167, 139, 250, .12); } +html[data-theme="dark"] .runtime-panel { border-color: var(--line); background: linear-gradient(155deg, rgba(255,255,255,.05), rgba(255,255,255,.02)); backdrop-filter: blur(14px); } +html[data-theme="dark"] .runtime-panel-heading { border-bottom-color: var(--line); } +html[data-theme="dark"] .runtime-refresh-note { color: #5b6b83; } +html[data-theme="dark"] .runtime-table th { color: #7c8ca3; background: rgba(2, 8, 18, .35); } +html[data-theme="dark"] .runtime-table td { border-top-color: rgba(148, 163, 184, .08); color: #93a2b8; } +html[data-theme="dark"] .runtime-table td strong { color: #dbe4f0; } +html[data-theme="dark"] .runtime-table td small { color: #64748b; } +html[data-theme="dark"] .runtime-status { background: rgba(148, 163, 184, .1); color: #93a2b8; } +html[data-theme="dark"] .runtime-status i { background: #64748b; } +html[data-theme="dark"] .runtime-status.running { color: #43e6c8; background: rgba(45, 212, 191, .1); } +html[data-theme="dark"] .runtime-status.running i { background: #2dd4bf; box-shadow: 0 0 8px rgba(45, 212, 191, .7); } +html[data-theme="dark"] .runtime-status.failed { color: #fda4a4; background: rgba(248, 113, 113, .1); } +html[data-theme="dark"] .runtime-status.failed i { background: #f87171; } +html[data-theme="dark"] .runtime-empty { color: #64748b; } + +/* Modal / forms / settings */ +html[data-theme="dark"] .modal { border-color: rgba(148, 163, 184, .18); background: #0d1526; box-shadow: 0 28px 80px rgba(2, 6, 14, .65); } +html[data-theme="dark"] .modal-head { border-bottom-color: var(--line); } +html[data-theme="dark"] .modal-head h2 { color: #e6edf6; } +html[data-theme="dark"] .modal-head h2 small { color: #64748b; } +html[data-theme="dark"] .form-field>span { color: #b7c3d4; } +html[data-theme="dark"] .form-field input, html[data-theme="dark"] .form-field textarea { border-color: rgba(148, 163, 184, .18); background: rgba(2, 8, 18, .5); color: #dbe4f0; } +html[data-theme="dark"] .form-field input:focus, html[data-theme="dark"] .form-field textarea:focus { border-color: rgba(45, 212, 191, .55); box-shadow: 0 0 0 3px rgba(45, 212, 191, .1); background: rgba(2, 8, 18, .7); } +html[data-theme="dark"] .form-field input::placeholder { color: #52627a; } +html[data-theme="dark"] .form-field small, html[data-theme="dark"] .form-note { color: #7c8ca3; } +html[data-theme="dark"] .terminal-head { color: #7c8ca3; border-bottom-color: var(--line); } +html[data-theme="dark"] .terminal-head button { border-color: var(--line); background: rgba(255, 255, 255, .05); color: #b7c3d4; } +html[data-theme="dark"] .log-output { background: #060b14; } +html[data-theme="dark"] .log-error { color: #fda4a4; background: rgba(248, 113, 113, .1); } +html[data-theme="dark"] .log-live { color: #43e6c8; } +html[data-theme="dark"] .log-live i { background: #2dd4bf; } +html[data-theme="dark"] .settings-panel { border-color: var(--line); background: linear-gradient(155deg, rgba(255,255,255,.055), rgba(255,255,255,.022)); backdrop-filter: blur(14px); box-shadow: 0 12px 30px rgba(2, 8, 20, .3); } +html[data-theme="dark"] .settings-token-status { color: #fbbf24; } +html[data-theme="dark"] .settings-token-status i { background: #fbbf24; } +html[data-theme="dark"] .settings-token-status.configured { color: #43e6c8; } +html[data-theme="dark"] .settings-token-status.configured i { background: #2dd4bf; } +html[data-theme="dark"] .settings-description { color: #93a2b8; } +html[data-theme="dark"] .settings-description code { background: rgba(45, 212, 191, .12); color: #43e6c8; } +html[data-theme="dark"] .settings-token-form label { color: #b7c3d4; } +html[data-theme="dark"] .settings-token-form input { border-color: rgba(148, 163, 184, .18); background: rgba(2, 8, 18, .5); color: #dbe4f0; } +html[data-theme="dark"] .settings-token-form input:focus { border-color: rgba(45, 212, 191, .55); box-shadow: 0 0 0 3px rgba(45, 212, 191, .1); } +html[data-theme="dark"] .settings-token-form input::placeholder { color: #52627a; } +html[data-theme="dark"] .settings-token-actions .secondary-button { border-color: var(--line); background: rgba(255, 255, 255, .04); } +html[data-theme="dark"] .settings-token-actions .secondary-button:hover { color: #fda4a4; border-color: rgba(248, 113, 113, .35); background: rgba(248, 113, 113, .08); } + +/* Compute surface blends into the global dark skin now. */ +html[data-theme="dark"] .cmp-surface { background: none; border: 0; border-radius: 0; box-shadow: none; padding: 2px 2px 6px 0; scrollbar-gutter: stable; } +/* 卡体染色暗底(glass_body 的 Web 等价):SURFACE→RAISED 混合 + 主色上淡下浓。 */ +html[data-theme="dark"] .cmp-card { background: linear-gradient(180deg, rgba(30, 33, 38, .72), rgba(24, 26, 30, .82)); } +html[data-theme="dark"] .cmp-card::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + background: linear-gradient(180deg, transparent 20%, color-mix(in srgb, var(--card-color, #fff) 7%, transparent)); + opacity: .85; + pointer-events: none; +} + +/* ============================================================ + Light theme(浅色控制台 + 算力页浅底翻色)。 + 深色皮肤块整体绑定在 html[data-theme="dark"];本块翻转全部 + 算力 token,并重新启用原挂于皮肤块的结构规则(透明表面、 + 卡片染色、canvas 层级)。初始主题跟随系统,手动切换后记住。 + ============================================================ */ +html[data-theme="light"] { + color-scheme: light; + --line: rgba(15, 23, 42, .08); + --muted: #64748b; + --green: #0d9488; + --surface: rgba(255, 255, 255, .8); + --surface-raised: rgba(255, 255, 255, .94); + /* 资源主色压深两档:白底上的霓虹改写成有对比度的深霓虹 */ + --c-cpu: #0f9e8e; + --c-gpu: #7c5cd6; + --c-mem: #c88a1f; + --c-disk: #db5a8a; + --c-net: #3b82f6; + --cmp-line: rgba(15, 23, 42, .07); + --cmp-muted: #64748b; + --cmp-faint: #94a3b8; + --cmp-ink: #101a2c; + --cmp-dim: #64748b; + --cmp-value: #33415a; + --cmp-label: #64748b; + --cmp-gridline: #d9dfe9; + --cmp-fill-1: rgba(15, 23, 42, .035); + --cmp-fill-2: rgba(15, 23, 42, .055); + --cmp-fill-3: rgba(15, 23, 42, .075); + --cmp-plate: rgba(255, 255, 255, .96); + --cmp-shadow: rgba(15, 23, 42, .1); + --cmp-edge: rgba(15, 23, 42, .08); + --cmp-edge-strong: rgba(15, 23, 42, .16); + --cmp-scroll: rgba(100, 116, 139, .3); + --cmp-ok-text: #0b7f5f; + --cmp-ok-icon: #0f9d7a; + --cmp-ok-dot: #10b981; + --cmp-ok-edge: rgba(13, 148, 136, .3); + --cmp-ok-soft: rgba(13, 148, 136, .09); + --cmp-ok-bg: rgba(13, 148, 136, .07); + --cmp-ok-glow: rgba(16, 185, 129, .45); + --cmp-warn-text: #92400e; + --cmp-warn-dot: #d97706; + --cmp-warn-edge: rgba(217, 119, 6, .32); + --cmp-warn-glow: rgba(217, 119, 6, .4); + --cmp-warn-bg: rgba(217, 119, 6, .07); +} +html[data-theme="light"] body, +html[data-theme="light"] .shell, +html[data-theme="light"] .workspace { + background: + radial-gradient(52% 42% at 6% -8%, rgba(13, 148, 136, .09), transparent 60%), + radial-gradient(40% 38% at 98% 0%, rgba(59, 130, 246, .08), transparent 55%), + radial-gradient(55% 45% at 55% 112%, rgba(124, 92, 214, .06), transparent 60%), + #f3f6fa; + background-attachment: fixed; + color: #0f172a; +} +/* 原深色皮肤里的结构规则在浅色分支等价重建 */ +html[data-theme="light"] .cmp-surface { background: none; border: 0; border-radius: 0; box-shadow: none; padding: 2px 2px 6px 0; scrollbar-gutter: stable; } +html[data-theme="light"] .cmp-canvas { z-index: 1; } +html[data-theme="light"] .cmp-card { background: linear-gradient(180deg, rgba(255, 255, 255, .92), rgba(248, 250, 253, .95)); } +html[data-theme="light"] .cmp-card::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + background: linear-gradient(180deg, transparent 20%, color-mix(in srgb, var(--card-color, #fff) 9%, transparent)); + opacity: .85; + pointer-events: none; +} diff --git a/frontend/src/theme.ts b/frontend/src/theme.ts new file mode 100644 index 0000000..3edbe4c --- /dev/null +++ b/frontend/src/theme.ts @@ -0,0 +1,39 @@ +import { setPalette, type ThemeMode } from "./compute/palette"; + +export const THEME_KEY = "compute-service-manager-theme"; +export type Theme = ThemeMode; + +/** 已存偏好优先;否则跟随系统。 */ +export function resolveTheme(): Theme { + try { + const stored = localStorage.getItem(THEME_KEY); + if (stored === "light" || stored === "dark") return stored; + } catch { + /* 隐私模式下 localStorage 不可用:退回系统判断 */ + } + return window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; +} + +/** CSS 分支(html[data-theme])与 canvas 调色板同步切换。 */ +export function applyTheme(theme: Theme) { + document.documentElement.dataset.theme = theme; + document.documentElement.style.colorScheme = theme; + setPalette(theme); +} + +export function rememberTheme(theme: Theme) { + try { + localStorage.setItem(THEME_KEY, theme); + } catch { + /* 存不下也不影响本次切换 */ + } +} + +export function hasStoredTheme(): boolean { + try { + const stored = localStorage.getItem(THEME_KEY); + return stored === "light" || stored === "dark"; + } catch { + return false; + } +}
服务状态进程 ID启动时间入口脚本
服务状态端口进程 ID启动时间入口脚本
{item.name}{item.description || "Python 服务"} {statusLabels[item.status]}{item.ports?.length ? item.ports.join(", ") : "—"} {item.pid ?? "—"} {item.active_since ? formatTime(item.active_since) : "—"} {item.script_path}