"""在主服务提供看板页面、运行历史和实时事件入口。
- 页面:serve 同一份 static/index.html,注入相对 base 和 'same-origin' 连接模式;
- 历史:直调 DashboardServer 的 public 方法,与 9300 同一数据源;
- 实时:透明字节管道桥到本进程 9301 权威实现——重放/快照/慢客户端语义
全部留在 DashboardServer._handle_ws,此处不做任何协议逻辑。
鉴权镜像 9300 侧规则:query token 或 Bearer 头,未配 token 放行。
"""
from __future__ import annotations
import asyncio
import hmac
import html
import json
import logging
from pathlib import Path
from urllib.parse import parse_qs, urlencode, urlparse
from fastapi import APIRouter, Request, WebSocket, WebSocketDisconnect
from fastapi.responses import HTMLResponse, JSONResponse
logger = logging.getLogger(__name__)
router = APIRouter()
_STATIC_DIR = Path(__file__).resolve().parent.parent / "model_agent" / "dashboard" / "static"
_STATIC_INDEX = _STATIC_DIR / "index.html"
def mount_assets(app) -> None:
"""在 /workflow/assets 挂载构建产物;目录不存在时跳过。"""
assets = _STATIC_DIR / "assets"
if assets.is_dir():
from fastapi.staticfiles import StaticFiles
app.mount("/workflow/assets", StaticFiles(directory=assets), name="dashboard-assets")
def _dashboard_token() -> str:
"""token 真源是 DashboardConfig.from_env()(main.py lifespan 已把 settings 回写 env)。"""
from app.model_agent.dashboard.config import DashboardConfig
return DashboardConfig.from_env().token
def _authorized(supplied: str | None, authorization: str = "") -> bool:
expected = _dashboard_token()
if not expected:
return True
bearer = authorization[7:] if authorization.lower().startswith("bearer ") else ""
token = supplied or bearer
return bool(token) and hmac.compare_digest(token, expected)
def _query_token(url: str) -> str | None:
return parse_qs(urlparse(url).query).get("token", [""])[0] or None
def _dashboard_base_href(request: Request) -> str:
forwarded_prefix = request.headers.get("x-forwarded-prefix", "").strip().rstrip("/")
if forwarded_prefix.startswith("/") and not forwarded_prefix.startswith("//"):
return f"{forwarded_prefix}/workflow/"
return "./" if request.url.path.endswith("/") else "./workflow/"
@router.get("/workflow")
@router.get("/workflow/")
async def dashboard_page(request: Request) -> HTMLResponse:
"""页面入口:用户可见 URL 为 /workflow(内部命名不动)。"""
try:
body = _STATIC_INDEX.read_bytes()
except OSError:
return HTMLResponse(content="dashboard static not built", status_code=404)
from app.model_agent.dashboard.config import DashboardConfig
body = body.replace(
b"__DASHBOARD_WS_PORT_VALUE__",
str(DashboardConfig.from_env().ws_port).encode(),
).replace(
b"__DASHBOARD_WS_CONNECT_VALUE__", json.dumps("same-origin").encode(),
)
base = html.escape(_dashboard_base_href(request), quote=True).encode()
body = body.replace(b"<head>", b'<head>\n <base href="' + base + b'">', 1)
return HTMLResponse(content=body, headers={"Cache-Control": "no-store"})
@router.get("/workflow/api/runs")
def dashboard_runs(request: Request, token: str | None = None, authorization: str = "") -> JSONResponse:
if not _authorized(token, request.headers.get("authorization", "") or authorization):
return JSONResponse(content={"detail": "dashboard token required"}, status_code=401)
from app.model_agent.dashboard.server import DashboardServer
return JSONResponse(
content={"runs": DashboardServer.get_instance().list_runs_with_deletable()},
headers={"Cache-Control": "no-store"},
)
@router.get("/workflow/api/runs/{workflow_id}")
def dashboard_run_detail(
workflow_id: str, request: Request, token: str | None = None, authorization: str = "",
) -> JSONResponse:
if not _authorized(token, request.headers.get("authorization", "") or authorization):
return JSONResponse(content={"detail": "dashboard token required"}, status_code=401)
from app.model_agent.dashboard.server import DashboardServer
run = DashboardServer.get_instance().get_run(workflow_id)
if run is None:
return JSONResponse(content={"detail": "run not found"}, status_code=404)
return JSONResponse(content=run, headers={"Cache-Control": "no-store"})
@router.delete("/workflow/api/runs/{workflow_id}")
def dashboard_run_delete(
workflow_id: str, request: Request, token: str | None = None, authorization: str = "",
) -> JSONResponse:
if not _authorized(token, request.headers.get("authorization", "") or authorization):
return JSONResponse(content={"detail": "dashboard token required"}, status_code=401)
from app.model_agent.dashboard.server import DashboardServer
result = DashboardServer.get_instance().delete_run(workflow_id)
if result == "active":
return JSONResponse(content={"detail": "run is active"}, status_code=409)
if result == "not_found":
return JSONResponse(content={"detail": "run not found"}, status_code=404)
return JSONResponse(content={"deleted": workflow_id}, headers={"Cache-Control": "no-store"})
@router.websocket("/workflow/ws")
async def dashboard_ws_proxy(ws: WebSocket) -> None:
if not _authorized(_query_token(str(ws.url))):
await ws.close(code=4401, reason="dashboard token required")
return
from app.model_agent.dashboard.config import DashboardConfig
cfg = DashboardConfig.from_env()
inner_token = _dashboard_token()
url = f"ws://127.0.0.1:{cfg.ws_port}/ws"
if inner_token:
url += f"?{urlencode({'token': inner_token})}"
try:
import websockets
upstream = await websockets.connect(url, max_size=None)
except Exception as exc:
logger.warning("Dashboard ws proxy upstream connect failed: %s", exc)
await ws.close(code=1013, reason="dashboard upstream unavailable")
return
await ws.accept()
async def upstream_to_client() -> None:
try:
async for message in upstream:
await ws.send_text(message if isinstance(message, str) else message.decode())
except Exception:
pass
finally:
try:
await ws.close()
except Exception:
pass
async def client_keepalive() -> None:
try:
while True:
await ws.receive_text()
except WebSocketDisconnect:
pass
except Exception:
pass
finally:
try:
await upstream.close()
except Exception:
pass
await asyncio.gather(upstream_to_client(), client_keepalive())
try:
await upstream.close()
except Exception:
pass