first commit

main
Bifang 2026-10-16 15:20:34 +08:00
commit e8432647ff
17 changed files with 2116 additions and 0 deletions

9
.gitignore vendored 100644
View File

@ -0,0 +1,9 @@
__pycache__/
*.py[cod]
.env
backend/.venv/
backend/data/
frontend/node_modules/
frontend/dist/
*.log

72
README.md 100644
View File

@ -0,0 +1,72 @@
# 本机算力服务台
前后端分离的 Python 服务管理面板。管理 API 和前端部署在被管理的 Linux 服务器上,API 使用当前 Linux 用户的 `systemd --user` 管理服务,不需要 SSH 或容器化模型。
## 功能
- 登记已有的 Conda 或 `.venv` Python 解释器、脚本、工作目录、启动参数和环境变量。
- 通过应用卡片启动、停止、重启服务,并读取状态、PID 和 journal 日志。
- 后端内置本机资源采集,监控 CPU、内存、磁盘、NVIDIA GPU、网络、温度与运行时间;不依赖 Nezha Agent 或远程监控 API。
- 每个应用有独立的 systemd user unit;面板 API 重启后,服务状态仍由 systemd 托管。
- 前端只发送结构化配置和固定操作;后端不接受任意 shell 命令。
## 目录
```text
backend/ FastAPI API、本机 systemd 管理和 SQLite 配置存储
frontend/ React + Vite 管理面板
```
## Linux 服务器部署
推荐使用交互式部署脚本。以将来运行服务的普通 Linux 账号,在项目目录执行:
```bash
bash deploy/install.sh
```
脚本会引导设置部署目录、访问端口和监听地址,创建 Python 虚拟环境、构建前端、生成管理密钥,并安装和启动 `systemd --user` 服务。默认监听 `0.0.0.0:8199`,用于可信内网访问;如需公网访问,请放在 HTTPS 反向代理后面并通过防火墙限制来源。面板和 API 同源提供,无需单独配置 Nginx 才能启动。
登记的应用服务与管理面板以同一个 Linux 账号运行。脚本会询问是否启用 linger,使面板在退出 SSH 后继续运行;也可以稍后手动执行 `sudo loginctl enable-linger "$USER"`。
```bash
systemctl --user status compute-service-manager
systemctl --user restart compute-service-manager
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。
如需手动配置 systemd、Nginx,可继续参考 `deploy/compute-service-manager.service.example` 和 `deploy/nginx.conf.example`。
前端构建和开发:
```bash
cd frontend
npm install
npm run dev
```
Vite 开发服务器默认将 `/api` 代理到 `127.0.0.1:8000`。Linux 部署脚本会先生成 `frontend/dist`,再由 FastAPI 后端同源托管静态页面与 API;源代码仍保持前后端分离。
## 添加服务示例
假设环境解释器是 `/opt/conda/envs/gemma/bin/python`,启动程序位于 `/dep/Bfmodeltest/gemma4_31b_deploy/serve.py`:
- Python 解释器:`/opt/conda/envs/gemma/bin/python`
- 启动脚本:`/dep/Bfmodeltest/gemma4_31b_deploy/serve.py`
- 工作目录:`/dep/Bfmodeltest/gemma4_31b_deploy`
- 参数 JSON:`["--port", "8000"]`
- 环境变量 JSON:`{"CUDA_VISIBLE_DEVICES": "0"}`
首次访问页面时,在侧边栏「设置」页填入 `PANEL_API_TOKEN`。应用登记后即可从卡片启停。
## 当前 MVP 边界
- 管理权限采用单个共享 API 密钥,持有密钥的人可以登记并以服务账号身份启动任意可访问的 Python 程序;适合信任使用者的内网试用,尚未实现用户账号、团队角色和操作审计。
- 服务以运行面板的 Linux 用户身份启动,不支持为不同应用选择不同 Linux 用户。
- 本机资源采集不可用时,资源监控显示为空。HTTP 健康探测和应用分组尚未实现。
- 环境变量会写入本机应用启动器和 SQLite 配置,文件权限限制为当前用户;环境文件也应限制为服务账号可读。
- `systemd --user` 需要登录会话管理器可用;服务器部署时应启用 linger 并设置运行时总线环境变量。

View File

@ -0,0 +1,19 @@
# Set this to a long random value before exposing the panel to your team.
PANEL_API_TOKEN=replace-with-a-long-random-token
# SQLite database location. The account running the API must be able to write here.
PANEL_DATABASE_PATH=./data/panel.db
# systemd user manager runtime. Replace 1000 with the Linux account UID.
XDG_RUNTIME_DIR=/run/user/1000
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

View File

@ -0,0 +1 @@

614
backend/app/main.py 100644
View File

@ -0,0 +1,614 @@
"""Local service manager API backed by the current user's systemd instance."""
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
from pathlib import Path
from typing import Any, Literal
import psutil
from fastapi import Depends, FastAPI, Header, HTTPException, Query, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel, Field, field_validator
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")))
SERVICE_HOME = Path(os.getenv("PANEL_SERVICE_HOME", str(Path.home() / ".local" / "share" / "compute-service-manager")))
UNIT_DIR = Path(os.getenv("PANEL_UNIT_DIR", str(Path.home() / ".config" / "systemd" / "user")))
API_TOKEN = os.getenv("PANEL_API_TOKEN", "")
ENV_KEY_PATTERN = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$")
_operation_lock = asyncio.Lock()
class AppInput(BaseModel):
"""Fields needed to run a Python service without accepting arbitrary shell text."""
name: str = Field(min_length=1, max_length=80)
description: str = Field(default="", max_length=240)
python_path: str = Field(min_length=1, max_length=1000)
script_path: str = Field(min_length=1, max_length=1000)
working_dir: str = Field(min_length=1, max_length=1000)
args: list[str] = Field(default_factory=list, max_length=100)
env: dict[str, str] = Field(default_factory=dict, max_length=100)
@field_validator("name")
@classmethod
def trim_name(cls, value: str) -> str:
value = value.strip()
if not value or any(ord(char) < 32 for char in value):
raise ValueError("应用名称不能为空,也不能包含控制字符")
return value
@field_validator("python_path", "script_path", "working_dir")
@classmethod
def require_absolute_path(cls, value: str) -> str:
if any(ord(char) < 32 for char in value):
raise ValueError("路径不能包含控制字符")
candidate = Path(value).expanduser()
if not candidate.is_absolute():
raise ValueError("路径必须是绝对路径")
return str(candidate)
@field_validator("env")
@classmethod
def validate_environment(cls, value: dict[str, str]) -> dict[str, str]:
for key in value:
if not ENV_KEY_PATTERN.fullmatch(key):
raise ValueError(f"无效的环境变量名:{key}")
if "\x00" in value[key]:
raise ValueError(f"环境变量 {key} 不能包含 NUL 字符")
return value
@field_validator("args")
@classmethod
def validate_args(cls, value: list[str]) -> list[str]:
if any("\x00" in part for part in value):
raise ValueError("启动参数不能包含 NUL 字符")
return value
class AppRecord(AppInput):
id: str
status: Literal["running", "stopped", "failed", "unknown"] = "stopped"
pid: int | None = None
active_since: str | None = None
created_at: str
updated_at: str
class AppAction(BaseModel):
action: Literal["start", "stop", "restart"]
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()
def connect_db() -> sqlite3.Connection:
DATABASE_PATH.parent.mkdir(parents=True, exist_ok=True)
connection = sqlite3.connect(DATABASE_PATH, timeout=10)
connection.row_factory = sqlite3.Row
return connection
def initialize_database() -> None:
with connect_db() as connection:
connection.execute(
"""CREATE TABLE IF NOT EXISTS apps (
id TEXT PRIMARY KEY,
name TEXT NOT NULL,
description TEXT NOT NULL DEFAULT '',
python_path TEXT NOT NULL,
script_path TEXT NOT NULL,
working_dir TEXT NOT NULL,
args_json TEXT NOT NULL,
env_json TEXT NOT NULL,
created_at TEXT NOT NULL,
updated_at TEXT NOT NULL
)"""
)
# SQLite 配置包含应用环境变量,限制数据库文件只对管理账号可读写。
DATABASE_PATH.chmod(0o600)
def require_token(authorization: str | None = Header(default=None)) -> None:
# API 操作统一使用服务端密钥鉴权,密钥不进入服务配置或日志。
if not API_TOKEN:
raise HTTPException(status_code=503, detail="请先配置 PANEL_API_TOKEN")
supplied = authorization.removeprefix("Bearer ") if authorization else ""
if not supplied or not hmac.compare_digest(supplied, API_TOKEN):
raise HTTPException(status_code=401, detail="管理密钥无效")
def unit_name(app_id: str) -> str:
return f"compute-app-{app_id}.service"
def service_paths(app_id: str) -> tuple[Path, Path]:
return UNIT_DIR / unit_name(app_id), SERVICE_HOME / "launchers" / f"{app_id}.sh"
def fetch_row(app_id: str) -> sqlite3.Row:
with connect_db() as connection:
row = connection.execute("SELECT * FROM apps WHERE id = ?", (app_id,)).fetchone()
if row is None:
raise HTTPException(status_code=404, detail="应用不存在")
return row
def to_record(row: sqlite3.Row, service_state: dict[str, str] | None = None) -> AppRecord:
state = service_state or {}
active = state.get("ActiveState", "unknown")
status: Literal["running", "stopped", "failed", "unknown"]
if active == "active":
status = "running"
elif active in {"inactive", "deactivating"}:
status = "stopped"
elif active == "failed":
status = "failed"
else:
status = "unknown"
return AppRecord(
id=row["id"],
name=row["name"],
description=row["description"],
python_path=row["python_path"],
script_path=row["script_path"],
working_dir=row["working_dir"],
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,
active_since=state.get("ActiveEnterTimestamp"),
created_at=row["created_at"],
updated_at=row["updated_at"],
)
def systemctl(*args: str, check: bool = True) -> subprocess.CompletedProcess[str]:
command = ["systemctl", "--user", *args]
try:
result = subprocess.run(command, text=True, capture_output=True, timeout=30, check=False)
except FileNotFoundError as exc:
raise HTTPException(status_code=503, detail="当前系统找不到 systemctl") from exc
except subprocess.TimeoutExpired as exc:
raise HTTPException(status_code=504, detail="systemd 操作超时") from exc
if check and result.returncode != 0:
message = (result.stderr or result.stdout).strip() or "systemd 操作失败"
raise HTTPException(status_code=409, detail=message[-1200:])
return result
def journalctl(*args: str) -> subprocess.CompletedProcess[str]:
try:
return subprocess.run(
["journalctl", "--user", *args],
text=True,
capture_output=True,
timeout=20,
check=False,
)
except FileNotFoundError as exc:
raise HTTPException(status_code=503, detail="当前系统找不到 journalctl") from exc
except subprocess.TimeoutExpired as exc:
raise HTTPException(status_code=504, detail="读取服务日志超时") from exc
def read_unit_state(app_id: str) -> dict[str, str]:
result = systemctl(
"show",
unit_name(app_id),
"--property=ActiveState,MainPID,ActiveEnterTimestamp",
check=False,
)
if result.returncode != 0:
return {"ActiveState": "inactive", "MainPID": "0"}
return dict(line.split("=", 1) for line in result.stdout.splitlines() if "=" in line)
def check_runtime(app: AppInput) -> tuple[Path, Path, Path]:
python = Path(app.python_path).expanduser().resolve()
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):
raise HTTPException(status_code=422, detail="Python 解释器不存在或不可执行")
if not script.is_file():
raise HTTPException(status_code=422, detail="启动脚本不存在")
if not working_dir.is_dir():
raise HTTPException(status_code=422, detail="工作目录不存在")
return python, script, working_dir
def write_service_files(app_id: str, app: AppInput) -> None:
python, script, working_dir = check_runtime(app)
unit_path, launcher_path = service_paths(app_id)
unit_path.parent.mkdir(parents=True, exist_ok=True)
launcher_path.parent.mkdir(parents=True, exist_ok=True)
# 用 argv 列表和 shlex 转义生成启动器,不拼接用户提供的 shell 片段。
command = [str(python), str(script), *app.args]
lines = ["#!/usr/bin/env bash", "set -euo pipefail", f"cd -- {shlex.quote(str(working_dir))}"]
lines.extend(f"export {key}={shlex.quote(value)}" for key, value in app.env.items())
lines.append("exec " + " ".join(shlex.quote(part) for part in command))
launcher_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
launcher_path.chmod(0o700)
# 每个应用使用独立 user unit;重启面板进程不会丢失服务的托管状态。
unit_path.write_text(
"\n".join(
[
"[Unit]",
f"Description=Managed app: {app.name.replace('%', '%%')}",
"After=network.target",
"",
"[Service]",
"Type=simple",
f"WorkingDirectory={systemd_quote(str(working_dir))}",
f"ExecStart=/usr/bin/bash {systemd_quote(str(launcher_path))}",
"Restart=on-failure",
"RestartSec=5s",
"TimeoutStopSec=30s",
"KillMode=control-group",
"",
"[Install]",
"WantedBy=default.target",
"",
]
),
encoding="utf-8",
)
unit_path.chmod(0o600)
def systemd_quote(value: str) -> str:
"""Quote a single systemd unit argument, including spaces and quote marks."""
return '"' + value.replace("\\", "\\\\").replace('"', '\\"').replace("%", "%%") + '"'
def save_app(app_id: str, app: AppInput) -> None:
timestamp = utc_now()
with connect_db() as connection:
connection.execute(
"""INSERT INTO apps
(id, name, description, python_path, script_path, working_dir, args_json, env_json, created_at, updated_at)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)""",
(
app_id,
app.name,
app.description,
app.python_path,
app.script_path,
app.working_dir,
json.dumps(app.args),
json.dumps(app.env),
timestamp,
timestamp,
),
)
def update_app(app_id: str, app: AppInput) -> None:
with connect_db() as connection:
connection.execute(
"""UPDATE apps SET name=?, description=?, python_path=?, script_path=?, working_dir=?,
args_json=?, env_json=?, updated_at=? WHERE id=?""",
(
app.name,
app.description,
app.python_path,
app.script_path,
app.working_dir,
json.dumps(app.args),
json.dumps(app.env),
utc_now(),
app_id,
),
)
@asynccontextmanager
async def lifespan(_: FastAPI):
initialize_database()
monitor_task = asyncio.create_task(system_monitor.run())
try:
yield
finally:
monitor_task.cancel()
await asyncio.gather(monitor_task, return_exceptions=True)
app = FastAPI(title="Compute Service Manager API", version="0.1.0", lifespan=lifespan)
origins = [item.strip() for item in os.getenv("PANEL_CORS_ORIGINS", "http://localhost:5173").split(",") if item.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=False,
allow_methods=["GET", "POST", "PUT", "DELETE"],
allow_headers=["Authorization", "Content-Type"],
)
# Production deployments serve the separately built frontend from the same origin.
FRONTEND_DIST = BASE_DIR.parent / "frontend" / "dist"
if (FRONTEND_DIST / "index.html").is_file():
app.mount("/assets", StaticFiles(directory=FRONTEND_DIST / "assets"), name="frontend-assets")
@app.get("/api/health")
def health() -> dict[str, str]:
return {"status": "ok"}
@app.get("/api/system/metrics", dependencies=[Depends(require_token)])
def system_metrics() -> dict[str, Any]:
"""Return the latest local system-monitor snapshot without calling another service."""
return system_monitor.snapshot()
@app.get("/api/apps", response_model=list[AppRecord], dependencies=[Depends(require_token)])
def list_apps() -> list[AppRecord]:
with connect_db() as connection:
rows = connection.execute("SELECT * FROM apps ORDER BY created_at DESC").fetchall()
return [to_record(row, read_unit_state(row["id"])) for row in rows]
@app.post("/api/apps", response_model=AppRecord, status_code=201, dependencies=[Depends(require_token)])
async def create_app(payload: AppInput) -> AppRecord:
check_runtime(payload)
app_id = str(uuid.uuid4())
async with _operation_lock:
await asyncio.to_thread(save_app, app_id, payload)
await asyncio.to_thread(write_service_files, app_id, payload)
await asyncio.to_thread(systemctl, "daemon-reload")
return to_record(fetch_row(app_id), {"ActiveState": "inactive", "MainPID": "0"})
@app.put("/api/apps/{app_id}", response_model=AppRecord, dependencies=[Depends(require_token)])
async def edit_app(app_id: str, payload: AppInput) -> AppRecord:
row = fetch_row(app_id)
if read_unit_state(app_id).get("ActiveState") == "active":
raise HTTPException(status_code=409, detail="请先停止应用,再修改配置")
check_runtime(payload)
async with _operation_lock:
await asyncio.to_thread(update_app, app_id, payload)
await asyncio.to_thread(write_service_files, app_id, payload)
await asyncio.to_thread(systemctl, "daemon-reload")
return to_record(fetch_row(app_id), {"ActiveState": "inactive", "MainPID": "0"})
@app.post("/api/apps/{app_id}/actions", response_model=AppRecord, dependencies=[Depends(require_token)])
async def app_action(app_id: str, payload: AppAction) -> AppRecord:
row = fetch_row(app_id)
async with _operation_lock:
if payload.action in {"start", "restart"}:
saved = AppInput(
name=row["name"],
description=row["description"],
python_path=row["python_path"],
script_path=row["script_path"],
working_dir=row["working_dir"],
args=json.loads(row["args_json"]),
env=json.loads(row["env_json"]),
)
await asyncio.to_thread(write_service_files, app_id, saved)
await asyncio.to_thread(systemctl, "daemon-reload")
if payload.action == "restart":
await asyncio.to_thread(systemctl, "restart", unit_name(app_id))
elif payload.action == "start":
await asyncio.to_thread(systemctl, "start", unit_name(app_id))
else:
await asyncio.to_thread(systemctl, "stop", unit_name(app_id), check=False)
return to_record(fetch_row(app_id), read_unit_state(app_id))
@app.get("/api/apps/{app_id}/logs", dependencies=[Depends(require_token)])
def app_logs(app_id: str, lines: int = Query(default=120, ge=1, le=1000)) -> dict[str, Any]:
fetch_row(app_id)
result = journalctl("--no-pager", "--output=short-iso", "-u", unit_name(app_id), "-n", str(lines))
return {"lines": result.stdout.splitlines(), "error": result.stderr.strip() if result.returncode else None}
@app.delete("/api/apps/{app_id}", status_code=204, dependencies=[Depends(require_token)])
async def delete_app(app_id: str) -> Response:
fetch_row(app_id)
if read_unit_state(app_id).get("ActiveState") == "active":
raise HTTPException(status_code=409, detail="请先停止应用,再删除")
unit_path, launcher_path = service_paths(app_id)
async with _operation_lock:
await asyncio.to_thread(unit_path.unlink, missing_ok=True)
await asyncio.to_thread(launcher_path.unlink, missing_ok=True)
def remove_row() -> None:
with connect_db() as connection:
connection.execute("DELETE FROM apps WHERE id = ?", (app_id,))
await asyncio.to_thread(remove_row)
await asyncio.to_thread(systemctl, "daemon-reload")
return Response(status_code=204)
@app.get("/{frontend_path:path}", include_in_schema=False)
def frontend_fallback(frontend_path: str) -> FileResponse:
"""Return the SPA entry for browser routes after API routes have been matched."""
if frontend_path == "api" or frontend_path.startswith("api/"):
raise HTTPException(status_code=404, detail="Not Found")
index_file = FRONTEND_DIST / "index.html"
if not index_file.is_file():
raise HTTPException(status_code=404, detail="前端尚未构建")
return FileResponse(index_file)

View File

@ -0,0 +1,5 @@
fastapi>=0.115,<1.0
uvicorn[standard]>=0.30,<1.0
pydantic>=2.8,<3.0
psutil>=6.0,<8.0

View File

@ -0,0 +1,18 @@
[Unit]
Description=Compute Service Manager API
After=network.target
[Service]
Type=simple
User=REPLACE_WITH_SERVICE_ACCOUNT
WorkingDirectory=/opt/compute-service-manager/backend
EnvironmentFile=/etc/compute-service-manager.env
Environment=XDG_RUNTIME_DIR=/run/user/REPLACE_WITH_UID
Environment=DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/REPLACE_WITH_UID/bus
ExecStart=/opt/compute-service-manager/backend/.venv/bin/uvicorn app.main:app --host 127.0.0.1 --port 8000
Restart=on-failure
RestartSec=3
[Install]
WantedBy=multi-user.target

158
deploy/install.sh 100644
View File

@ -0,0 +1,158 @@
#!/usr/bin/env bash
# Guided, per-user deployment for the Compute Service Manager on Linux.
set -Eeuo pipefail
SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
CURRENT_USER="$(id -un)"
DEFAULT_INSTALL_DIR="$SCRIPT_DIR"
color() {
local code="$1"
shift
printf '\033[%sm%s\033[0m\n' "$code" "$*"
}
info() { color '36' "$*"; }
success() { color '32' "$*"; }
warn() { color '33' "$*"; }
fail() { color '31' "$*" >&2; exit 1; }
ask() {
local prompt="$1" default="$2" answer
read -r -p "$prompt [$default]: " answer
printf '%s' "${answer:-$default}"
}
confirm() {
local prompt="$1" answer
read -r -p "$prompt [Y/n]: " answer
[[ -z "$answer" || "$answer" =~ ^[Yy]$ ]]
}
version_at_least() {
local actual="$1" required="$2"
[[ "$(printf '%s\n%s\n' "$required" "$actual" | sort -V | head -n1)" == "$required" ]]
}
[[ "$(uname -s)" == "Linux" ]] || fail '该脚本仅支持 Linux。'
[[ "$EUID" -ne 0 ]] || fail '请使用普通 Linux 账号运行;不要以 root 运行。'
[[ -t 0 ]] || fail '该脚本需要交互式终端,请通过 SSH 登录后直接执行。'
[[ -f "$SCRIPT_DIR/backend/app/main.py" && -f "$SCRIPT_DIR/frontend/package.json" ]] || fail '请从项目 deploy/install.sh 执行,或确保脚本位于项目 deploy 目录。'
command -v systemctl >/dev/null || fail '未找到 systemctl;当前系统需要 systemd。'
command -v python3 >/dev/null || fail '未找到 python3,请先安装 Python 3.10 或更高版本。'
command -v node >/dev/null || fail '未找到 node,请先安装 Node.js 18 或更高版本。'
command -v npm >/dev/null || fail '未找到 npm,请先安装 Node.js 18 或更高版本。'
systemctl --user show-environment >/dev/null 2>&1 || fail '当前账号的 systemd user manager 不可用。请通过正常 SSH 登录后重试,并确认 PAM/systemd-logind 已启动用户会话。'
PYTHON_VERSION="$(python3 -c 'import sys; print("%d.%d" % sys.version_info[:2])')"
NODE_VERSION="$(node --version | sed 's/^v//')"
version_at_least "$PYTHON_VERSION" '3.10' || fail "Python 版本过低:$PYTHON_VERSION(需要 3.10+)。"
version_at_least "$NODE_VERSION" '18.0' || fail "Node.js 版本过低:$NODE_VERSION(需要 18+)。"
printf '\n'
color '32' 'Compute Service Manager · Linux 引导式部署'
printf '运行账号:%s\n项目来源:%s\n\n' "$CURRENT_USER" "$SCRIPT_DIR"
INSTALL_DIR="$(ask '部署目录' "$DEFAULT_INSTALL_DIR")"
INSTALL_DIR="${INSTALL_DIR/#\~/$HOME}"
INSTALL_DIR="$(mkdir -p -- "$INSTALL_DIR" && cd -- "$INSTALL_DIR" && pwd)"
[[ "$INSTALL_DIR" != *[[:space:]%\\]* ]] || fail '部署目录不能包含空格、百分号或反斜杠(systemd unit 路径限制)。'
[[ "$INSTALL_DIR" != "$SCRIPT_DIR/"* ]] || fail '部署目录不能位于项目源码目录内部。'
if [[ "$INSTALL_DIR" != "$SCRIPT_DIR" ]]; then
if [[ -n "$(find "$INSTALL_DIR" -mindepth 1 -maxdepth 1 -print -quit)" ]] && ! confirm "部署目录已有文件,是否更新覆盖同名项目文件?"; then
fail '用户取消部署。'
fi
mkdir -p "$INSTALL_DIR/backend" "$INSTALL_DIR/frontend" "$INSTALL_DIR/deploy"
# Exclude machine-specific build/runtime files while copying the project source.
tar -C "$SCRIPT_DIR" \
--exclude='./backend/.venv' --exclude='./backend/__pycache__' \
--exclude='./frontend/node_modules' --exclude='./frontend/dist' \
-cf - backend frontend deploy README.md .gitignore | tar -C "$INSTALL_DIR" -xf -
fi
DEFAULT_PORT='8199'
PORT="$(ask '面板端口' "$DEFAULT_PORT")"
[[ "$PORT" =~ ^[0-9]{1,5}$ ]] && (( PORT >= 1 && PORT <= 65535 )) || fail '端口必须是 1 到 65535 之间的数字。'
BIND_HOST="$(ask '监听地址(0.0.0.0 可供内网团队访问)' '0.0.0.0')"
[[ "$BIND_HOST" =~ ^[A-Za-z0-9.:_-]+$ ]] || fail '监听地址格式无效。'
ENV_DIR="$HOME/.config/compute-service-manager"
ENV_FILE="$ENV_DIR/manager.env"
UNIT_DIR="$HOME/.config/systemd/user"
UNIT_FILE="$UNIT_DIR/compute-service-manager.service"
mkdir -p "$ENV_DIR" "$UNIT_DIR"
TOKEN=""
read -r -s -p '管理密钥(留空则自动生成):' TOKEN
printf '\n'
if [[ -z "$TOKEN" ]]; then
if command -v openssl >/dev/null; then
TOKEN="$(openssl rand -hex 32)"
else
TOKEN="$(python3 -c 'import secrets; print(secrets.token_urlsafe(48))')"
fi
fi
[[ "$TOKEN" =~ ^[A-Za-z0-9._~+/=-]+$ ]] || fail '管理密钥仅可包含字母、数字及 . _ ~ + / = - 字符。'
info '安装后端 Python 依赖…'
python3 -m venv "$INSTALL_DIR/backend/.venv"
"$INSTALL_DIR/backend/.venv/bin/python" -m pip install --upgrade pip
"$INSTALL_DIR/backend/.venv/bin/pip" install -r "$INSTALL_DIR/backend/requirements.txt"
info '安装前端依赖并构建生产页面…'
if [[ -f "$INSTALL_DIR/frontend/package-lock.json" ]]; then
(cd "$INSTALL_DIR/frontend" && npm ci)
else
(cd "$INSTALL_DIR/frontend" && npm install)
fi
(cd "$INSTALL_DIR/frontend" && npm run build)
# Keep the shared API secret out of the unit file and restrict it to this account.
umask 077
cat > "$ENV_FILE" <<EOF
PANEL_DATABASE_PATH=$HOME/.local/share/compute-service-manager/panel.db
PANEL_SERVICE_HOME=$HOME/.local/share/compute-service-manager
PANEL_UNIT_DIR=$HOME/.config/systemd/user
EOF
printf 'PANEL_API_TOKEN=%s\n' "$TOKEN" >> "$ENV_FILE"
chmod 600 "$ENV_FILE"
cat > "$UNIT_FILE" <<EOF
[Unit]
Description=Compute Service Manager
After=network.target
[Service]
Type=simple
WorkingDirectory=$INSTALL_DIR/backend
EnvironmentFile=$ENV_FILE
ExecStart=$INSTALL_DIR/backend/.venv/bin/uvicorn app.main:app --host $BIND_HOST --port $PORT
Restart=on-failure
RestartSec=3
[Install]
WantedBy=default.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now compute-service-manager.service
if command -v loginctl >/dev/null && loginctl show-user "$CURRENT_USER" -p Linger --value 2>/dev/null | grep -qx 'no'; then
if command -v sudo >/dev/null && confirm '启用 linger,使面板在退出 SSH 后仍持续运行?(需要 sudo 权限)'; then
sudo loginctl enable-linger "$CURRENT_USER" || warn 'linger 启用失败;面板可能会在退出登录后停止。'
else
warn '尚未启用 linger;面板可能会在退出登录后停止。稍后可执行:sudo loginctl enable-linger '"$CURRENT_USER"
fi
fi
HOST_IP="$(hostname -I 2>/dev/null | awk '{print $1}')"
printf '\n'
success '部署完成。'
printf '本机访问: http://127.0.0.1:%s\n' "$PORT"
if [[ -n "$HOST_IP" ]]; then
printf '内网访问: http://%s:%s\n' "$HOST_IP" "$PORT"
fi
printf '管理密钥: %s\n' "$TOKEN"
printf '密钥文件: %s(权限 600)\n' "$ENV_FILE"
printf '\n服务管理命令:\n systemctl --user status compute-service-manager\n systemctl --user restart compute-service-manager\n journalctl --user -u compute-service-manager -f\n'
warn '请通过防火墙限制访问来源;直接 HTTP 部署适用于可信内网,公网访问应配置 HTTPS 反向代理。'

View File

@ -0,0 +1,21 @@
server {
listen 443 ssl;
server_name compute.example.internal;
root /opt/compute-service-manager/frontend/dist;
index index.html;
location /api/ {
proxy_pass http://127.0.0.1:8000/api/;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
location / {
try_files $uri $uri/ /index.html;
}
}

View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="theme-color" content="#f4f6fa" />
<meta name="description" content="本机模型服务编排与算力资源监控控制台" />
<title>ComputeOS · 算力控制中心</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

View File

@ -0,0 +1,24 @@
{
"name": "compute-service-manager-web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc --noEmit && vite build",
"preview": "vite preview"
},
"dependencies": {
"@vitejs/plugin-react": "^4.3.4",
"lucide-react": "^0.468.0",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"vite": "^6.0.0"
},
"devDependencies": {
"@types/react": "^18.3.12",
"@types/react-dom": "^18.3.1",
"typescript": "^5.7.2"
}
}

View File

@ -0,0 +1,631 @@
import { useCallback, useEffect, useMemo, useState } from "react";
import type { FormEvent, ReactNode } from "react";
import {
Activity,
AlertCircle,
Check,
CircleHelp,
Cpu,
FileCode2,
Gauge,
HardDrive,
KeyRound,
ListChecks,
LoaderCircle,
MemoryStick,
MoreHorizontal,
Play,
Plus,
RefreshCw,
Search,
Server,
Settings2,
Square,
TerminalSquare,
Trash2,
X,
} from "lucide-react";
type AppStatus = "running" | "stopped" | "failed" | "unknown";
type ManagedApp = {
id: string;
name: string;
description: string;
python_path: string;
script_path: string;
working_dir: string;
args: string[];
env: Record<string, string>;
status: AppStatus;
pid: number | null;
active_since: string | null;
created_at: string;
updated_at: string;
};
type AppDraft = Pick<ManagedApp, "name" | "description" | "python_path" | "script_path" | "working_dir"> & {
args_text: string;
env_text: string;
};
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; cores: number | null; cpu_names?: string[]; load_1m: number | null } | null;
memory: { used_bytes: number; total_bytes: number; percent: number } | null;
disk: { path: string; used_bytes: number; total_bytes: number; percent: number } | null;
gpus: Array<{
index: number;
name: string;
utilization: number | null;
memory_used_mb?: number | null;
memory_total_mb?: number | null;
}>;
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";
function pageFromHash(): PageKey {
const page = window.location.hash.slice(1);
return page === "compute" || page === "runtime" || page === "services" || page === "settings" ? page : "compute";
}
const API_BASE = import.meta.env.VITE_API_BASE_URL ?? "";
const TOKEN_KEY = "compute-service-manager-token";
const emptyDraft: AppDraft = {
name: "",
description: "",
python_path: "",
script_path: "",
working_dir: "",
args_text: "",
env_text: "{}",
};
async function request<T>(path: string, token: string, init?: RequestInit): Promise<T> {
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<T>;
}
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 (
<section className="trend-panel">
<div className="panel-heading"><div><span className="panel-kicker">RESOURCE ACTIVITY</span><h2>资源使用趋势</h2></div><span className="trend-window">{samples.length ? `最近 ${samples.length * 5} 秒` : "暂无数据"}</span></div>
<div className="chart-legend"><span><i className="legend-cpu" />CPU</span><span><i className="legend-memory" />内存</span><span><i className="legend-gpu" />GPU</span></div>
<div className="chart-wrap">
<div className="chart-axis"><span>100%</span><span>50%</span><span>0%</span></div>
<svg className="trend-chart" viewBox="0 0 100 40" preserveAspectRatio="none" role="img" aria-label="CPU、内存、GPU 使用率趋势">
{[4, 21, 38].map((y) => <line key={y} x1="0" x2="100" y1={y} y2={y} className="chart-gridline" />)}
{samples.length > 1 && <>
<polyline points={line("cpu")} className="chart-line cpu-line" />
<polyline points={line("memory")} className="chart-line memory-line" />
<polyline points={line("gpu")} className="chart-line gpu-line" />
</>}
</svg>
{samples.length < 2 && <div className="chart-placeholder">暂无本机监控数据</div>}
</div>
<div className="chart-foot"><span>约 2 分钟滚动窗口</span><span>{samples.length ? new Date(samples[samples.length - 1].time).toLocaleTimeString("zh-CN", { hour12: false }) : "等待数据"}</span></div>
</section>
);
}
function ResourceCard({ icon, label, value, detail, percent, tone }: {
icon: ReactNode;
label: string;
value: string;
detail: string;
percent: number;
tone: "green" | "violet" | "blue" | "amber";
}) {
return (
<div className="resource-card">
<div className="resource-topline">
<div className={`metric-icon ${tone}`}>{icon}</div>
<span className="resource-label" title={label}>{label}</span>
<strong>{value}</strong>
</div>
<div className={`resource-track ${tone}`}><span style={{ width: `${boundedPercent(percent)}%` }} /></div>
<span className="resource-detail" title={detail}>{detail}</span>
</div>
);
}
function RuntimeStatusTable({ apps }: { apps: ManagedApp[] }) {
const statusLabels: Record<AppStatus, string> = {
running: "运行中",
stopped: "已停止",
failed: "启动失败",
unknown: "状态未知",
};
return (
<section className="runtime-panel">
<div className="panel-heading runtime-panel-heading">
<div><span className="panel-kicker">PROCESS SUPERVISION</span><h2>进程运行明细</h2></div>
<span className="runtime-refresh-note">每 5 秒自动刷新</span>
</div>
{apps.length ? (
<div className="runtime-table-wrap">
<table className="runtime-table">
<thead><tr><th>服务</th><th>状态</th><th>进程 ID</th><th>启动时间</th><th>入口脚本</th></tr></thead>
<tbody>{apps.map((item) => (
<tr key={item.id}>
<td><strong>{item.name}</strong><small>{item.description || "Python 服务"}</small></td>
<td><span className={`runtime-status ${item.status}`}><i />{statusLabels[item.status]}</span></td>
<td>{item.pid ?? "—"}</td>
<td>{item.active_since ? formatTime(item.active_since) : "—"}</td>
<td className="runtime-path" title={item.script_path}>{item.script_path}</td>
</tr>
))}</tbody>
</table>
</div>
) : <div className="runtime-empty">尚无已登记的服务运行状态</div>}
</section>
);
}
function App() {
const [activePage, setActivePage] = useState<PageKey>(pageFromHash);
const [token, setToken] = useState(() => sessionStorage.getItem(TOKEN_KEY) ?? "");
const [apps, setApps] = useState<ManagedApp[]>([]);
const [metrics, setMetrics] = useState<SystemMetrics | null>(null);
const [metricSamples, setMetricSamples] = useState<MetricSample[]>([]);
const [loading, setLoading] = useState(false);
const [notice, setNotice] = useState("");
const [error, setError] = useState("");
const [search, setSearch] = useState("");
const [modal, setModal] = useState<"add" | "edit" | "logs" | null>(null);
const [selected, setSelected] = useState<ManagedApp | null>(null);
const [draft, setDraft] = useState<AppDraft>(emptyDraft);
const [busyId, setBusyId] = useState("");
const [logLines, setLogLines] = useState<string[]>([]);
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);
}, []);
function navigateTo(page: PageKey) {
if (window.location.hash === `#${page}`) setActivePage(page);
else window.location.hash = page;
}
const loadApps = useCallback(async () => {
if (!token) return;
setLoading(true);
try {
const result = await request<ManagedApp[]>("/api/apps", token);
setApps(result);
setError("");
} catch (reason) {
setError(reason instanceof Error ? reason.message : "无法连接管理服务");
} finally {
setLoading(false);
}
}, [token]);
const loadMetrics = useCallback(async () => {
if (!token) return;
try {
setMetrics(await request<SystemMetrics>("/api/system/metrics", token));
} catch {
// 资源监控暂时不可用时保留最近一次数据,不影响服务启停操作。
}
}, [token]);
useEffect(() => {
if (token) {
sessionStorage.setItem(TOKEN_KEY, token);
void loadApps();
void loadMetrics();
}
}, [token, loadApps, loadMetrics]);
useEffect(() => {
if (!token) return;
// 定时刷新卡片状态,后端仍由 systemd 负责进程托管。
const timer = window.setInterval(() => {
void loadApps();
void loadMetrics();
}, 5000);
return () => window.clearInterval(timer);
}, [token, loadApps, loadMetrics]);
const filteredApps = useMemo(() => {
const needle = search.trim().toLowerCase();
if (!needle) return apps;
return apps.filter((item) => `${item.name} ${item.description} ${item.script_path}`.toLowerCase().includes(needle));
}, [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);
setError("");
setNotice("");
try {
await request<ManagedApp>(`/api/apps/${item.id}/actions`, token, {
method: "POST",
body: JSON.stringify({ action }),
});
setNotice(`${item.name}:${action === "start" ? "启动请求已发送" : action === "stop" ? "停止请求已发送" : "重启请求已发送"}`);
await loadApps();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "操作失败");
} finally {
setBusyId("");
}
}
function openAdd() {
setSelected(null);
setDraft(emptyDraft);
setModal("add");
}
function openEdit(item: ManagedApp) {
setSelected(item);
setDraft({
name: item.name,
description: item.description,
python_path: item.python_path,
script_path: item.script_path,
working_dir: item.working_dir,
args_text: JSON.stringify(item.args, null, 2),
env_text: JSON.stringify(item.env, null, 2),
});
setModal("edit");
}
async function saveApp(event: FormEvent) {
event.preventDefault();
setError("");
try {
const env = JSON.parse(draft.env_text || "{}") as Record<string, string>;
const args = JSON.parse(draft.args_text || "[]") as unknown;
if (!Array.isArray(args) || !args.every((value) => typeof value === "string")) {
throw new Error("启动参数必须是字符串数组,例如 [\"--port\", \"8000\"]");
}
const payload = {
name: draft.name,
description: draft.description,
python_path: draft.python_path,
script_path: draft.script_path,
working_dir: draft.working_dir,
args,
env,
};
const path = selected ? `/api/apps/${selected.id}` : "/api/apps";
await request<ManagedApp>(path, token, { method: selected ? "PUT" : "POST", body: JSON.stringify(payload) });
setModal(null);
setNotice(selected ? "应用配置已更新" : "应用已添加");
await loadApps();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "配置格式不正确");
}
}
async function showLogs(item: ManagedApp) {
setSelected(item);
setLogLines([]);
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) {
if (!window.confirm(`确认删除“${item.name}”的登记配置?`)) return;
try {
await request<void>(`/api/apps/${item.id}`, token, { method: "DELETE" });
setNotice("应用配置已删除");
await loadApps();
} catch (reason) {
setError(reason instanceof Error ? reason.message : "删除失败");
}
}
function saveToken(value: string) {
const nextToken = value.trim();
if (!nextToken) return;
setToken(nextToken);
sessionStorage.setItem(TOKEN_KEY, nextToken);
setError("");
setNotice("管理密钥已保存在当前会话");
}
function clearToken() {
sessionStorage.removeItem(TOKEN_KEY);
setToken("");
setApps([]);
setMetrics(null);
setMetricSamples([]);
setNotice("已清除当前浏览器会话中的管理密钥");
}
const pageTitles: Record<PageKey, string> = { compute: "算力监控", services: "服务管理", runtime: "运行状态", settings: "设置" };
return (
<main className="shell">
<aside className="rail">
<div className="rail-brand"><div className="brand-mark"><Activity size={19} strokeWidth={2.4} /></div><div className="brand-copy"><strong>Compute<span>OS</span></strong><small>CONTROL PLANE</small></div></div>
<div className="rail-divider" />
<span className="rail-caption">工作空间</span>
<button className={`rail-button ${activePage === "compute" ? "active" : ""}`} title="算力监控" aria-current={activePage === "compute" ? "page" : undefined} onClick={() => navigateTo("compute")}><Activity size={18} /><span>算力监控</span></button>
<button className={`rail-button ${activePage === "services" ? "active" : ""}`} title="服务管理" aria-current={activePage === "services" ? "page" : undefined} onClick={() => navigateTo("services")}><Server size={18} /><span>服务管理</span><b>{apps.length}</b></button>
<button className={`rail-button ${activePage === "runtime" ? "active" : ""}`} title="运行状态" aria-current={activePage === "runtime" ? "page" : undefined} onClick={() => navigateTo("runtime")}><ListChecks size={18} /><span>运行状态</span></button>
<div className="rail-spacer" />
<button className={`rail-button ${activePage === "settings" ? "active" : ""}`} title="设置" aria-current={activePage === "settings" ? "page" : undefined} onClick={() => navigateTo("settings")}><Settings2 size={18} /><span>设置</span></button>
<div className="rail-node"><span className={`online-dot ${!metrics?.server || !metrics.server.is_online ? "offline-dot" : ""}`} /><div><b>本机节点</b><small>{metrics?.server ? "本机采集在线" : "等待本机采集"}</small></div></div>
</aside>
<section className="workspace">
<header className="topbar">
<div className="breadcrumbs"><span>工作空间</span><span className="crumb-separator">/</span><strong>{pageTitles[activePage]}</strong></div>
<div className="top-actions">
<div className="server-pill"><span className={`online-dot ${!metrics?.server || !metrics.server.is_online ? "offline-dot" : ""}`} /><span>{metrics?.server?.name ?? "本机节点"}</span></div>
<button className="icon-button" title="设置" onClick={() => navigateTo("settings")}><KeyRound size={16} /></button>
<button className="icon-button" title="刷新" onClick={() => { void loadApps(); void loadMetrics(); }}><RefreshCw size={16} className={loading ? "spin" : ""} /></button>
</div>
</header>
<div className="content">
{error && <div className="alert error-alert"><AlertCircle size={16} /><span>{error}</span><button onClick={() => setError("")}><X size={14} /></button></div>}
{notice && <div className="alert success-alert"><Check size={16} /><span>{notice}</span><button onClick={() => setNotice("")}><X size={14} /></button></div>}
{activePage === "services" && <>
<section className="hero-row page-hero">
<div><div className="eyebrow"><span className="eyebrow-line" />SERVICE CONTROL</div><h1>服务管理</h1><p className="subtitle">管理已登记的服务,按需启动、停止或查看日志。</p></div>
<button className="primary-button" disabled={!token} title={!token ? "请先在设置页配置管理密钥" : undefined} onClick={openAdd}><Plus size={17} />添加服务</button>
</section>
</>}
{activePage === "compute" && <>
<section className="hero-row page-hero">
<div><div className="eyebrow"><span className="eyebrow-line" />COMPUTE MONITORING</div><h1>算力监控</h1><p className="subtitle">查看节点资源占用、硬件信息与近期变化趋势。</p></div>
<div className={`connection-badge ${metrics?.connection_status === "connected" ? "connected" : ""}`}><span className={`online-dot ${metrics?.connection_status === "connected" ? "" : "offline-dot"}`} />{!token ? "请在设置中配置管理密钥" : metrics?.connection_status === "connected" ? "本机采集正常" : metrics?.connection_status === "unavailable" ? "本机采集不可用" : "正在采集"}</div>
</section>
<section className="metrics-row" id="resources">
<ResourceCard icon={<Cpu size={17} />} 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" />
<ResourceCard icon={<MemoryStick size={17} />} 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" />
<ResourceCard icon={<Activity size={17} />} label={primaryGpu ? `GPU ${primaryGpu.index} · ${primaryGpu.name}` : "GPU 利用率"} value={gpuPercent == null ? "暂无数据" : `${gpuPercent.toFixed(1)}%`} detail={gpuMemoryText} percent={gpuPercent ?? 0} tone="blue" />
<ResourceCard icon={<HardDrive size={17} />} 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" />
</section>
<div className="monitor-caption"><span className={`online-dot ${metrics?.connection_status === "connected" ? "" : "offline-dot"}`} />数据来源 · 本机系统采集<span className="caption-separator">·</span>每 5 秒刷新{metrics?.captured_at ? ` · 更新于 ${new Date(metrics.captured_at).toLocaleTimeString("zh-CN", { hour12: false })}` : ""}</div>
{metrics?.error && <div className="monitor-warning"><AlertCircle size={15} /><span>{metrics.error}</span></div>}
<section className="monitor-grid">
<MetricTrend samples={metricSamples} />
<section className="host-panel">
<div className="panel-heading"><div><span className="panel-kicker">NODE PROFILE</span><h2>节点概况</h2></div><div className={`host-state ${metrics?.server?.is_online ? "online" : ""}`}><span />{metrics?.server ? "本机在线" : "暂无数据"}</div></div>
{metrics?.server ? <>
<div className="host-identity"><div className="host-symbol"><Server size={21} /></div><div><strong>{metrics.server.name}</strong><span>{metrics.server.platform || "Linux compute node"}{metrics.server.id ? ` · ID ${metrics.server.id}` : ""}</span></div></div>
<div className="host-details">
<div><span>处理器</span><b title={metrics.server.cpu_names.join(", ")}>{metrics.server.cpu_names[0] ?? "暂无数据"}</b></div>
<div><span>加速器</span><b title={metrics.server.gpu_names.join(", ")}>{metrics.server.gpu_names.join(" · ") || "暂无数据"}</b></div>
<div><span>运行时间</span><b>{formatUptime(metrics.server.uptime_seconds)}</b></div>
<div><span>网络吞吐</span><b>{metrics.network ? `↓ ${formatBytes(metrics.network.in_bytes_per_second)}/s ↑ ${formatBytes(metrics.network.out_bytes_per_second)}/s` : "暂无数据"}</b></div>
</div>
</> : <div className="host-empty">暂无本机采集数据</div>}
</section>
</section>
</>}
{activePage === "services" && <>
<section className="section-heading" id="services">
<div><div><span className="panel-kicker">MANAGED SERVICES</span><h2>已登记服务</h2></div><span className="section-count">{apps.length.toString().padStart(2, "0")}</span><span className="service-summary"><i className="service-dot" />{runningCount} 运行中 <span>·</span> {failedCount} 异常</span></div>
<div className="section-tools">
<label className="search-box"><Search size={15} /><input value={search} onChange={(event) => setSearch(event.target.value)} placeholder="搜索应用或路径" /></label>
<button className="filter-button" onClick={() => { void loadApps(); void loadMetrics(); }}><RefreshCw size={14} />刷新状态</button>
</div>
</section>
{!token ? null : loading && apps.length === 0 ? (
<div className="loading-state"><LoaderCircle size={20} className="spin" />正在读取本机服务…</div>
) : filteredApps.length ? (
<div className="app-grid">
{filteredApps.map((item) => <ServiceCard key={item.id} item={item} busy={busyId === item.id} onAction={runAction} onLogs={showLogs} onEdit={openEdit} onDelete={deleteApp} />)}
<button className="add-card" onClick={openAdd}>
<span className="add-card-icon"><Plus size={19} /></span>
<strong>登记新的应用服务</strong>
<span>绑定 Python 环境与启动脚本</span>
</button>
</div>
) : (
<section className="empty-state">
<div className="empty-icon"><FileCode2 size={22} /></div>
<h3>{search ? "没有匹配的应用" : "还没有登记应用"}</h3>
<p>{search ? "试试其他应用名称或目录。" : "添加已有的 Python 服务,即可从卡片快捷启停。"}</p>
{!search && <button className="primary-button" onClick={openAdd}><Plus size={16} />添加第一个应用</button>}
</section>
)}
</>}
{activePage === "runtime" && <>
<section className="hero-row page-hero">
<div><div className="eyebrow"><span className="eyebrow-line" />RUNTIME STATUS</div><h1>运行状态</h1><p className="subtitle">集中查看登记服务的 systemd 进程状态与启动信息。</p></div>
<button className="filter-button runtime-refresh" onClick={() => { void loadApps(); void loadMetrics(); }}><RefreshCw size={14} className={loading ? "spin" : ""} />立即刷新</button>
</section>
<section className="runtime-kpis">
<div><span className="runtime-kpi-icon green"><Play size={17} /></span><small>运行中</small><strong>{runningCount}</strong></div>
<div><span className="runtime-kpi-icon amber"><AlertCircle size={17} /></span><small>启动异常</small><strong>{failedCount}</strong></div>
<div><span className="runtime-kpi-icon blue"><Server size={17} /></span><small>已登记服务</small><strong>{apps.length}</strong></div>
<div><span className="runtime-kpi-icon violet"><Gauge size={17} /></span><small>刷新频率</small><strong>5<span>秒</span></strong></div>
</section>
{token ? loading && apps.length === 0 ? <div className="loading-state"><LoaderCircle size={20} className="spin" />正在读取本机服务…</div> : <RuntimeStatusTable apps={apps} /> : null}
</>}
{activePage === "settings" && <>
<section className="hero-row page-hero">
<div><div className="eyebrow"><span className="eyebrow-line" />PANEL SETTINGS</div><h1>设置</h1><p className="subtitle">配置本机管理服务的访问密钥。</p></div>
</section>
<SettingsPanel currentToken={token} onSave={saveToken} onClear={clearToken} />
</>}
<footer className="footer"><span>COMPUTE SERVICE MANAGER <i>·</i> LOCAL CONTROL PLANE</span><button><CircleHelp size={13} />使用说明</button></footer>
</div>
</section>
{modal === "add" || modal === "edit" ? (
<div className="modal-backdrop" onMouseDown={() => setModal(null)}>
<section className="modal app-modal" onMouseDown={(event) => event.stopPropagation()}>
<div className="modal-head"><div><span className="modal-kicker">SERVICE CONFIGURATION</span><h2>{selected ? "编辑应用" : "添加应用"}</h2></div><button className="icon-button" onClick={() => setModal(null)}><X size={17} /></button></div>
<form onSubmit={saveApp}>
<div className="form-grid">
<FormField label="应用名称" required><input required value={draft.name} onChange={(event) => setDraft({ ...draft, name: event.target.value })} placeholder="例如:Gemma 4 31B" /></FormField>
<FormField label="说明"><input value={draft.description} onChange={(event) => setDraft({ ...draft, description: event.target.value })} placeholder="例如:推理服务、Embedding 或其他" /></FormField>
<FormField label="Python 解释器" required hint="填写 conda 环境或 .venv 中的 python 绝对路径"><input required value={draft.python_path} onChange={(event) => setDraft({ ...draft, python_path: event.target.value })} placeholder="/opt/conda/envs/gemma/bin/python" /></FormField>
<FormField label="启动脚本" required><input required value={draft.script_path} onChange={(event) => setDraft({ ...draft, script_path: event.target.value })} placeholder="/dep/project/serve.py" /></FormField>
<FormField label="工作目录" required><input required value={draft.working_dir} onChange={(event) => setDraft({ ...draft, working_dir: event.target.value })} placeholder="/dep/project" /></FormField>
<FormField label="启动参数 JSON" hint="字符串数组可正确保留路径和参数中的空格"><textarea rows={3} value={draft.args_text} onChange={(event) => setDraft({ ...draft, args_text: event.target.value })} placeholder={'["--port", "8000"]'} spellCheck={false} /></FormField>
<FormField label="环境变量 JSON" hint="可填写 CUDA_VISIBLE_DEVICES、HF_HOME 等"><textarea rows={4} value={draft.env_text} onChange={(event) => setDraft({ ...draft, env_text: event.target.value })} spellCheck={false} /></FormField>
</div>
<div className="form-note"><CircleHelp size={14} /><span>服务将由当前登录 Linux 用户的 systemd user manager 运行。请确认该用户有权读取模型与脚本目录。</span></div>
<div className="modal-actions"><button type="button" className="secondary-button" onClick={() => setModal(null)}>取消</button><button className="primary-button" type="submit">{selected ? "保存配置" : "登记应用"}</button></div>
</form>
</section>
</div>
) : null}
{modal === "logs" && selected ? (
<div className="modal-backdrop" onMouseDown={() => setModal(null)}>
<section className="modal logs-modal" onMouseDown={(event) => event.stopPropagation()}>
<div className="modal-head"><div><span className="modal-kicker">JOURNAL OUTPUT</span><h2>{selected.name} <small>最近日志</small></h2></div><button className="icon-button" onClick={() => setModal(null)}><X size={17} /></button></div>
<div className="terminal-head"><TerminalSquare size={14} />systemd journal <button onClick={() => void showLogs(selected)}><RefreshCw size={13} />重新读取</button></div>
<pre className="log-output">{logLines.length ? logLines.join("\n") : "暂无日志输出"}</pre>
</section>
</div>
) : null}
</main>
);
}
function ServiceCard({
item,
busy,
onAction,
onLogs,
onEdit,
onDelete,
}: {
item: ManagedApp;
busy: boolean;
onAction: (item: ManagedApp, action: "start" | "stop" | "restart") => void;
onLogs: (item: ManagedApp) => void;
onEdit: (item: ManagedApp) => void;
onDelete: (item: ManagedApp) => void;
}) {
const [menuOpen, setMenuOpen] = useState(false);
const running = item.status === "running";
const failed = item.status === "failed";
const statusText = running ? "运行中" : failed ? "启动失败" : item.status === "unknown" ? "状态未知" : "已停止";
return (
<article className={`service-card ${running ? "is-running" : ""}`}>
<div className="card-topline"><div className={`service-icon ${running ? "running" : failed ? "failed" : ""}`}><Cpu size={19} /></div><div className={`status-badge ${running ? "running" : failed ? "failed" : "stopped"}`}><span />{statusText}</div><div className="menu-wrap"><button className="more-button" onClick={() => setMenuOpen(!menuOpen)}><MoreHorizontal size={18} /></button>{menuOpen && <div className="card-menu"><button onClick={() => { setMenuOpen(false); onEdit(item); }}><Settings2 size={14} />编辑配置</button><button className="danger-menu" onClick={() => { setMenuOpen(false); onDelete(item); }}><Trash2 size={14} />删除登记</button></div>}</div></div>
<div className="card-title-row"><div><h3>{item.name}</h3><p>{item.description || "Python 服务"}</p></div></div>
<div className="service-path"><FileCode2 size={13} /><span title={item.script_path}>{item.script_path}</span></div>
<div className="runtime-row"><div><span>运行时</span><b title={item.python_path}>{item.python_path}</b></div><div><span>进程 PID</span><b>{item.pid ?? "—"}</b></div></div>
<div className="card-meta"><span><span className="meta-dot" />{running ? `启动于 ${formatTime(item.active_since)}` : `更新于 ${formatTime(item.updated_at)}`}</span><button onClick={() => onLogs(item)}><TerminalSquare size={13} />日志</button></div>
<div className="card-actions">
{running ? <button className="stop-button" disabled={busy} onClick={() => onAction(item, "stop")}>{busy ? <LoaderCircle size={15} className="spin" /> : <Square size={13} fill="currentColor" />}停止服务</button> : <button className="start-button" disabled={busy} onClick={() => onAction(item, "start")}>{busy ? <LoaderCircle size={15} className="spin" /> : <Play size={14} fill="currentColor" />}启动服务</button>}
<button className="restart-button" disabled={busy} title="重启服务" onClick={() => onAction(item, "restart")}><RefreshCw size={15} /></button>
</div>
</article>
);
}
function FormField({ label, required, hint, children }: { label: string; required?: boolean; hint?: string; children: ReactNode }) {
return <label className="form-field"><span>{label}{required && <i> *</i>}</span>{hint && <small>{hint}</small>}{children}</label>;
}
function SettingsPanel({ currentToken, onSave, onClear }: { currentToken: string; onSave: (token: string) => void; onClear: () => void }) {
const [value, setValue] = useState("");
return (
<section className="settings-panel">
<div className="panel-heading"><div><span className="panel-kicker">ACCESS CONTROL</span><h2>管理密钥</h2></div><span className={`settings-token-status ${currentToken ? "configured" : ""}`}><i />{currentToken ? "已配置" : "未配置"}</span></div>
<p className="settings-description">填写部署时设置的 <code>PANEL_API_TOKEN</code>。密钥仅保存在当前浏览器标签页会话中,用于访问服务管理和本机监控数据。</p>
<form className="settings-token-form" onSubmit={(event) => { event.preventDefault(); onSave(value); setValue(""); }}>
<label htmlFor="panel-token">{currentToken ? "更换管理密钥" : "管理密钥"}</label>
{/* Never echo the active secret back into the form; users enter a replacement explicitly. */}
<input id="panel-token" type="password" autoComplete="new-password" value={value} onChange={(event) => setValue(event.target.value)} placeholder={currentToken ? "已配置;输入新密钥以更换" : "粘贴 PANEL_API_TOKEN"} />
<div className="settings-token-actions">
<button className="primary-button" type="submit" disabled={!value.trim()}>{currentToken ? "更新密钥" : "保存并连接"}</button>
{currentToken && <button className="secondary-button" type="button" onClick={onClear}>清除本地密钥</button>}
</div>
</form>
</section>
);
}
export default App;

View File

@ -0,0 +1,11 @@
import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./styles.css";
ReactDOM.createRoot(document.getElementById("root")!).render(
<React.StrictMode>
<App />
</React.StrictMode>,
);

View File

@ -0,0 +1,483 @@
:root {
font-family: "Segoe UI", "Microsoft YaHei", sans-serif;
color: #e9eef2;
background: #0b1016;
font-synthesis: none;
text-rendering: optimizeLegibility;
--surface: #111820;
--surface-raised: #151e28;
--line: rgba(164, 183, 198, .12);
--muted: #82909c;
--green: #72e0b4;
--mono: "DM Mono", Consolas, monospace;
}
* { box-sizing: border-box; }
body { margin: 0; min-width: 320px; min-height: 100vh; background: #0b1016; }
button, input, textarea { font: inherit; }
button { color: inherit; cursor: pointer; }
button:disabled { opacity: .56; cursor: wait; }
.shell { min-height: 100vh; display: flex; }
.rail { width: 68px; min-height: 100vh; flex: 0 0 68px; border-right: 1px solid var(--line); background: #0d131a; display: flex; align-items: center; flex-direction: column; padding: 18px 0 16px; gap: 13px; }
.brand-mark { width: 36px; height: 36px; border: 1px solid rgba(114,224,180,.35); border-radius: 11px; color: var(--green); background: rgba(57,172,128,.12); display: grid; place-items: center; box-shadow: 0 0 24px rgba(60,210,155,.08); }
.rail-divider { width: 28px; height: 1px; background: var(--line); margin: 4px 0 2px; }
.rail-button { width: 38px; height: 38px; border: 0; background: transparent; color: #75838f; display: grid; place-items: center; border-radius: 10px; transition: .18s ease; }
.rail-button:hover, .rail-button.active { color: var(--green); background: rgba(114,224,180,.11); }
.rail-spacer { flex: 1; }
.avatar { height: 30px; width: 30px; display: grid; place-items: center; border-radius: 50%; background: #263442; border: 1px solid #405365; color: #b8c8d4; font: 10px var(--mono); }
.workspace { min-width: 0; flex: 1; }
.topbar { height: 64px; border-bottom: 1px solid var(--line); padding: 0 clamp(22px, 4vw, 56px); display: flex; align-items: center; justify-content: space-between; }
.breadcrumbs { display: flex; align-items: center; gap: 10px; font-size: 12px; color: #75838f; }
.breadcrumbs strong { color: #d8e0e7; font-weight: 600; }
.crumb-separator { color: #46535f; }
.top-actions { display: flex; align-items: center; gap: 10px; }
.server-pill { height: 32px; display: flex; align-items: center; gap: 8px; border: 1px solid var(--line); border-radius: 8px; padding: 0 10px; color: #aebbc5; font-size: 11px; }
.online-dot { width: 7px; height: 7px; display: inline-block; border-radius: 50%; background: var(--green); box-shadow: 0 0 9px rgba(114,224,180,.62); }
.icon-button { width: 33px; height: 33px; display: grid; place-items: center; border: 1px solid var(--line); border-radius: 8px; background: #121a22; color: #92a0aa; }
.icon-button:hover { border-color: rgba(114,224,180,.35); color: var(--green); }
.content { width: min(1240px, 100%); margin: 0 auto; padding: 45px clamp(22px, 4vw, 56px) 28px; }
.hero-row { display: flex; justify-content: space-between; align-items: flex-end; gap: 24px; }
.eyebrow, .modal-kicker { display: flex; align-items: center; gap: 8px; color: #71808c; font: 10px var(--mono); letter-spacing: .12em; }
.eyebrow-line { width: 17px; height: 1px; background: var(--green); }
h1 { margin: 13px 0 8px; font: 700 clamp(30px, 4vw, 42px)/1.12 Manrope, sans-serif; letter-spacing: -.045em; }
.title-dot { color: var(--green); }
.subtitle { margin: 0; color: #81909b; font-size: 13px; }
.primary-button { min-height: 38px; padding: 0 15px; border: 1px solid #74e3b8; border-radius: 8px; display: inline-flex; align-items: center; justify-content: center; gap: 8px; background: #70ddb2; color: #092017; font-size: 12px; font-weight: 700; box-shadow: 0 5px 18px rgba(63,194,144,.12); transition: .18s ease; }
.primary-button:hover { background: #8bf0c8; transform: translateY(-1px); }
.metrics-row { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 11px; margin: 34px 0 10px; }
.resource-card { min-width: 0; min-height: 112px; padding: 14px; border: 1px solid var(--line); border-radius: 11px; background: linear-gradient(140deg, #131b23, #10171e); }
.metric-icon, .node-icon { width: 34px; height: 34px; display: grid; place-items: center; border-radius: 9px; flex: 0 0 34px; }
.metric-icon.green { color: var(--green); background: rgba(66,189,139,.12); }
.metric-icon.violet { color: #b4a5ff; background: rgba(132,112,255,.12); }
.metric-icon.amber { color: #f3bf76; background: rgba(240,174,84,.12); }
.metric-icon.blue { color: #86b9ff; background: rgba(92,155,234,.13); }
.resource-topline { min-width: 0; display: flex; align-items: center; gap: 9px; }
.resource-label { overflow: hidden; min-width: 0; color: #8997a1; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
.resource-topline strong { margin-left: auto; color: #e4ebef; font: 600 20px Manrope, sans-serif; letter-spacing: -.04em; }
.resource-track { height: 5px; overflow: hidden; margin: 13px 0 9px; border-radius: 5px; background: #26313a; }
.resource-track span { height: 100%; display: block; border-radius: inherit; background: var(--green); transition: width .35s ease; }
.resource-track.violet span { background: #aa98ff; }
.resource-track.blue span { background: #78b3ff; }
.resource-track.amber span { background: #efb66c; }
.resource-detail { overflow: hidden; display: block; color: #71808a; font: 9px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
.monitor-caption { display: flex; align-items: center; justify-content: flex-end; gap: 7px; margin: 0 2px 34px; color: #65737e; font-size: 9px; }
.monitor-caption .online-dot { width: 5px; height: 5px; }
.section-heading { display: flex; justify-content: space-between; align-items: center; margin-bottom: 17px; }
.section-heading>div:first-child { display: flex; align-items: center; gap: 10px; }
.service-summary { color: #788690; font-size: 10px; }
h2 { margin: 0; font: 600 17px Manrope, sans-serif; letter-spacing: -.02em; }
.section-count { min-width: 24px; height: 19px; display: grid; place-items: center; border: 1px solid var(--line); border-radius: 5px; color: #91a0aa; font: 10px var(--mono); }
.section-tools { display: flex; gap: 8px; }
.search-box { width: 210px; height: 33px; padding: 0 10px; display: flex; align-items: center; gap: 7px; border: 1px solid var(--line); border-radius: 7px; color: #697984; background: #0f161d; }
.search-box input { width: 100%; padding: 0; border: 0; outline: 0; background: transparent; color: #dce5ea; font-size: 11px; }
.search-box input::placeholder { color: #66747e; }
.filter-button { height: 33px; padding: 0 10px; display: inline-flex; align-items: center; gap: 6px; border: 1px solid var(--line); border-radius: 7px; color: #9ba9b2; background: #121a22; font-size: 10px; }
.filter-button:hover { color: var(--green); }
.app-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 13px; }
.service-card { position: relative; min-width: 0; padding: 17px 17px 14px; border: 1px solid rgba(165,184,200,.13); border-radius: 11px; background: linear-gradient(145deg, rgba(21,30,39,.95), rgba(15,22,29,.98)); transition: border-color .2s, transform .2s, box-shadow .2s; }
.service-card:hover { border-color: rgba(142,171,190,.28); transform: translateY(-2px); box-shadow: 0 12px 30px rgba(0,0,0,.15); }
.service-card.is-running { border-color: rgba(114,224,180,.3); box-shadow: inset 0 1px 0 rgba(114,224,180,.04); }
.card-topline { display: flex; align-items: center; gap: 8px; }
.service-icon { width: 37px; height: 37px; display: grid; place-items: center; border: 1px solid rgba(139,158,174,.15); border-radius: 10px; color: #aebbc6; background: #1a2631; }
.service-icon.running { border-color: rgba(114,224,180,.2); color: var(--green); background: rgba(66,189,139,.1); }
.service-icon.failed { color: #ff8e82; background: rgba(240,91,83,.1); }
.status-badge { height: 22px; display: flex; align-items: center; gap: 6px; padding: 0 8px; border: 1px solid transparent; border-radius: 20px; font-size: 9px; }
.status-badge span { width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
.status-badge.running { color: #83e4bc; border-color: rgba(114,224,180,.18); background: rgba(69,192,143,.08); }
.status-badge.stopped { color: #8d9aa5; border-color: rgba(141,154,165,.12); background: rgba(111,128,140,.07); }
.status-badge.failed { color: #ff9a8f; border-color: rgba(255,129,116,.18); background: rgba(255,129,116,.08); }
.menu-wrap { position: relative; margin-left: auto; }
.more-button { width: 28px; height: 28px; display: grid; place-items: center; border: 0; background: transparent; color: #76848e; border-radius: 6px; }
.more-button:hover { color: white; background: rgba(255,255,255,.06); }
.card-menu { position: absolute; z-index: 2; right: 0; top: 30px; width: 130px; padding: 5px; border: 1px solid #33414c; border-radius: 8px; background: #1a242d; box-shadow: 0 10px 28px rgba(0,0,0,.4); }
.card-menu button { width: 100%; padding: 8px; border: 0; border-radius: 5px; display: flex; align-items: center; gap: 8px; background: transparent; color: #bec9d0; text-align: left; font-size: 10px; }
.card-menu button:hover { background: rgba(255,255,255,.06); }
.card-menu .danger-menu { color: #f28b82; }
.card-title-row { margin: 14px 0 12px; }
.card-title-row h3 { overflow: hidden; margin: 0 0 4px; color: #e3eaee; font: 600 14px Manrope, sans-serif; text-overflow: ellipsis; white-space: nowrap; }
.card-title-row p { overflow: hidden; margin: 0; color: #788690; font-size: 10px; text-overflow: ellipsis; white-space: nowrap; }
.service-path { display: flex; align-items: center; gap: 7px; padding: 9px 9px; border: 1px solid rgba(154,172,186,.1); border-radius: 6px; background: rgba(9,14,19,.48); color: #87a1ae; }
.service-path svg { flex: 0 0 auto; color: #718c9b; }
.service-path span { overflow: hidden; color: #9eacb5; font: 9px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
.runtime-row { display: grid; grid-template-columns: 1fr auto; gap: 10px; padding: 12px 0 10px; }
.runtime-row>div { display: grid; gap: 5px; min-width: 0; }
.runtime-row span { color: #697883; font-size: 9px; }
.runtime-row b { overflow: hidden; color: #b7c2ca; font: 9px var(--mono); text-overflow: ellipsis; white-space: nowrap; }
.card-meta { padding: 9px 0 11px; border-top: 1px solid rgba(154,172,186,.09); display: flex; align-items: center; justify-content: space-between; gap: 6px; color: #74828c; font-size: 9px; }
.card-meta>span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.meta-dot { width: 5px; height: 5px; margin-right: 6px; display: inline-block; border-radius: 50%; background: #70818e; vertical-align: 1px; }
.is-running .meta-dot { background: var(--green); }
.card-meta button { flex: 0 0 auto; padding: 3px 0 3px 6px; display: flex; align-items: center; gap: 5px; border: 0; background: transparent; color: #84939d; font-size: 9px; }
.card-meta button:hover { color: var(--green); }
.card-actions { display: flex; gap: 7px; }
.start-button, .stop-button { height: 33px; flex: 1; display: flex; align-items: center; justify-content: center; gap: 7px; border: 1px solid rgba(114,224,180,.34); border-radius: 6px; background: rgba(81,199,149,.1); color: #80e4b9; font-size: 10px; font-weight: 600; }
.start-button:hover { background: rgba(81,199,149,.18); }
.stop-button { border-color: rgba(232,144,123,.28); background: rgba(213,109,91,.08); color: #e6a090; }
.stop-button:hover { background: rgba(213,109,91,.14); }
.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-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; }
.empty-state { min-height: 270px; border: 1px dashed rgba(144,163,177,.2); border-radius: 11px; display: flex; align-items: center; justify-content: center; flex-direction: column; text-align: center; background: rgba(14,21,28,.36); }
.empty-icon { width: 46px; height: 46px; margin-bottom: 13px; display: grid; place-items: center; border: 1px solid rgba(114,224,180,.2); border-radius: 13px; color: var(--green); background: rgba(57,172,128,.09); }
.empty-state h3 { margin: 0 0 6px; color: #d6e0e5; font-size: 13px; }
.empty-state p { margin: 0 0 17px; color: #7b8992; font-size: 10px; }
.loading-state { min-height: 250px; display: flex; align-items: center; justify-content: center; gap: 10px; color: #87959f; font-size: 12px; }
.footer { margin-top: 44px; padding-top: 16px; border-top: 1px solid var(--line); display: flex; justify-content: space-between; align-items: center; color: #5f6d77; font: 9px var(--mono); letter-spacing: .05em; }
.footer i { color: var(--green); font-style: normal; }
.footer button { display: flex; align-items: center; gap: 5px; border: 0; background: transparent; color: #77858f; font-size: 10px; }
.alert { margin: -2px 0 14px; padding: 10px 12px; display: flex; align-items: center; gap: 8px; border: 1px solid; border-radius: 7px; font-size: 11px; }
.alert button { margin-left: auto; display: grid; place-items: center; border: 0; background: transparent; color: inherit; }
.error-alert { border-color: rgba(255,128,116,.2); background: rgba(194,78,68,.09); color: #ffaaa0; }
.success-alert { border-color: rgba(114,224,180,.2); background: rgba(57,172,128,.08); color: #8ee8c1; }
.modal-backdrop { position: fixed; inset: 0; z-index: 10; padding: 22px; display: grid; place-items: center; background: rgba(3,7,10,.72); backdrop-filter: blur(8px); }
.modal { width: min(650px, 100%); max-height: min(90vh, 850px); overflow: auto; border: 1px solid #2a3843; border-radius: 13px; background: #121a22; box-shadow: 0 24px 80px rgba(0,0,0,.48); }
.modal-head { padding: 19px 21px 16px; border-bottom: 1px solid var(--line); display: flex; align-items: center; justify-content: space-between; }
.modal-kicker { margin-bottom: 6px; font-size: 9px; }
.modal-head h2 { font-size: 17px; }
.modal-head h2 small { margin-left: 5px; color: #84929d; font: 10px "DM Sans", sans-serif; }
.app-modal form { padding: 17px 21px 20px; }
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 13px; }
.form-field { min-width: 0; display: grid; gap: 6px; }
.form-field>span { color: #b8c3ca; font-size: 10px; font-weight: 600; }
.form-field>span i { color: #e99a80; font-style: normal; }
.form-field small { color: #71808b; font-size: 9px; line-height: 1.4; }
.form-field input, .form-field textarea { width: 100%; min-width: 0; padding: 9px 10px; border: 1px solid #2a3944; outline: none; border-radius: 6px; background: #0d141b; color: #dbe4e9; font: 10px var(--mono); }
.form-field input:focus, .form-field textarea:focus { border-color: rgba(114,224,180,.52); box-shadow: 0 0 0 2px rgba(114,224,180,.07); }
.form-field input::placeholder { color: #53626e; }
.form-field textarea { resize: vertical; }
.form-field:last-child { grid-column: 1 / -1; }
.form-note { margin-top: 14px; display: flex; align-items: flex-start; gap: 7px; color: #82909a; font-size: 9px; line-height: 1.5; }
.form-note svg { flex: 0 0 auto; color: #8ea0ab; }
.modal-actions { margin-top: 19px; display: flex; justify-content: flex-end; gap: 8px; }
.secondary-button { min-height: 36px; padding: 0 13px; border: 1px solid #2b3944; border-radius: 7px; background: #17212a; color: #a9b5bd; font-size: 11px; }
.secondary-button:hover { background: #1c2933; }
.logs-modal { width: min(850px, 100%); }
.terminal-head { padding: 10px 15px; display: flex; align-items: center; gap: 7px; color: #85939d; font: 10px var(--mono); border-bottom: 1px solid var(--line); }
.terminal-head button { margin-left: auto; padding: 5px 7px; border: 1px solid var(--line); border-radius: 5px; display: flex; align-items: center; gap: 5px; background: #18232c; color: #a7b4bc; font-size: 9px; }
.log-output { min-height: 200px; max-height: 55vh; overflow: auto; margin: 0; padding: 16px; color: #bdd0d4; background: #0b1117; font: 10px/1.65 var(--mono); white-space: pre-wrap; overflow-wrap: anywhere; }
.spin { animation: spin 1s linear infinite; }
@keyframes spin { to { transform: rotate(360deg); } }
@media (max-width: 1000px) {
.metrics-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.app-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 680px) {
.rail { width: 52px; flex-basis: 52px; }
.topbar { height: 56px; padding: 0 14px; }
.server-pill { display: none; }
.content { padding: 29px 15px 22px; }
.hero-row { align-items: flex-start; flex-direction: column; gap: 17px; }
.hero-row>.primary-button { align-self: stretch; }
.metrics-row { grid-template-columns: 1fr 1fr; margin: 25px 0 8px; gap: 8px; }
.resource-card { min-height: 104px; padding: 10px; }
.resource-topline { gap: 6px; }
.resource-topline .metric-icon { width: 28px; height: 28px; flex-basis: 28px; }
.resource-topline strong { font-size: 17px; }
.monitor-caption { margin-bottom: 28px; }
.section-heading { align-items: flex-start; flex-direction: column; gap: 12px; }
.section-tools, .search-box { width: 100%; }
.filter-button { flex: 0 0 auto; }
.app-grid { grid-template-columns: 1fr; }
.add-card { min-height: 180px; }
.form-grid { grid-template-columns: 1fr; }
.form-field:last-child { grid-column: auto; }
.app-modal form { padding: 15px; }
.modal-head { padding: 16px; }
.footer { margin-top: 30px; }
}
/* Dashboard refresh: spacious utility-first cards and a calm, light control plane. */
:root {
color: #172033;
background: #f4f6fa;
--line: #e6eaf0;
--muted: #7b8494;
--green: #13a879;
--surface: #fff;
--surface-raised: #f8fafc;
}
body { color: #172033; background: #f4f6fa; }
.shell { background: #f4f6fa; }
.rail { width: 232px; flex-basis: 232px; align-items: stretch; padding: 23px 15px 18px; gap: 8px; border-right: 1px solid #e8ebf0; background: #fff; }
.rail-brand { display: flex; align-items: center; gap: 11px; padding: 0 8px 5px; }
.brand-mark { width: 39px; height: 39px; flex-basis: 39px; border-radius: 12px; color: #fff; border: 0; background: linear-gradient(145deg, #16b981, #0c8e6c); box-shadow: 0 7px 17px rgba(16, 160, 116, .2); }
.brand-copy { display: grid; gap: 3px; }
.brand-copy strong { color: #172033; font-size: 15px; letter-spacing: -.04em; }
.brand-copy strong span { margin-left: 3px; color: #119b70; }
.brand-copy small { color: #9aa2af; font: 8px var(--mono); letter-spacing: .12em; }
.rail-divider { width: 100%; height: 1px; margin: 13px 0 10px; background: #edf0f4; }
.rail-caption { padding: 0 11px 4px; color: #9aa2af; font-size: 10px; font-weight: 600; letter-spacing: .04em; }
.rail-button { width: 100%; height: 42px; padding: 0 11px; display: flex; justify-content: flex-start; gap: 11px; border-radius: 9px; color: #788293; font-size: 11px; text-align: left; }
.rail-button:hover { color: #168d69; background: #f3faf7; }
.rail-button.active { color: #10815f; background: #eaf8f2; font-weight: 600; }
.rail-button span { flex: 1; }
.rail-button b { color: #8e99a7; font: 10px var(--mono); }
.rail-spacer { min-height: 30px; }
.rail-node { margin-top: 10px; padding: 12px 10px; display: flex; align-items: center; gap: 9px; border: 1px solid #e9edf1; border-radius: 10px; background: #fafbfc; }
.rail-node div { min-width: 0; display: grid; gap: 3px; }
.rail-node b { color: #374151; font-size: 10px; font-weight: 600; }
.rail-node small { color: #8993a1; font-size: 9px; }
.workspace { background: #f4f6fa; }
.topbar { height: 66px; padding: 0 clamp(22px, 3.7vw, 54px); border-bottom-color: #e8ebf0; background: rgba(255,255,255,.82); }
.breadcrumbs { color: #8a94a3; }
.breadcrumbs strong { color: #394253; }
.server-pill, .icon-button { border-color: #e6eaf0; background: #fff; color: #687486; }
.content { width: min(1440px, 100%); padding: 37px clamp(22px, 3.7vw, 54px) 34px; }
.hero-row { align-items: center; }
.eyebrow, .modal-kicker { color: #929baa; font-size: 9px; }
.eyebrow-line { width: 18px; height: 2px; border-radius: 2px; background: #17a879; }
h1 { color: #182234; margin: 12px 0 7px; font-size: clamp(29px, 3vw, 37px); letter-spacing: -.055em; }
.title-dot { color: #15a879; }
.subtitle { color: #778293; font-size: 12px; }
.hero-actions { display: flex; align-items: center; gap: 11px; }
.connection-badge { min-height: 34px; padding: 0 11px; display: inline-flex; align-items: center; gap: 8px; border: 1px solid #e6eaf0; border-radius: 8px; color: #737e8e; background: #fff; font-size: 10px; }
.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); }
.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; }
.resource-card, .trend-panel, .host-panel { border: 1px solid #e8ebf0; border-radius: 13px; background: #fff; box-shadow: 0 3px 12px rgba(21, 34, 54, .025); }
.resource-card { min-height: 120px; padding: 16px 17px 14px; }
.metric-icon { width: 35px; height: 35px; flex-basis: 35px; border-radius: 10px; }
.metric-icon.green { color: #0e9d70; background: #e9f8f1; }
.metric-icon.violet { color: #7959cf; background: #f1ecff; }
.metric-icon.blue { color: #397bcc; background: #eaf3ff; }
.metric-icon.amber { color: #c3822b; background: #fff4e3; }
.resource-label { color: #697587; font-size: 10px; font-weight: 500; }
.resource-topline strong { color: #1d293a; font-size: 23px; }
.resource-track { margin: 14px 0 10px; background: #eef1f5; }
.resource-track span { background: #1ab180; }
.resource-track.violet span { background: #9273eb; }
.resource-track.blue span { background: #5797ed; }
.resource-track.amber span { background: #e4a64d; }
.resource-detail { color: #8993a1; font-size: 9px; }
.monitor-caption { margin: 0 1px 17px; color: #929baa; font-size: 9px; }
.monitor-caption .online-dot { background: #18aa79; box-shadow: none; }
.caption-separator { color: #c3c9d2; }
.monitor-warning { margin: 0 0 16px; padding: 10px 12px; display: flex; align-items: center; gap: 8px; border: 1px solid #f5e5c7; border-radius: 9px; color: #996820; background: #fffaf0; font-size: 10px; }
.monitor-grid { display: grid; grid-template-columns: minmax(0, 1.55fr) minmax(300px, 1fr); gap: 14px; margin-bottom: 34px; }
.trend-panel, .host-panel { min-width: 0; padding: 18px 19px 15px; }
.panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
.panel-kicker { display: block; margin-bottom: 5px; color: #a0a8b3; font: 8px var(--mono); letter-spacing: .11em; }
.panel-heading h2 { color: #253145; font-size: 14px; letter-spacing: -.02em; }
.trend-window { color: #99a2ae; font-size: 9px; }
.chart-legend { display: flex; gap: 14px; margin: 19px 0 2px 28px; }
.chart-legend span { display: inline-flex; align-items: center; gap: 5px; color: #7e8998; font-size: 9px; }
.chart-legend i { width: 7px; height: 7px; border-radius: 50%; }
.legend-cpu { background: #13a879; }
.legend-memory { background: #9273eb; }
.legend-gpu { background: #5797ed; }
.chart-wrap { position: relative; height: 116px; padding-left: 31px; }
.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; }
.cpu-line { stroke: #13a879; }
.memory-line { stroke: #9273eb; }
.gpu-line { stroke: #5797ed; }
.chart-placeholder { position: absolute; inset: 0 0 0 31px; display: grid; place-items: center; color: #a1a9b4; font-size: 10px; }
.chart-foot { display: flex; justify-content: space-between; padding: 4px 0 0 31px; color: #a1a9b4; font-size: 8px; }
.host-state { display: inline-flex; align-items: center; gap: 6px; color: #8d96a4; font-size: 9px; }
.host-state span { width: 6px; height: 6px; border-radius: 50%; background: #e1a34e; }
.host-state.online { color: #16855f; }
.host-state.online span { background: #17aa78; }
.host-identity { margin: 18px 0 14px; padding: 12px; display: flex; align-items: center; gap: 10px; border-radius: 10px; background: #f7f9fb; }
.host-symbol { width: 38px; height: 38px; display: grid; place-items: center; border-radius: 10px; color: #168c67; background: #e6f6ee; }
.host-identity>div:last-child { min-width: 0; display: grid; gap: 4px; }
.host-identity strong { overflow: hidden; color: #303c4e; font-size: 11px; text-overflow: ellipsis; white-space: nowrap; }
.host-identity span { overflow: hidden; color: #8b95a2; font-size: 9px; text-overflow: ellipsis; white-space: nowrap; }
.host-empty { min-height: 156px; display: grid; place-items: center; color: #9aa3af; font-size: 10px; }
.host-details { display: grid; grid-template-columns: 1fr 1fr; gap: 12px 18px; }
.host-details>div { min-width: 0; display: grid; gap: 5px; }
.host-details span { color: #9aa3af; font-size: 9px; }
.host-details b { overflow: hidden; color: #536073; font-size: 9px; font-weight: 500; text-overflow: ellipsis; white-space: nowrap; }
.section-heading { align-items: flex-end; margin: 0 0 15px; }
.section-heading>div:first-child { align-items: flex-end; gap: 10px; }
.section-heading h2 { color: #202c3f; font-size: 17px; }
.section-count { border-color: #e6eaf0; color: #7b8695; background: #fff; }
.service-summary { color: #7f8a99; }
.service-dot { width: 6px; height: 6px; margin-right: 4px; display: inline-block; border-radius: 50%; background: #18aa79; }
.section-tools { gap: 9px; }
.search-box, .filter-button { border-color: #e6eaf0; border-radius: 8px; background: #fff; color: #7e8998; }
.search-box input { color: #3c485a; }
.search-box input::placeholder { color: #a5adb8; }
.filter-button:hover { color: #12845f; background: #f3faf7; }
.service-card { border-color: #e7ebf0; border-radius: 12px; background: #fff; box-shadow: 0 3px 12px rgba(21, 34, 54, .025); }
.service-card:hover { border-color: #c9e7db; box-shadow: 0 10px 24px rgba(21, 34, 54, .07); }
.service-card.is-running { border-color: #ccebdd; box-shadow: inset 0 2px 0 #d8f3e7, 0 3px 12px rgba(21, 34, 54, .025); }
.service-icon { border-color: #e7ebf0; color: #68778a; background: #f3f6f9; }
.service-icon.running { border-color: #d8f1e5; color: #14956d; background: #ebf8f1; }
.card-title-row h3 { color: #263347; }
.card-title-row p { color: #8993a1; }
.service-path { border-color: #edf0f4; background: #f8fafc; color: #74899a; }
.service-path span { color: #68798a; }
.runtime-row span, .card-meta { color: #919baa; }
.runtime-row b { color: #667487; }
.card-menu { border-color: #e5e9ef; background: #fff; box-shadow: 0 10px 28px rgba(32,45,62,.12); }
.card-menu button { color: #596679; }
.card-menu button:hover { background: #f4f7fa; }
.more-button { color: #8a95a2; }
.more-button:hover { color: #475569; background: #f2f5f8; }
.restart-button { border-color: #e7ebf0; background: #f8fafc; color: #778394; }
.add-card { border-color: #cfd9e1; border-radius: 12px; background: #fafcfd; color: #718093; }
.add-card:hover { border-color: #9dd7c0; background: #f2fbf7; }
.add-card-icon { border-color: #d6eee3; color: #14966d; background: #eaf8f1; }
.empty-state { border-color: #d8dfe7; border-radius: 13px; background: #fff; }
.empty-state h3 { color: #29364a; }
.empty-state p { color: #8792a1; }
.empty-icon { border-color: #d6eee3; color: #14966d; background: #eaf8f1; }
.loading-state { color: #778394; }
.footer { border-top-color: #e7ebf0; color: #9ba4b0; }
.footer button { color: #8792a1; }
.alert { border-radius: 9px; }
.modal { border-color: #e4e8ee; border-radius: 14px; background: #fff; box-shadow: 0 24px 70px rgba(24, 36, 52, .2); }
.modal-head { border-bottom-color: #edf0f4; }
.modal-head h2 { color: #253145; }
.modal-head h2 small { color: #8993a1; }
.form-field>span { color: #4f5d70; }
.form-field input, .form-field textarea { border-color: #dfe5ec; background: #fbfcfd; color: #344155; }
.form-field input:focus, .form-field textarea:focus { border-color: #77c8a7; }
.form-field input::placeholder { color: #aab2bd; }
.form-field small, .form-note { color: #7d8998; }
.secondary-button { border-color: #e0e5eb; background: #fff; color: #657184; }
.secondary-button:hover { background: #f6f8fa; }
.terminal-head { color: #8290a0; border-bottom-color: #e7ebf0; }
.terminal-head button { border-color: #e5e9ee; background: #f8fafc; color: #657184; }
.log-output { color: #d2e4de; background: #17231f; }
/* Match Sub2API's compact admin typography and neutral, teal-accented surfaces. */
:root { font-family: system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "PingFang SC", "Microsoft YaHei", sans-serif; color: #0f172a; }
body, .shell, .workspace { background: #f8fafc; }
body { color: #0f172a; font-size: 14px; line-height: 1.5; }
.rail { width: 256px; flex-basis: 256px; gap: 5px; padding: 20px 14px 16px; background: #fff; border-right-color: #e5e7eb; }
.rail-brand { padding: 0 9px 8px; gap: 12px; }
.brand-mark { width: 38px; height: 38px; flex-basis: 38px; border-radius: 11px; background: #0d9488; box-shadow: 0 4px 10px rgba(13,148,136,.14); }
.brand-copy strong { font-size: 16px; letter-spacing: -.025em; }
.brand-copy small { font-family: inherit; font-size: 9px; letter-spacing: .1em; }
.rail-divider { margin: 10px 0; background: #f1f5f9; }
.rail-caption { color: #94a3b8; font-size: 11px; }
.rail-button { height: 42px; gap: 12px; border-radius: 10px; color: #475569; font-size: 13px; font-weight: 500; }
.rail-button:hover { color: #0f766e; background: #f1f5f9; }
.rail-button.active { color: #0f766e; background: #f0fdfa; font-weight: 600; }
.rail-button b { font: 11px system-ui, sans-serif; color: #64748b; }
.rail-node { border-color: #e5e7eb; background: #f8fafc; }
.workspace { background: #f8fafc; }
.topbar { border-bottom-color: #e5e7eb; background: rgba(255,255,255,.94); }
.breadcrumbs { font-size: 13px; }
.breadcrumbs strong { color: #0f172a; }
.content { width: min(1360px, 100%); padding: 32px clamp(22px, 3.7vw, 48px) 32px; }
h1 { margin: 9px 0 5px; color: #0f172a; font: 700 clamp(25px, 2.5vw, 30px)/1.25 system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", "Microsoft YaHei", sans-serif; letter-spacing: -.035em; }
h2 { font-family: inherit; font-size: 16px; }
.subtitle { color: #64748b; font-size: 14px; }
.eyebrow, .modal-kicker { font-family: inherit; font-size: 10px; font-weight: 600; letter-spacing: .08em; }
.eyebrow-line { background: #0d9488; }
.title-dot { color: #0d9488; }
.primary-button { border-color: #0d9488; background: #0d9488; box-shadow: 0 2px 5px rgba(13,148,136,.16); font-size: 13px; font-weight: 600; }
.primary-button:hover { background: #0f766e; }
.page-hero { margin: 4px 0 27px; align-items: center; }
.metrics-row { margin-top: 0; }
.resource-card, .trend-panel, .host-panel, .runtime-panel { border-color: #e5e7eb; border-radius: 12px; box-shadow: 0 1px 2px rgba(15,23,42,.025); }
.resource-card { padding: 16px; }
.resource-topline strong { font-family: inherit; font-size: 22px; }
.resource-label { font-size: 12px; }
.resource-detail { font-family: inherit; font-size: 11px; }
.metric-icon.green { color: #0f766e; background: #ccfbf1; }
.resource-track span { background: #0d9488; }
.resource-track.violet span { background: #8b5cf6; }
.resource-track.blue span { background: #3b82f6; }
.resource-track.amber span { background: #f59e0b; }
.connection-badge { border-radius: 9px; font-size: 12px; }
.section-heading { margin-bottom: 16px; }
.section-heading h2 { font-size: 18px; }
.panel-kicker { font-family: inherit; font-size: 9px; font-weight: 600; letter-spacing: .08em; }
.monitor-caption { font-size: 11px; }
.chart-placeholder, .host-empty { font-size: 12px; }
.service-summary, .filter-button, .search-box input { font-size: 12px; }
.service-card { border-radius: 12px; }
.card-title-row h3 { font-size: 14px; }
.card-title-row p { font-size: 12px; }
.runtime-kpis { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 14px; margin: 4px 0 18px; }
.runtime-kpis>div { min-height: 104px; padding: 16px; display: grid; grid-template-columns: 36px 1fr; grid-template-rows: auto 1fr; align-items: center; column-gap: 12px; border: 1px solid #e5e7eb; border-radius: 12px; background: #fff; }
.runtime-kpi-icon { width: 36px; height: 36px; grid-row: 1 / 3; display: grid; place-items: center; border-radius: 10px; }
.runtime-kpi-icon.green { color: #0f766e; background: #ccfbf1; }
.runtime-kpi-icon.amber { color: #b45309; background: #fef3c7; }
.runtime-kpi-icon.blue { color: #2563eb; background: #dbeafe; }
.runtime-kpi-icon.violet { color: #7c3aed; background: #ede9fe; }
.runtime-kpis small { color: #64748b; font-size: 12px; }
.runtime-kpis strong { align-self: start; color: #0f172a; font-size: 23px; line-height: 1.1; }
.runtime-kpis strong span { margin-left: 3px; color: #64748b; font-size: 12px; font-weight: 500; }
.runtime-panel { overflow: hidden; background: #fff; }
.runtime-panel-heading { min-height: 64px; padding: 0 18px; border-bottom: 1px solid #e5e7eb; }
.runtime-refresh-note { color: #94a3b8; font-size: 11px; }
.runtime-table-wrap { overflow-x: auto; }
.runtime-table { width: 100%; border-collapse: collapse; text-align: left; }
.runtime-table th { padding: 11px 16px; color: #64748b; background: #f8fafc; font-size: 11px; font-weight: 600; white-space: nowrap; }
.runtime-table td { max-width: 260px; padding: 13px 16px; border-top: 1px solid #f1f5f9; color: #475569; font-size: 12px; white-space: nowrap; }
.runtime-table td:first-child { display: grid; gap: 2px; }
.runtime-table td strong { color: #0f172a; font-size: 13px; font-weight: 600; }
.runtime-table td small { color: #94a3b8; font-size: 11px; }
.runtime-status { display: inline-flex; align-items: center; gap: 7px; padding: 3px 8px; border-radius: 999px; background: #f1f5f9; color: #475569; font-size: 11px; }
.runtime-status i { width: 6px; height: 6px; border-radius: 50%; background: #94a3b8; }
.runtime-status.running { color: #0f766e; background: #f0fdfa; }
.runtime-status.running i { background: #14b8a6; }
.runtime-status.failed { color: #b91c1c; background: #fef2f2; }
.runtime-status.failed i { background: #ef4444; }
.runtime-path { overflow: hidden; text-overflow: ellipsis; }
.runtime-empty { padding: 44px 20px; color: #94a3b8; font-size: 13px; text-align: center; }
.runtime-refresh { min-height: 36px; padding: 0 12px; }
.search-box, .filter-button { border-color: #e2e8f0; background: #fff; }
.search-box input { font-family: inherit; }
.filter-button:hover { color: #0f766e; background: #f0fdfa; }
.icon-button { border-color: #e2e8f0; background: #fff; }
.icon-button:hover { color: #0f766e; border-color: #99f6e4; }
.empty-state h3 { font-size: 16px; }
.empty-state p { font-size: 13px; }
.footer { font-family: inherit; }
.settings-panel { max-width: 760px; padding: 21px; border: 1px solid #e5e7eb; border-radius: 12px; background: #fff; box-shadow: 0 1px 2px rgba(15,23,42,.025); }
.settings-panel .panel-heading { margin-bottom: 12px; }
.settings-token-status { display: inline-flex; align-items: center; gap: 7px; color: #b45309; font-size: 12px; }
.settings-token-status i { width: 7px; height: 7px; border-radius: 50%; background: #f59e0b; }
.settings-token-status.configured { color: #0f766e; }
.settings-token-status.configured i { background: #14b8a6; }
.settings-description { max-width: 620px; margin: 0 0 20px; color: #64748b; font-size: 13px; line-height: 1.65; }
.settings-description code { padding: 2px 5px; border-radius: 4px; background: #f1f5f9; color: #0f766e; font: 12px ui-monospace, monospace; }
.settings-token-form { max-width: 520px; display: grid; gap: 8px; }
.settings-token-form label { color: #334155; font-size: 12px; font-weight: 600; }
.settings-token-form input { width: 100%; min-height: 40px; padding: 0 11px; border: 1px solid #cbd5e1; border-radius: 8px; outline: none; background: #fff; color: #0f172a; font: 13px system-ui, sans-serif; }
.settings-token-form input:focus { border-color: #14b8a6; box-shadow: 0 0 0 3px rgba(20,184,166,.12); }
.settings-token-form input::placeholder { color: #94a3b8; }
.settings-token-actions { margin-top: 7px; display: flex; gap: 9px; }
.settings-token-actions .secondary-button { min-height: 38px; border-color: #e2e8f0; background: #fff; font-size: 12px; }
.settings-token-actions .secondary-button:hover { color: #b91c1c; border-color: #fecaca; background: #fff7f7; }
.settings-token-actions .primary-button:disabled { cursor: not-allowed; opacity: .5; }
@media (max-width: 1000px) {
.rail { width: 205px; flex-basis: 205px; }
.monitor-grid { grid-template-columns: 1fr; }
.runtime-kpis { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (max-width: 680px) {
.rail { width: 54px; flex-basis: 54px; align-items: center; padding: 14px 7px; }
.rail-brand { padding: 0; }
.brand-copy, .rail-caption, .rail-divider, .rail-button span, .rail-button b, .rail-node { display: none; }
.rail-button { width: 38px; padding: 0; justify-content: center; }
.topbar { background: #fff; }
.content { padding: 27px 14px 22px; }
.hero-actions { width: 100%; justify-content: space-between; }
.hero-actions .primary-button { min-width: 120px; }
.monitor-grid { gap: 10px; margin-bottom: 27px; }
.trend-panel, .host-panel { padding: 14px; }
.section-heading { align-items: flex-start; }
.section-heading>div:first-child { flex-wrap: wrap; }
.section-heading .section-tools { width: 100%; }
.runtime-kpis { gap: 8px; }
.runtime-kpis>div { min-height: 92px; padding: 11px; grid-template-columns: 30px 1fr; column-gap: 8px; }
.runtime-kpi-icon { width: 30px; height: 30px; }
.runtime-table th, .runtime-table td { padding: 10px 12px; }
}

1
frontend/src/vite-env.d.ts vendored 100644
View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"allowJs": false,
"skipLibCheck": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "ESNext",
"moduleResolution": "Bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx"
},
"include": ["src"]
}

View File

@ -0,0 +1,13 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
export default defineConfig({
plugins: [react()],
server: {
host: "0.0.0.0",
proxy: {
"/api": "http://127.0.0.1:8000",
},
},
});