from __future__ import annotations import asyncio import json import os import uuid from contextlib import asynccontextmanager from pathlib import Path from typing import Any from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect from fastapi.responses import FileResponse, HTMLResponse, JSONResponse, Response, StreamingResponse from fastapi.staticfiles import StaticFiles from mcp.server.transport_security import TransportSecuritySettings from pydantic import BaseModel from app.adb_lan.controller import LanAdbController, assert_lan_only_request, is_private_ip from app.admin.chat_agent import ChatSessionRunner, HubMcpChatAgent from app.admin.ui import ADMIN_HTML from app.bridge.discovery import LanDiscoveryResponder from app.bridge.manager import DeviceBridgeManager from app.mcp.server import build_mcp_server, mcp_request_is_lan from app.models import HubChatAIConfig, HubConfig, RepairAIConfig from app.storage.db import PulseWallDB, now_ms class LanDebugPolicyBody(BaseModel): allowed: bool adb_target: str | None = None class DeviceRepairAiBody(BaseModel): use_custom: bool = False repair_ai: RepairAIConfig | None = None class DeviceUiPrefsBody(BaseModel): screen_mirror_enabled: bool | None = None class ChatRequestBody(BaseModel): message: str history: list[dict[str, Any]] = [] class CreateSessionBody(BaseModel): title: str = "新会话" class RenameSessionBody(BaseModel): title: str class SendSessionMessageBody(BaseModel): message: str class PromptGroupBody(BaseModel): name: str sort_order: int = 0 class QuickPromptBody(BaseModel): group_id: str title: str content: str sort_order: int = 0 class RollbackBody(BaseModel): snapshot_id: str = "home" class LanAdbActionBody(BaseModel): action: str params: dict[str, Any] = {} class LanAdbPairBody(BaseModel): pair_address: str pairing_code: str device_id: str | None = None class WebhookBody(BaseModel): url: str secret: str = "" class TestDeviceBody(BaseModel): device_id: str def create_app(db_path: str | None = None, releases_dir: str | Path | None = None) -> FastAPI: resolved_db = db_path or os.environ.get("PULSEWALL_DB_PATH", "pulsewall_hub.db") resolved_releases = Path( releases_dir or os.environ.get("PULSEWALL_RELEASES_DIR", str(Path(__file__).resolve().parent.parent / "releases")) ) resolved_releases.mkdir(parents=True, exist_ok=True) db = PulseWallDB(resolved_db) bridge = DeviceBridgeManager(db) adb_controller = LanAdbController(db) mcp_server = build_mcp_server(db, bridge, adb_controller) chat_agent = HubMcpChatAgent(db, mcp_server) chat_runner = ChatSessionRunner(db, chat_agent) # Disable DNS rebinding host restriction so LAN IPs (192.168.x.x / Tailscale) work seamlessly mcp_http_app = mcp_server.streamable_http_app( streamable_http_path="/", json_response=True, stateless_http=True, transport_security=TransportSecuritySettings(enable_dns_rebinding_protection=False), host="0.0.0.0", ) discovery = LanDiscoveryResponder() shutdown_event = asyncio.Event() adb_controller.bind_shutdown_event(shutdown_event) @asynccontextmanager async def lifespan(_app: FastAPI): await discovery.start() try: async with mcp_server.session_manager.run(): yield finally: shutdown_event.set() adb_controller.stop_all_streams() chat_runner.cancel_all() await bridge.close_all() discovery.stop() app = FastAPI(title="PulseWall Hub", version="0.1.0", lifespan=lifespan) app.state.db = db app.state.bridge = bridge app.state.adb_controller = adb_controller app.state.mcp_server = mcp_server app.state.chat_agent = chat_agent app.state.chat_runner = chat_runner app.state.shutdown_event = shutdown_event @app.middleware("http") async def lan_context_and_auth_middleware(request: Request, call_next): client_host = request.client.host if request.client else None forwarded_ok = True for hdr in ("x-forwarded-for", "x-real-ip", "cf-connecting-ip"): val = request.headers.get(hdr) if val and any(not is_private_ip(p.strip()) for p in val.split(",") if p.strip()): forwarded_ok = False token = mcp_request_is_lan.set(is_private_ip(client_host) and forwarded_ok) try: cfg = db.get_config() if cfg.auth_token and request.url.path.startswith(("/mcp", "/api/events", "/api/webhooks")): auth = request.headers.get("authorization", "") if auth != f"Bearer {cfg.auth_token}": return JSONResponse({"detail": "Unauthorized"}, status_code=401) return await call_next(request) finally: mcp_request_is_lan.reset(token) app.mount("/mcp", mcp_http_app) @app.get("/health") def health() -> dict[str, Any]: return { "status": "ok", "online_devices": bridge.connected_device_ids(), "mcp_endpoint": "/mcp", "admin_ui": "/admin", } # ---- App Self-Update (OTA) API ---- def _read_ota_meta() -> dict[str, Any] | None: meta_file = resolved_releases / "latest.json" if not meta_file.exists(): return None try: meta = json.loads(meta_file.read_text(encoding="utf-8")) apk_file = resolved_releases / str(meta.get("filename", "pulsewall-latest.apk")) if not apk_file.exists(): return None meta["download_path"] = f"/api/ota/download/{apk_file.name}" return meta except Exception: return None @app.get("/api/ota/latest") def ota_latest(request: Request) -> dict[str, Any]: meta = _read_ota_meta() if not meta: return {"available": False, "message": "No APK release published yet."} base = str(request.base_url).rstrip("/") return { "available": True, **meta, "download_url": f"{base}{meta['download_path']}", } @app.get("/api/ota/download/{filename}") def ota_download(filename: str) -> FileResponse: safe_name = Path(filename).name if not safe_name.endswith(".apk"): raise HTTPException(status_code=400, detail="Only .apk files can be downloaded.") apk_path = resolved_releases / safe_name if not apk_path.exists(): raise HTTPException(status_code=404, detail="APK release not found.") return FileResponse( path=str(apk_path), media_type="application/vnd.android.package-archive", filename=safe_name, ) @app.post("/api/admin/ota/push") async def admin_ota_push(request: Request, device_id: str | None = None) -> dict[str, Any]: """Smart OTA routing: ADB-connected devices -> direct `adb install -r`; others -> App self-update push.""" meta = _read_ota_meta() if not meta: raise HTTPException(status_code=404, detail="No APK release published in hub/releases yet.") base = str(request.base_url).rstrip("/") payload = {**meta, "download_url": f"{base}{meta['download_path']}"} apk_path = resolved_releases / str(meta.get("filename", "pulsewall-latest.apk")) if device_id: dev = db.get_device(device_id) if not dev: raise HTTPException(status_code=404, detail="Device not found") candidates = [dev] else: online_ids = set(bridge.connected_device_ids()) candidates = [d for d in db.list_devices() if d["device_id"] in online_ids] enriched = await adb_controller.enrich_devices_with_adb(candidates) results: list[dict[str, Any]] = [] adb_started = 0 app_pushed = 0 for dev in enriched: did = dev["device_id"] if dev.get("adb_connected") and dev.get("adb_serial"): started = adb_controller.start_adb_ota_install(did, dev["adb_serial"], apk_path, meta) results.append({"device_id": did, "method": "adb", "status": "installing" if started else "already_installing"}) adb_started += 1 elif await bridge.send_frame(did, "ota.available", payload): results.append({"device_id": did, "method": "app", "status": "pushed"}) app_pushed += 1 else: results.append({"device_id": did, "method": "none", "status": "offline"}) db.add_audit( "ota", device_id or "all", f"OTA v{meta['version_name']} ({meta['version_code']}): ADB 直装 {adb_started} 台 · App 自更新推送 {app_pushed} 台", {"results": results}, ) return { "ok": True, "pushed_devices": adb_started + app_pushed, "adb_installs": adb_started, "app_pushes": app_pushed, "results": results, "release": payload, } @app.get("/api/admin/ota/adb-status/{device_id}") def admin_ota_adb_status(device_id: str) -> dict[str, Any]: return adb_controller.get_adb_ota_status(device_id) @app.websocket("/ws/device/{device_id}") async def ws_device(websocket: WebSocket, device_id: str) -> None: cfg = db.get_config() if cfg.auth_token: q_tok = websocket.query_params.get("token", "") hdr_tok = websocket.headers.get("authorization", "") if q_tok != cfg.auth_token and hdr_tok != f"Bearer {cfg.auth_token}": await websocket.close(code=4401, reason="Unauthorized") return await websocket.accept() await bridge.register(device_id, websocket) try: while True: raw = await websocket.receive_text() await bridge.handle_incoming(device_id, raw) except WebSocketDisconnect: pass finally: bridge.unregister(device_id, websocket) @app.get("/api/events/stream") async def events_stream(request: Request) -> StreamingResponse: q = bridge.subscribe_sse() async def gen(): try: yield 'event: connected\ndata: {"status":"ok"}\n\n' while not shutdown_event.is_set(): if await request.is_disconnected(): break try: evt = await asyncio.wait_for(q.get(), timeout=1.5) yield f"event: {evt['event_type']}\ndata: {json.dumps(evt, ensure_ascii=False)}\n\n" except asyncio.TimeoutError: yield ": keepalive\n\n" finally: bridge.unsubscribe_sse(q) return StreamingResponse(gen(), media_type="text/event-stream") @app.post("/api/webhooks") def register_webhook(body: WebhookBody) -> dict[str, Any]: return db.add_webhook(body.url, body.secret) @app.get("/api/webhooks") def list_webhooks() -> dict[str, Any]: return {"webhooks": db.list_webhooks()} @app.delete("/api/webhooks/{webhook_id}") def remove_webhook(webhook_id: str) -> dict[str, Any]: return {"deleted": db.delete_webhook(webhook_id)} @app.post("/api/lan-debug/pair") async def lan_debug_pair(body: LanAdbPairBody, request: Request) -> dict[str, Any]: assert_lan_only_request(request) return await adb_controller.pair_wireless(body.pair_address, body.pairing_code, body.device_id) @app.get("/api/lan-debug/{device_id}/screen.png") async def lan_debug_screen_png(device_id: str, request: Request) -> Response: assert_lan_only_request(request) png = await adb_controller.capture_screen_png(device_id) return Response( content=png, media_type="image/png", headers={"Cache-Control": "no-store, max-age=0"}, ) @app.websocket("/ws/lan-debug/{device_id}/video") async def ws_lan_debug_video( websocket: WebSocket, device_id: str, quality: str = "hd", format: str = "fmp4", ) -> None: client_host = websocket.client.host if websocket.client else None forwarded_ok = True for hdr in ("x-forwarded-for", "x-real-ip", "cf-connecting-ip"): val = websocket.headers.get(hdr) if val and any(not is_private_ip(p.strip()) for p in val.split(",") if p.strip()): forwarded_ok = False if not is_private_ip(client_host) or not forwarded_ok: await websocket.close(code=4403, reason="LAN only") return await websocket.accept() try: await adb_controller.stream_fmp4_ws(device_id, websocket, quality=quality, stream_format=format) except WebSocketDisconnect: pass except Exception as exc: try: await websocket.send_json({"type": "error", "message": str(getattr(exc, "detail", exc))}) except Exception: pass try: await websocket.close(code=1011) except Exception: pass @app.get("/api/lan-debug/{device_id}/stream.mjpeg") async def lan_debug_stream_mjpeg( device_id: str, request: Request, quality: str = "hd", fps: int = 20, ) -> StreamingResponse: assert_lan_only_request(request) # Validate device & ADB availability before starting stream headers await adb_controller._resolve_target_serial(device_id, require_control_auth=False) return StreamingResponse( adb_controller.stream_mjpeg(device_id, request, quality=quality, fps=fps), media_type="multipart/x-mixed-replace; boundary=frame", headers={"Cache-Control": "no-store, no-cache, must-revalidate", "X-Accel-Buffering": "no"}, ) @app.post("/api/lan-debug/{device_id}/action") async def lan_debug_action(device_id: str, body: LanAdbActionBody, request: Request) -> dict[str, Any]: assert_lan_only_request(request) return await adb_controller.execute_action(device_id, body.action, body.params) admin_dist = Path(__file__).resolve().parent / "admin" / "dist" admin_assets = admin_dist / "assets" if admin_assets.exists(): app.mount("/admin/assets", StaticFiles(directory=str(admin_assets)), name="admin-assets") @app.get("/admin", response_class=HTMLResponse) @app.get("/admin/", response_class=HTMLResponse) def admin_page(): index_file = admin_dist / "index.html" if index_file.exists(): return FileResponse(str(index_file), media_type="text/html; charset=utf-8") return HTMLResponse(ADMIN_HTML) @app.get("/api/admin/devices") async def admin_devices() -> dict[str, Any]: devices = await adb_controller.enrich_devices_with_adb(db.list_devices()) return {"devices": devices} @app.get("/api/admin/devices/{device_id}/metrics") def admin_device_metrics(device_id: str, range: str = "1h") -> dict[str, Any]: return db.query_telemetry_history(device_id=device_id, range_key=range) @app.put("/api/admin/devices/{device_id}/lan-debug") def admin_set_lan_debug(device_id: str, body: LanDebugPolicyBody, request: Request) -> dict[str, Any]: assert_lan_only_request(request) dev = db.set_device_lan_debug(device_id, body.allowed, body.adb_target) if not dev: raise HTTPException(status_code=404, detail="Device not found") return {"device": dev} @app.put("/api/admin/devices/{device_id}/ui-prefs") def admin_set_device_ui_prefs(device_id: str, body: DeviceUiPrefsBody) -> dict[str, Any]: patch = {k: v for k, v in body.model_dump().items() if v is not None} dev = db.set_device_ui_prefs(device_id, patch) if not dev: raise HTTPException(status_code=404, detail="Device not found") return {"ok": True, "device": dev} @app.put("/api/admin/devices/{device_id}/repair-ai") async def admin_set_device_repair_ai(device_id: str, body: DeviceRepairAiBody) -> dict[str, Any]: override = body.repair_ai if body.use_custom and body.repair_ai is not None else None dev = db.set_device_repair_ai(device_id, override) if not dev: raise HTTPException(status_code=404, detail="Device not found") pushed = await bridge.push_config(device_id) return {"ok": True, "device": dev, "pushed_online": pushed > 0} @app.post("/api/admin/devices/{device_id}/rollback") async def admin_device_rollback(device_id: str, body: RollbackBody) -> dict[str, Any]: if body.snapshot_id == "home": ok = await bridge.send_frame(device_id, "render.home", {}) return {"ok": ok, "snapshot_id": "home"} snap = db.get_snapshot(body.snapshot_id) if not snap: raise HTTPException(status_code=404, detail="Snapshot not found") ok = await bridge.send_frame( device_id, "render.rollback", {"snapshot_id": snap["snapshot_id"], "html": snap["html"], "title": snap.get("title", "")}, ) return {"ok": ok, "snapshot_id": snap["snapshot_id"]} @app.put("/api/admin/chat-ai-config") def admin_save_chat_ai_config(chat_cfg: HubChatAIConfig) -> dict[str, Any]: cfg = db.get_config() cfg.hub_chat_ai = chat_cfg db.save_config(cfg) return {"ok": True, "hub_chat_ai": chat_cfg.model_dump()} @app.post("/api/admin/chat") async def admin_chat(body: ChatRequestBody) -> dict[str, Any]: return await chat_agent.chat(user_message=body.message, history=body.history) # ---- Persistent Multi-Session Background Chat API ---- @app.get("/api/admin/chat/sessions") def admin_list_chat_sessions() -> dict[str, Any]: sessions = db.list_chat_sessions() if not sessions: first = db.create_chat_session("默认会话") sessions = [first] return {"sessions": sessions} @app.post("/api/admin/chat/sessions") def admin_create_chat_session(body: CreateSessionBody) -> dict[str, Any]: return {"session": db.create_chat_session(body.title)} @app.put("/api/admin/chat/sessions/{session_id}") def admin_rename_chat_session(session_id: str, body: RenameSessionBody) -> dict[str, Any]: s = db.rename_chat_session(session_id, body.title) if not s: raise HTTPException(status_code=404, detail="Session not found") return {"session": s} @app.delete("/api/admin/chat/sessions/{session_id}") def admin_delete_chat_session(session_id: str) -> dict[str, Any]: chat_runner.cancel_session_run(session_id) return {"deleted": db.delete_chat_session(session_id)} @app.get("/api/admin/chat/sessions/{session_id}/messages") def admin_get_session_messages(session_id: str) -> dict[str, Any]: sess = db.get_chat_session(session_id) if not sess: raise HTTPException(status_code=404, detail="Session not found") return {"session": sess, "messages": db.list_chat_messages(session_id)} @app.post("/api/admin/chat/sessions/{session_id}/messages") async def admin_send_session_message(session_id: str, body: SendSessionMessageBody) -> dict[str, Any]: text = body.message.strip() if not text: raise HTTPException(status_code=400, detail="消息不能为空") return chat_runner.start_message_run(session_id, text) # ---- Quick Prompt Groups & Items CRUD API ---- @app.get("/api/admin/prompts") def admin_list_prompts() -> dict[str, Any]: return {"groups": db.list_prompt_groups_with_items()} @app.post("/api/admin/prompt-groups") def admin_create_prompt_group(body: PromptGroupBody) -> dict[str, Any]: return {"group": db.create_prompt_group(body.name, body.sort_order)} @app.put("/api/admin/prompt-groups/{group_id}") def admin_update_prompt_group(group_id: str, body: PromptGroupBody) -> dict[str, Any]: g = db.update_prompt_group(group_id, body.name, body.sort_order) if not g: raise HTTPException(status_code=404, detail="Prompt group not found") return {"group": g} @app.delete("/api/admin/prompt-groups/{group_id}") def admin_delete_prompt_group(group_id: str) -> dict[str, Any]: return {"deleted": db.delete_prompt_group(group_id)} @app.post("/api/admin/prompts") def admin_create_quick_prompt(body: QuickPromptBody) -> dict[str, Any]: return {"prompt": db.create_quick_prompt(body.group_id, body.title, body.content, body.sort_order)} @app.put("/api/admin/prompts/{prompt_id}") def admin_update_quick_prompt(prompt_id: str, body: QuickPromptBody) -> dict[str, Any]: p = db.update_quick_prompt( prompt_id, group_id=body.group_id, title=body.title, content=body.content, sort_order=body.sort_order, ) if not p: raise HTTPException(status_code=404, detail="Quick prompt not found") return {"prompt": p} @app.delete("/api/admin/prompts/{prompt_id}") def admin_delete_quick_prompt(prompt_id: str) -> dict[str, Any]: return {"deleted": db.delete_quick_prompt(prompt_id)} @app.get("/api/admin/config") def admin_get_config() -> dict[str, Any]: return db.get_config().model_dump() @app.put("/api/admin/config") async def admin_save_config(cfg: HubConfig) -> dict[str, Any]: db.save_config(cfg) pushed = await bridge.push_config() return {"ok": True, "pushed_devices": pushed} @app.get("/api/admin/events") def admin_events() -> dict[str, Any]: return {"events": db.list_pending_events(limit=40)} @app.get("/api/admin/audits") def admin_audits() -> dict[str, Any]: return {"audits": db.list_audits(limit=60)} @app.get("/api/admin/snapshots/{device_id}") def admin_snapshots(device_id: str) -> dict[str, Any]: return {"snapshots": db.list_snapshots(device_id=device_id, limit=20)} @app.post("/api/admin/test/feed") async def admin_test_feed(body: TestDeviceBody) -> dict[str, Any]: item_id = f"feed_{uuid.uuid4().hex[:8]}" ok = await bridge.send_frame( body.device_id, "feed.push", { "item_id": item_id, "title": "中心桥测试消息", "body": "这是一条普通动态消息,应只响一声叮叮提示音,无需确认操作。", "level": "info", "source": "hub-admin", "sound": "ding", "tags": ["test"], "ts": now_ms(), }, ) return {"ok": ok, "item_id": item_id} @app.post("/api/admin/test/alarm") async def admin_test_alarm(body: TestDeviceBody) -> dict[str, Any]: alert_id = f"alert_{uuid.uuid4().hex[:8]}" ok = await bridge.send_frame( body.device_id, "alert.trigger", { "alert_id": alert_id, "title": "紧急服务器异常(演练)", "message": "prod-gateway 连续 3 次健康检查失败,错误码 502。", "level": "critical", "presentation": "fullscreen_alarm", "sound": "siren", "vibrate": True, "wake_screen": True, "tts_text": "紧急警报,生产网关异常,请立即确认处理", "details_code": "HTTP 502 Bad Gateway\nupstream: 10.0.2.15:8080 connection refused", "interaction": { "interaction_id": f"int_{uuid.uuid4().hex[:8]}", "mode": "action_required", "presets": [ {"id": "ack", "label": "确认收到", "style": "primary"}, {"id": "restart", "label": "让 AI 重启网关", "style": "danger"}, {"id": "snooze_30m", "label": "暂缓 30 分钟", "style": "secondary"}, ], "allow_custom_input": True, "custom_input_placeholder": "输入其他处理指示...", }, }, ) return {"ok": ok, "alert_id": alert_id} @app.post("/api/admin/test/home") async def admin_test_home(body: TestDeviceBody) -> dict[str, Any]: ok = await bridge.send_frame(body.device_id, "render.home", {}) return {"ok": ok} @app.post("/api/admin/test/render") async def admin_test_render(body: TestDeviceBody) -> dict[str, Any]: sample_html = """
LIVE · AI CANVAS --:--:--

PulseWall 动态画布已就绪

当前页面由中心桥下发并通过了端侧校验与自适应渲染。

系统状态
HEALTHY
快速回报
""" return await bridge.send_render_and_wait( device_id=body.device_id, html=sample_html, mode="full", title="PulseWall 测试动态页", wait_validation_sec=12, ) return app app = create_app()