Initial commit: PulseWall hub, Android app, and protocol docs
- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
This commit is contained in:
commit
c037b43f4a
77 files changed
+20098
No files matched your search
+28
@@ -0,0 +1,28 @@
|
|||||||
|
# Local headless Android toolchain & caches
|
||||||
|
.toolchain/
|
||||||
|
.gradle/
|
||||||
|
|
||||||
|
# Python
|
||||||
|
__pycache__/
|
||||||
|
*.py[cod]
|
||||||
|
.venv/
|
||||||
|
*.db
|
||||||
|
*.sqlite3
|
||||||
|
.env
|
||||||
|
|
||||||
|
# Android / Gradle
|
||||||
|
android/.gradle/
|
||||||
|
android/local.properties
|
||||||
|
android/build/
|
||||||
|
android/app/build/
|
||||||
|
android/.idea/
|
||||||
|
*.iml
|
||||||
|
hub/releases/*.apk
|
||||||
|
hub/releases/latest.json
|
||||||
|
hub/web/node_modules/
|
||||||
|
hub/app/admin/dist/
|
||||||
|
android/vendor-builder/node_modules/
|
||||||
|
|
||||||
|
# OS / Editors
|
||||||
|
.DS_Store
|
||||||
|
*.swp
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
# PulseWall
|
||||||
|
|
||||||
|
AI-driven Android 11 live information wall, real-time device status monitor, and bidirectional MCP interactive terminal.
|
||||||
|
|
||||||
|
## Repository Layout
|
||||||
|
|
||||||
|
- `protocol/` — Canonical architecture, MCP schema, and WebSocket protocol specs:
|
||||||
|
- `protocol/architecture.md`
|
||||||
|
- `protocol/mcp-schema.md`
|
||||||
|
- `protocol/ws-protocol.md`
|
||||||
|
- `hub/` — Python Central Bridge (`FastAPI` + official `MCP` Streamable HTTP + `WebSocket` device gateway + `SQLite` + Web Admin Panel + LAN-only ADB Debug controller)
|
||||||
|
- `android/` — Android 11 (`minSdk = 30`) native Kotlin client with layered `basic`/`root` telemetry, offline Vue 3 + PulseWall CSS framework, offscreen pre-render validation sandbox, runtime console watchdog, OpenAI-compatible on-device Repair Sentinel, and unbreakable native alert/alarm layer.
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### 1. Start the Python Hub
|
||||||
|
```bash
|
||||||
|
cd /data/working/PulseWall/hub
|
||||||
|
./run_hub.sh
|
||||||
|
```
|
||||||
|
- **Web Admin Panel**: `http://<hub-ip>:8765/admin`
|
||||||
|
- **Generic MCP Endpoint (Streamable HTTP)**: `http://<hub-ip>:8765/mcp/`
|
||||||
|
- **Upstream Plugin Event Stream (SSE)**: `http://<hub-ip>:8765/api/events/stream`
|
||||||
|
- **Android WebSocket Gateway**: `ws://<hub-ip>:8765/ws/device/{device_id}`
|
||||||
|
- **LAN-Only Developer Debug / ADB API**: `POST http://<hub-ip>:8765/api/lan-debug/{device_id}/action`
|
||||||
|
|
||||||
|
### 2. Build the Android 11 APK
|
||||||
|
```bash
|
||||||
|
/data/working/PulseWall/android/build_apk.sh
|
||||||
|
```
|
||||||
|
Output APK:
|
||||||
|
`android/app/build/outputs/apk/debug/app-debug.apk`
|
||||||
|
|
||||||
|
### 3. First-Time Pairing
|
||||||
|
1. Install `app-debug.apk` onto your Android 11 device.
|
||||||
|
2. Tap the top-right floating status pill (`⚙`) to set your Hub WebSocket URL (`ws://<hub-ip>:8765`) and device name.
|
||||||
|
3. Open `http://<hub-ip>:8765/admin` to verify live device telemetry & DisplayProfile, configure your OpenAI-compatible end-side Repair AI model (pushed live to the device), and test feed/alarm/dynamic canvas rendering.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIDPTCCAiWgAwIBAgIUVnWe0FCUWnM1H7/i/rts/H4h0b0wDQYJKoZIhvcNAQEL
|
||||||
|
BQAwFTETMBEGA1UEAwwKYWktc3BlYWtlcjAeFw0yNjExMjkxNDQ2NDdaFw0zNjEx
|
||||||
|
MjYxNDQ2NDdaMBUxEzARBgNVBAMMCmFpLXNwZWFrZXIwggEiMA0GCSqGSIb3DQEB
|
||||||
|
AQUAA4IBDwAwggEKAoIBAQDB7s/3sZ9KLSF8jJCGwDm+IPZq2/x+FUdxqXyffEbK
|
||||||
|
n/1SVYNL2zKCM0BDXSBOrk9WQtBT+3ROijQ6BsG4eNtx2kMNSxscGQFwEBDxisAv
|
||||||
|
J+g1c3Euyij9DHdFrGaCxtGJbmxcT9N37r4VEnlEUZvKE5AcfS3ANuDn/3/WY/Vb
|
||||||
|
I/r61V0cpj2xQr3/ChRKw3w8M7tQrTvJArhbC1Mb3yBa57WMxdglcqeLrqLeSxpk
|
||||||
|
YHSX8Wrf4ZsBxU5d/UPv8TD5pyui9+kzzaUQxGVuByWdTc5/MspuDI1cGk3Qbeul
|
||||||
|
p3lxwFLQwvWsU7lsn2siWrypT4Q6GbbOlMlMzxyQY45HAgMBAAGjgYQwgYEwHQYD
|
||||||
|
VR0OBBYEFC0y9aSS6hLZCKZWr2AtpX+I1ZY2MB8GA1UdIwQYMBaAFC0y9aSS6hLZ
|
||||||
|
CKZWr2AtpX+I1ZY2MA8GA1UdEwEB/wQFMAMBAf8wLgYDVR0RBCcwJYcEwKgBb4cE
|
||||||
|
CioAAYcEfwAAAYIGZ2VtaW5pgglsb2NhbGhvc3QwDQYJKoZIhvcNAQELBQADggEB
|
||||||
|
AJ8Xk0fiaq0O8no0JCNEzZl5izEpy4SnWhuaEa009lxKe4924y0ORhPAeCC6ybmf
|
||||||
|
ZJLOhFgPoXxSsQwZ1wb/N8FCWboYtW1XFbtW+OsxDT7rGdmDOAAXgjmG4i3wMWLt
|
||||||
|
59LPGoEj2gOOvmNIkkga8txC5EM/OK/inURypXRSK0b2vNcCiqG4w9SSb99gDM7P
|
||||||
|
poHZHP3p2T1peqKWwuAe52bV+6Vo3Y1YO3udMyhCxcpsxbA+G2bLA8uNlvTOqcLO
|
||||||
|
SuiCsRptEYSCpd91WngXZThVL4Yly40D1DxoMRsEV/UiiYQO/A7IinbyyX7FGUCh
|
||||||
|
ZR2KSyVwb5Tjuqj5Ps/NarQ=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application")
|
||||||
|
id("org.jetbrains.kotlin.android")
|
||||||
|
}
|
||||||
|
|
||||||
|
val pwVersionCode = (project.findProperty("pwVersionCode") as String?)?.toIntOrNull() ?: 1
|
||||||
|
val pwVersionName = (project.findProperty("pwVersionName") as String?) ?: "0.1.0"
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "com.pulsewall.app"
|
||||||
|
compileSdk = 34
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
applicationId = "com.pulsewall.app"
|
||||||
|
minSdk = 30
|
||||||
|
targetSdk = 30
|
||||||
|
versionCode = pwVersionCode
|
||||||
|
versionName = pwVersionName
|
||||||
|
}
|
||||||
|
|
||||||
|
buildFeatures {
|
||||||
|
buildConfig = true
|
||||||
|
}
|
||||||
|
|
||||||
|
signingConfigs {
|
||||||
|
create("pulsewallFixed") {
|
||||||
|
storeFile = file("../keystore/pulsewall-dev.jks")
|
||||||
|
storePassword = "pulsewall123"
|
||||||
|
keyAlias = "pulsewall"
|
||||||
|
keyPassword = "pulsewall123"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
debug {
|
||||||
|
signingConfig = signingConfigs.getByName("pulsewallFixed")
|
||||||
|
}
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
signingConfig = signingConfigs.getByName("pulsewallFixed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "17"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
implementation("androidx.core:core-ktx:1.13.1")
|
||||||
|
implementation("androidx.appcompat:appcompat:1.7.0")
|
||||||
|
implementation("androidx.webkit:webkit:1.11.0")
|
||||||
|
implementation("com.squareup.okhttp3:okhttp:4.12.0")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1")
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
|
||||||
|
|
||||||
|
<uses-feature android:name="android.hardware.touchscreen" android:required="false" />
|
||||||
|
<uses-feature android:name="android.software.leanback" android:required="false" />
|
||||||
|
|
||||||
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
|
||||||
|
<uses-permission android:name="android.permission.VIBRATE" />
|
||||||
|
<uses-permission android:name="android.permission.WAKE_LOCK" />
|
||||||
|
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
|
||||||
|
<uses-permission android:name="android.permission.USE_FULL_SCREEN_INTENT" />
|
||||||
|
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
|
||||||
|
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
|
||||||
|
|
||||||
|
<application
|
||||||
|
android:allowBackup="true"
|
||||||
|
android:label="PulseWall"
|
||||||
|
android:supportsRtl="true"
|
||||||
|
android:usesCleartextTraffic="true"
|
||||||
|
android:theme="@style/Theme.PulseWall">
|
||||||
|
|
||||||
|
<activity
|
||||||
|
android:name=".MainActivity"
|
||||||
|
android:exported="true"
|
||||||
|
android:launchMode="singleTop"
|
||||||
|
android:showWhenLocked="true"
|
||||||
|
android:turnScreenOn="true"
|
||||||
|
android:configChanges="orientation|screenSize|screenLayout|smallestScreenSize|keyboardHidden">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.MAIN" />
|
||||||
|
<category android:name="android.intent.category.LAUNCHER" />
|
||||||
|
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
|
||||||
|
</intent-filter>
|
||||||
|
</activity>
|
||||||
|
|
||||||
|
<service
|
||||||
|
android:name=".service.PulseWallKeepAliveService"
|
||||||
|
android:exported="false" />
|
||||||
|
|
||||||
|
<receiver
|
||||||
|
android:name=".service.BootReceiver"
|
||||||
|
android:exported="true">
|
||||||
|
<intent-filter>
|
||||||
|
<action android:name="android.intent.action.BOOT_COMPLETED" />
|
||||||
|
<action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
|
||||||
|
</intent-filter>
|
||||||
|
</receiver>
|
||||||
|
|
||||||
|
<provider
|
||||||
|
android:name="androidx.core.content.FileProvider"
|
||||||
|
android:authorities="${applicationId}.fileprovider"
|
||||||
|
android:exported="false"
|
||||||
|
android:grantUriPermissions="true">
|
||||||
|
<meta-data
|
||||||
|
android:name="android.support.FILE_PROVIDER_PATHS"
|
||||||
|
android:resource="@xml/file_paths" />
|
||||||
|
</provider>
|
||||||
|
</application>
|
||||||
|
</manifest>
|
||||||
@@ -0,0 +1,502 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||||
|
<title>PulseWall Host</title>
|
||||||
|
<link rel="stylesheet" href="./pulsewall-tokens.css" />
|
||||||
|
<link rel="stylesheet" href="./libs/tailwind-lite.min.css" />
|
||||||
|
<script src="./vue.global.prod.js"></script>
|
||||||
|
<script src="./libs/dayjs.min.js"></script>
|
||||||
|
<script src="./libs/pw-icons.min.js"></script>
|
||||||
|
<script src="./pw-lib-loader.js"></script>
|
||||||
|
<style>
|
||||||
|
#pw-stage-host {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
z-index: 50;
|
||||||
|
display: none;
|
||||||
|
background: #0a0f1d;
|
||||||
|
}
|
||||||
|
#pw-stage-host.active {
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
#pw-stage-frame {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border: 0;
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background: #0a0f1d;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<!-- Layer 1: Built-in Home Screen (frozen & hidden when AI custom page is active) -->
|
||||||
|
<div id="pw-home-layer">
|
||||||
|
<div id="pw-shell">
|
||||||
|
<div id="pw-canvas">
|
||||||
|
<div class="pw-stack">
|
||||||
|
<div class="pw-card pw-hero">
|
||||||
|
<div class="pw-row pw-between">
|
||||||
|
<span class="pw-pill" id="pw-conn-pill">等待连接中心桥...</span>
|
||||||
|
<span class="pw-muted" id="pw-clock">--:--:--</span>
|
||||||
|
</div>
|
||||||
|
<h1 style="margin:10px 0 6px;font-size:24px;">PulseWall 信息墙</h1>
|
||||||
|
<div class="pw-muted" id="pw-conn-detail" style="margin-bottom:10px;">正在尝试连接中心桥...</div>
|
||||||
|
<div class="pw-row">
|
||||||
|
<button class="pw-btn pw-btn-primary" id="btn-discover" onclick="window.PulseWall.discoverHub()">🔍 自动搜索局域网中心桥</button>
|
||||||
|
<button class="pw-btn pw-btn-secondary" id="btn-settings" onclick="window.PulseWall.openSettings()">⚙ 打开终端设置</button>
|
||||||
|
<button class="pw-btn pw-btn-secondary" id="btn-ota" onclick="window.PulseWall.checkUpdate()">🔄 检查自更新</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pw-tv-hint">
|
||||||
|
🎮 遥控器操作指南:<b>上下左右</b> 移动焦点/滚屏 · <b>OK/确定</b> 点击选中项 · <b>菜单键(MENU)</b> 随时打开设置
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pw-grid-2">
|
||||||
|
<div class="pw-card">
|
||||||
|
<div class="pw-muted">屏幕规格</div>
|
||||||
|
<div class="pw-metric" id="pw-viewport">--</div>
|
||||||
|
</div>
|
||||||
|
<div class="pw-card">
|
||||||
|
<div class="pw-muted">电量 / 温度</div>
|
||||||
|
<div class="pw-metric" id="pw-power">--</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="pw-card">
|
||||||
|
<div class="pw-row pw-between" style="margin-bottom:10px;">
|
||||||
|
<strong>实时信息流</strong>
|
||||||
|
<span class="pw-muted" id="pw-feed-count">0 条</span>
|
||||||
|
</div>
|
||||||
|
<div id="pw-feed-list">
|
||||||
|
<div class="pw-muted">暂无动态,等待 AI 通过 MCP 推送...</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Layer 2: Isolated Fullscreen AI Page Stage (at most ONE active iframe; 100% torn down on replace/home) -->
|
||||||
|
<div id="pw-stage-host"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var BASE_HREF = "https://appassets.androidplatform.net/assets/pulsewall/";
|
||||||
|
var feedItems = [];
|
||||||
|
var currentSnapshotId = "builtin_home";
|
||||||
|
var currentTaskId = "";
|
||||||
|
var deviceProfile = {};
|
||||||
|
var telemetry = {};
|
||||||
|
var lastConnected = false;
|
||||||
|
var lastConnDetail = "";
|
||||||
|
var currentFocusEl = null;
|
||||||
|
var isCustomMode = false;
|
||||||
|
var isHostFrozen = false;
|
||||||
|
var activeStageFrame = null;
|
||||||
|
var homeClockTimer = null;
|
||||||
|
|
||||||
|
function startHomeClock() {
|
||||||
|
stopHomeClock();
|
||||||
|
if (isCustomMode || isHostFrozen) return;
|
||||||
|
function tick() {
|
||||||
|
var el = document.getElementById("pw-clock");
|
||||||
|
if (el) el.textContent = new Date().toLocaleTimeString();
|
||||||
|
}
|
||||||
|
tick();
|
||||||
|
homeClockTimer = setInterval(tick, 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopHomeClock() {
|
||||||
|
if (homeClockTimer) {
|
||||||
|
clearInterval(homeClockTimer);
|
||||||
|
homeClockTimer = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function notifyRuntimeError(source, message, stack) {
|
||||||
|
try {
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.onRuntimeError) {
|
||||||
|
window.AndroidBridge.onRuntimeError(
|
||||||
|
currentSnapshotId,
|
||||||
|
currentTaskId,
|
||||||
|
String(source || "runtime"),
|
||||||
|
String(message || "Unknown error"),
|
||||||
|
String(stack || "")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.__pwOnStageError = function (source, message, stack) {
|
||||||
|
notifyRuntimeError(source, message, stack);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.onerror = function (msg, url, line, col, err) {
|
||||||
|
notifyRuntimeError("window.onerror", msg + " (" + line + ":" + col + ")", err && err.stack ? err.stack : "");
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
window.addEventListener("unhandledrejection", function (ev) {
|
||||||
|
var r = ev && ev.reason;
|
||||||
|
notifyRuntimeError("unhandledrejection", r && r.message ? r.message : String(r), r && r.stack ? r.stack : "");
|
||||||
|
});
|
||||||
|
|
||||||
|
function buildStageDocument(rawHtml) {
|
||||||
|
var html = String(rawHtml || "");
|
||||||
|
var headInject =
|
||||||
|
'<base href="' + BASE_HREF + '" />' +
|
||||||
|
'<link rel="stylesheet" href="./pulsewall-tokens.css" />' +
|
||||||
|
'<link rel="stylesheet" href="./libs/tailwind-lite.min.css" />' +
|
||||||
|
'<script src="./vue.global.prod.js"><\/script>' +
|
||||||
|
'<script src="./libs/dayjs.min.js"><\/script>' +
|
||||||
|
'<script src="./libs/pw-icons.min.js"><\/script>' +
|
||||||
|
'<script src="./pw-lib-loader.js"><\/script>' +
|
||||||
|
'<script src="./pw-stage-bootstrap.js"><\/script>';
|
||||||
|
|
||||||
|
var isFullDoc = /<\s*!doctype\b|<\s*html\b/i.test(html);
|
||||||
|
if (isFullDoc) {
|
||||||
|
if (/<\s*head\b[^>]*>/i.test(html)) {
|
||||||
|
return html.replace(/<\s*head\b[^>]*>/i, function (m) { return m + "\n" + headInject + "\n"; });
|
||||||
|
}
|
||||||
|
if (/<\s*html\b[^>]*>/i.test(html)) {
|
||||||
|
return html.replace(/<\s*html\b[^>]*>/i, function (m) { return m + "\n<head>" + headInject + "</head>\n"; });
|
||||||
|
}
|
||||||
|
return "<head>" + headInject + "</head>" + html;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
'<!DOCTYPE html><html lang="zh-CN"><head>' +
|
||||||
|
'<meta charset="UTF-8" />' +
|
||||||
|
'<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />' +
|
||||||
|
headInject +
|
||||||
|
'<style>html,body{margin:0;padding:0;width:100%;min-height:100vh;background:#0a0f1d;color:#eef4ff;overflow-x:hidden;}</style>' +
|
||||||
|
'</head><body>' + html + '</body></html>'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function teardownStageFrame() {
|
||||||
|
var host = document.getElementById("pw-stage-host");
|
||||||
|
if (activeStageFrame) {
|
||||||
|
var old = activeStageFrame;
|
||||||
|
activeStageFrame = null;
|
||||||
|
try {
|
||||||
|
var w = old.contentWindow;
|
||||||
|
if (w && typeof w.__pwPageDispose === "function") {
|
||||||
|
w.__pwPageDispose();
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
old.src = "about:blank";
|
||||||
|
} catch (_) {}
|
||||||
|
try {
|
||||||
|
if (old.parentNode) old.parentNode.removeChild(old);
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (host) {
|
||||||
|
host.innerHTML = "";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- IR Remote / TV D-Pad Spatial Navigation Engine (Home Layer) ----
|
||||||
|
function getFocusables() {
|
||||||
|
var home = document.getElementById("pw-home-layer");
|
||||||
|
if (!home || home.style.display === "none") return [];
|
||||||
|
var nodes = home.querySelectorAll("button, a[href], input, select, textarea, [tabindex], [role='button'], [onclick], .pw-btn");
|
||||||
|
return Array.prototype.slice.call(nodes).filter(function (el) {
|
||||||
|
if (el.disabled) return false;
|
||||||
|
var rect = el.getBoundingClientRect();
|
||||||
|
return rect.width > 4 && rect.height > 4 && window.getComputedStyle(el).visibility !== "hidden";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearTvFocus() {
|
||||||
|
if (currentFocusEl) {
|
||||||
|
currentFocusEl.classList.remove("pw-tv-focus");
|
||||||
|
currentFocusEl = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setTvFocus(el) {
|
||||||
|
if (!el) return;
|
||||||
|
if (currentFocusEl && currentFocusEl !== el) currentFocusEl.classList.remove("pw-tv-focus");
|
||||||
|
currentFocusEl = el;
|
||||||
|
el.classList.add("pw-tv-focus");
|
||||||
|
try { el.focus({ preventScroll: true }); } catch (e) {}
|
||||||
|
try { el.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" }); } catch (e) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function findNextFocusable(dir) {
|
||||||
|
var list = getFocusables();
|
||||||
|
if (!list.length) return null;
|
||||||
|
if (!currentFocusEl || list.indexOf(currentFocusEl) === -1) return list[0];
|
||||||
|
var cur = currentFocusEl.getBoundingClientRect();
|
||||||
|
var cx = cur.left + cur.width / 2;
|
||||||
|
var cy = cur.top + cur.height / 2;
|
||||||
|
var best = null;
|
||||||
|
var bestScore = Infinity;
|
||||||
|
for (var i = 0; i < list.length; i++) {
|
||||||
|
var el = list[i];
|
||||||
|
if (el === currentFocusEl) continue;
|
||||||
|
var r = el.getBoundingClientRect();
|
||||||
|
var dx = r.left + r.width / 2 - cx;
|
||||||
|
var dy = r.top + r.height / 2 - cy;
|
||||||
|
var valid = false, primary = 0, secondary = 0;
|
||||||
|
if (dir === "right" && dx > 6) { valid = true; primary = dx; secondary = Math.abs(dy); }
|
||||||
|
else if (dir === "left" && dx < -6) { valid = true; primary = -dx; secondary = Math.abs(dy); }
|
||||||
|
else if (dir === "down" && dy > 6) { valid = true; primary = dy; secondary = Math.abs(dx); }
|
||||||
|
else if (dir === "up" && dy < -6) { valid = true; primary = -dy; secondary = Math.abs(dx); }
|
||||||
|
if (valid) {
|
||||||
|
var score = primary + secondary * 2.2;
|
||||||
|
if (score < bestScore) { bestScore = score; best = el; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
window.__pwClearTvFocus = clearTvFocus;
|
||||||
|
window.__pwFocusFirst = function () {
|
||||||
|
if (isCustomMode && activeStageFrame && activeStageFrame.contentWindow && activeStageFrame.contentWindow.__pwFocusFirst) {
|
||||||
|
try { activeStageFrame.contentWindow.__pwFocusFirst(); } catch (_) {}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var list = getFocusables();
|
||||||
|
if (list.length) setTvFocus(list[0]);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__pwRemoteKey = function (dir) {
|
||||||
|
if (isCustomMode && activeStageFrame && activeStageFrame.contentWindow && activeStageFrame.contentWindow.__pwRemoteKey) {
|
||||||
|
try { return !!activeStageFrame.contentWindow.__pwRemoteKey(dir); } catch (_) { return false; }
|
||||||
|
}
|
||||||
|
if (dir === "ok") {
|
||||||
|
if (!currentFocusEl || !document.body.contains(currentFocusEl)) window.__pwFocusFirst();
|
||||||
|
if (currentFocusEl) currentFocusEl.click();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var next = findNextFocusable(dir);
|
||||||
|
if (next) { setTvFocus(next); return true; }
|
||||||
|
if (dir === "down") { window.scrollBy({ top: 240, behavior: "smooth" }); return true; }
|
||||||
|
if (dir === "up") {
|
||||||
|
if (window.scrollY > 10) {
|
||||||
|
window.scrollBy({ top: -240, behavior: "smooth" });
|
||||||
|
} else {
|
||||||
|
clearTvFocus();
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.onFocusTopBar) {
|
||||||
|
window.AndroidBridge.onFocusTopBar();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Public Bridge API
|
||||||
|
window.PulseWall = {
|
||||||
|
loadLib: function (names) {
|
||||||
|
return window.__pwLibLoader ? window.__pwLibLoader.loadLib(names) : Promise.reject(new Error("LibLoader unavailable"));
|
||||||
|
},
|
||||||
|
libs: window.__pwLibLoader ? Object.keys(window.__pwLibLoader.catalog) : [],
|
||||||
|
sendAction: function (presetId, label, customText) {
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.onWebAction) {
|
||||||
|
window.AndroidBridge.onWebAction(
|
||||||
|
String(presetId || "web_action"),
|
||||||
|
String(label || presetId || ""),
|
||||||
|
customText == null ? "" : String(customText)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
openSettings: function () {
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.openSettings) window.AndroidBridge.openSettings();
|
||||||
|
},
|
||||||
|
discoverHub: function () {
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.discoverHub) window.AndroidBridge.discoverHub();
|
||||||
|
},
|
||||||
|
checkUpdate: function () {
|
||||||
|
if (window.AndroidBridge && window.AndroidBridge.checkUpdate) window.AndroidBridge.checkUpdate();
|
||||||
|
},
|
||||||
|
getDeviceProfile: function () { return deviceProfile; },
|
||||||
|
getTelemetry: function () { return telemetry; },
|
||||||
|
getDataContext: function () { return window.__PW_DATA__ || {}; }
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__pwApplySafeArea = function (topDp, bottomDp) {
|
||||||
|
document.documentElement.style.setProperty("--safe-top", (topDp || 28) + "px");
|
||||||
|
document.documentElement.style.setProperty("--safe-bottom", (bottomDp || 16) + "px");
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__pwUpdateStatus = function (connected, profileJson, telemetryJson, connDetail) {
|
||||||
|
lastConnected = !!connected;
|
||||||
|
if (connDetail) lastConnDetail = connDetail;
|
||||||
|
try { deviceProfile = JSON.parse(profileJson || "{}"); } catch (e) {}
|
||||||
|
try { telemetry = JSON.parse(telemetryJson || "{}"); } catch (e) {}
|
||||||
|
if (!isCustomMode) renderHomeStatus();
|
||||||
|
};
|
||||||
|
|
||||||
|
function renderHomeStatus() {
|
||||||
|
var pill = document.getElementById("pw-conn-pill");
|
||||||
|
if (pill) {
|
||||||
|
pill.textContent = lastConnected ? "已连接中心桥" : "未连接 · 重试中";
|
||||||
|
pill.className = "pw-pill " + (lastConnected ? "pw-ok" : "pw-warn");
|
||||||
|
}
|
||||||
|
var det = document.getElementById("pw-conn-detail");
|
||||||
|
if (det && lastConnDetail) det.textContent = lastConnDetail;
|
||||||
|
var vp = document.getElementById("pw-viewport");
|
||||||
|
if (vp && deviceProfile.viewport_css_w) {
|
||||||
|
vp.textContent = deviceProfile.viewport_css_w + "×" + deviceProfile.viewport_css_h + " (" + (deviceProfile.device_type || "device") + ")";
|
||||||
|
}
|
||||||
|
var pw = document.getElementById("pw-power");
|
||||||
|
if (pw) {
|
||||||
|
var bat = telemetry.battery_pct != null ? (telemetry.battery_pct + "%") : "外接电源";
|
||||||
|
var tmp = telemetry.battery_temp_c != null ? (telemetry.battery_temp_c + "°C") : "--";
|
||||||
|
pw.textContent = bat + " / " + tmp;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s) {
|
||||||
|
return String(s || "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderFeedList() {
|
||||||
|
var listEl = document.getElementById("pw-feed-list");
|
||||||
|
var cntEl = document.getElementById("pw-feed-count");
|
||||||
|
if (cntEl) cntEl.textContent = feedItems.length + " 条";
|
||||||
|
if (listEl) {
|
||||||
|
if (!feedItems.length) {
|
||||||
|
listEl.innerHTML = '<div class="pw-muted">暂无动态,等待 AI 通过 MCP 推送...</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
listEl.innerHTML = feedItems.map(function (it) {
|
||||||
|
var bodyHtml = it.html_snippet ? it.html_snippet : "<div>" + escapeHtml(it.body) + "</div>";
|
||||||
|
var timeStr = new Date(it.ts || Date.now()).toLocaleTimeString();
|
||||||
|
return '<div class="pw-feed-item level-' + escapeHtml(it.level || "info") + '">' +
|
||||||
|
'<div class="pw-row pw-between"><strong>' + escapeHtml(it.title) + '</strong><span class="pw-muted">' + timeStr + '</span></div>' +
|
||||||
|
'<div style="margin-top:4px;font-size:13px;color:#cbd5e1;">' + bodyHtml + '</div>' +
|
||||||
|
'</div>';
|
||||||
|
}).join("");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
window.__pwPushFeed = function (itemJson) {
|
||||||
|
try {
|
||||||
|
var item = JSON.parse(itemJson);
|
||||||
|
feedItems.unshift(item);
|
||||||
|
if (feedItems.length > 50) feedItems.pop();
|
||||||
|
if (!isCustomMode) renderFeedList();
|
||||||
|
} catch (e) {
|
||||||
|
notifyRuntimeError("feed_render", e.message, e.stack);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Freeze / unfreeze active page layer when Activity moves to background / foreground
|
||||||
|
window.__pwFreezeActiveLayer = function (frozen) {
|
||||||
|
isHostFrozen = !!frozen;
|
||||||
|
if (isHostFrozen) {
|
||||||
|
stopHomeClock();
|
||||||
|
if (activeStageFrame && activeStageFrame.contentWindow && activeStageFrame.contentWindow.__pwSetFrozen) {
|
||||||
|
try { activeStageFrame.contentWindow.__pwSetFrozen(true); } catch (_) {}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (isCustomMode) {
|
||||||
|
if (activeStageFrame && activeStageFrame.contentWindow && activeStageFrame.contentWindow.__pwSetFrozen) {
|
||||||
|
try { activeStageFrame.contentWindow.__pwSetFrozen(false); } catch (_) {}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
renderHomeStatus();
|
||||||
|
renderFeedList();
|
||||||
|
startHomeClock();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__pwRestoreHome = function () {
|
||||||
|
isCustomMode = false;
|
||||||
|
currentTaskId = "";
|
||||||
|
currentSnapshotId = "builtin_home";
|
||||||
|
window.__PW_DATA__ = {};
|
||||||
|
teardownStageFrame();
|
||||||
|
|
||||||
|
var stageHost = document.getElementById("pw-stage-host");
|
||||||
|
if (stageHost) stageHost.classList.remove("active");
|
||||||
|
var homeLayer = document.getElementById("pw-home-layer");
|
||||||
|
if (homeLayer) homeLayer.style.display = "block";
|
||||||
|
|
||||||
|
clearTvFocus();
|
||||||
|
renderHomeStatus();
|
||||||
|
renderFeedList();
|
||||||
|
startHomeClock();
|
||||||
|
window.scrollTo(0, 0);
|
||||||
|
setTimeout(function () { window.__pwFocusFirst(); }, 100);
|
||||||
|
};
|
||||||
|
|
||||||
|
window.__pwMountCanvas = function (payloadB64) {
|
||||||
|
try {
|
||||||
|
var bytes = Uint8Array.from(atob(payloadB64), function (c) { return c.charCodeAt(0); });
|
||||||
|
var payload = JSON.parse(new TextDecoder("utf-8").decode(bytes));
|
||||||
|
currentTaskId = payload.task_id || "";
|
||||||
|
currentSnapshotId = payload.snapshot_id || "custom";
|
||||||
|
window.__PW_DATA__ = payload.data_context || {};
|
||||||
|
|
||||||
|
// 1. Completely destroy previous AI page iframe & freeze Home layer
|
||||||
|
teardownStageFrame();
|
||||||
|
isCustomMode = true;
|
||||||
|
stopHomeClock();
|
||||||
|
clearTvFocus();
|
||||||
|
|
||||||
|
var homeLayer = document.getElementById("pw-home-layer");
|
||||||
|
if (homeLayer) homeLayer.style.display = "none";
|
||||||
|
|
||||||
|
var stageHost = document.getElementById("pw-stage-host");
|
||||||
|
if (!stageHost) return;
|
||||||
|
stageHost.classList.add("active");
|
||||||
|
|
||||||
|
// 2. Mount new AI page in a clean isolated fullscreen iframe
|
||||||
|
var iframe = document.createElement("iframe");
|
||||||
|
iframe.id = "pw-stage-frame";
|
||||||
|
iframe.setAttribute("allow", "autoplay; fullscreen");
|
||||||
|
stageHost.appendChild(iframe);
|
||||||
|
activeStageFrame = iframe;
|
||||||
|
|
||||||
|
var doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
|
||||||
|
if (!doc) {
|
||||||
|
notifyRuntimeError("mount_canvas", "Unable to access isolated stage iframe document", "");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
doc.open();
|
||||||
|
doc.write(buildStageDocument(payload.html || ""));
|
||||||
|
doc.close();
|
||||||
|
|
||||||
|
if (isHostFrozen && iframe.contentWindow && iframe.contentWindow.__pwSetFrozen) {
|
||||||
|
try { iframe.contentWindow.__pwSetFrozen(true); } catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
setTimeout(function () {
|
||||||
|
if (activeStageFrame !== iframe) return;
|
||||||
|
try {
|
||||||
|
var w = iframe.contentWindow;
|
||||||
|
var d = iframe.contentDocument;
|
||||||
|
if (w && w.__pwFocusFirst) w.__pwFocusFirst();
|
||||||
|
if (d && w) {
|
||||||
|
var overflow = d.documentElement.scrollWidth - w.innerWidth;
|
||||||
|
if (overflow > 16) {
|
||||||
|
notifyRuntimeError("layout_overflow", "Horizontal overflow detected: +" + overflow + "px on viewport " + w.innerWidth + "px", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}, 400);
|
||||||
|
} catch (e) {
|
||||||
|
notifyRuntimeError("mount_canvas", e.message, e.stack);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
startHomeClock();
|
||||||
|
setTimeout(function () { window.__pwFocusFirst(); }, 300);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
/*
|
||||||
|
* anime.js v3.2.2
|
||||||
|
* (c) 2023 Julian Garnier
|
||||||
|
* Released under the MIT license
|
||||||
|
* animejs.com
|
||||||
|
*/
|
||||||
|
|
||||||
|
!function(n,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):n.anime=e()}(this,function(){"use strict";var i={update:null,begin:null,loopBegin:null,changeBegin:null,change:null,changeComplete:null,loopComplete:null,complete:null,loop:1,direction:"normal",autoplay:!0,timelineOffset:0},M={duration:1e3,delay:0,endDelay:0,easing:"easeOutElastic(1, .5)",round:0},j=["translateX","translateY","translateZ","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skew","skewX","skewY","perspective","matrix","matrix3d"],l={CSS:{},springs:{}};function C(n,e,t){return Math.min(Math.max(n,e),t)}function u(n,e){return-1<n.indexOf(e)}function o(n,e){return n.apply(null,e)}var w={arr:function(n){return Array.isArray(n)},obj:function(n){return u(Object.prototype.toString.call(n),"Object")},pth:function(n){return w.obj(n)&&n.hasOwnProperty("totalLength")},svg:function(n){return n instanceof SVGElement},inp:function(n){return n instanceof HTMLInputElement},dom:function(n){return n.nodeType||w.svg(n)},str:function(n){return"string"==typeof n},fnc:function(n){return"function"==typeof n},und:function(n){return void 0===n},nil:function(n){return w.und(n)||null===n},hex:function(n){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(n)},rgb:function(n){return/^rgb/.test(n)},hsl:function(n){return/^hsl/.test(n)},col:function(n){return w.hex(n)||w.rgb(n)||w.hsl(n)},key:function(n){return!i.hasOwnProperty(n)&&!M.hasOwnProperty(n)&&"targets"!==n&&"keyframes"!==n}};function d(n){n=/\(([^)]+)\)/.exec(n);return n?n[1].split(",").map(function(n){return parseFloat(n)}):[]}function c(r,t){var n=d(r),e=C(w.und(n[0])?1:n[0],.1,100),a=C(w.und(n[1])?100:n[1],.1,100),o=C(w.und(n[2])?10:n[2],.1,100),n=C(w.und(n[3])?0:n[3],.1,100),u=Math.sqrt(a/e),i=o/(2*Math.sqrt(a*e)),c=i<1?u*Math.sqrt(1-i*i):0,s=i<1?(i*u-n)/c:-n+u;function f(n){var e=t?t*n/1e3:n,e=i<1?Math.exp(-e*i*u)*(+Math.cos(c*e)+s*Math.sin(c*e)):(1+s*e)*Math.exp(-e*u);return 0===n||1===n?n:1-e}return t?f:function(){var n=l.springs[r];if(n)return n;for(var e=0,t=0;;)if(1===f(e+=1/6)){if(16<=++t)break}else t=0;return n=e*(1/6)*1e3,l.springs[r]=n}}function q(e){return void 0===e&&(e=10),function(n){return Math.ceil(C(n,1e-6,1)*e)*(1/e)}}var H=function(b,e,M,t){if(0<=b&&b<=1&&0<=M&&M<=1){var x=new Float32Array(11);if(b!==e||M!==t)for(var n=0;n<11;++n)x[n]=k(.1*n,b,M);return function(n){return b===e&&M===t||0===n||1===n?n:k(r(n),e,t)}}function r(n){for(var e=0,t=1;10!==t&&x[t]<=n;++t)e+=.1;var r=e+.1*((n-x[--t])/(x[t+1]-x[t])),a=O(r,b,M);if(.001<=a){for(var o=n,u=r,i=b,c=M,s=0;s<4;++s){var f=O(u,i,c);if(0===f)return u;u-=(k(u,i,c)-o)/f}return u}if(0===a)return r;for(var l,d,p=n,h=e,g=e+.1,m=b,v=M,y=0;0<(l=k(d=h+(g-h)/2,m,v)-p)?g=d:h=d,1e-7<Math.abs(l)&&++y<10;);return d}};function r(n,e){return 1-3*e+3*n}function k(n,e,t){return((r(e,t)*n+(3*t-6*e))*n+3*e)*n}function O(n,e,t){return 3*r(e,t)*n*n+2*(3*t-6*e)*n+3*e}e={linear:function(){return function(n){return n}}},t={Sine:function(){return function(n){return 1-Math.cos(n*Math.PI/2)}},Expo:function(){return function(n){return n?Math.pow(2,10*n-10):0}},Circ:function(){return function(n){return 1-Math.sqrt(1-n*n)}},Back:function(){return function(n){return n*n*(3*n-2)}},Bounce:function(){return function(n){for(var e,t=4;n<((e=Math.pow(2,--t))-1)/11;);return 1/Math.pow(4,3-t)-7.5625*Math.pow((3*e-2)/22-n,2)}},Elastic:function(n,e){void 0===e&&(e=.5);var t=C(n=void 0===n?1:n,1,10),r=C(e,.1,2);return function(n){return 0===n||1===n?n:-t*Math.pow(2,10*(n-1))*Math.sin((n-1-r/(2*Math.PI)*Math.asin(1/t))*(2*Math.PI)/r)}}},["Quad","Cubic","Quart","Quint"].forEach(function(n,e){t[n]=function(){return function(n){return Math.pow(n,e+2)}}}),Object.keys(t).forEach(function(n){var r=t[n];e["easeIn"+n]=r,e["easeOut"+n]=function(e,t){return function(n){return 1-r(e,t)(1-n)}},e["easeInOut"+n]=function(e,t){return function(n){return n<.5?r(e,t)(2*n)/2:1-r(e,t)(-2*n+2)/2}},e["easeOutIn"+n]=function(e,t){return function(n){return n<.5?(1-r(e,t)(1-2*n))/2:(r(e,t)(2*n-1)+1)/2}}});var e,t,s=e;function P(n,e){if(w.fnc(n))return n;var t=n.split("(")[0],r=s[t],a=d(n);switch(t){case"spring":return c(n,e);case"cubicBezier":return o(H,a);case"steps":return o(q,a);default:return o(r,a)}}function a(n){try{return document.querySelectorAll(n)}catch(n){}}function I(n,e){for(var t,r=n.length,a=2<=arguments.length?e:void 0,o=[],u=0;u<r;u++)u in n&&(t=n[u],e.call(a,t,u,n))&&o.push(t);return o}function f(n){return n.reduce(function(n,e){return n.concat(w.arr(e)?f(e):e)},[])}function p(n){return w.arr(n)?n:(n=w.str(n)?a(n)||n:n)instanceof NodeList||n instanceof HTMLCollection?[].slice.call(n):[n]}function h(n,e){return n.some(function(n){return n===e})}function g(n){var e,t={};for(e in n)t[e]=n[e];return t}function x(n,e){var t,r=g(n);for(t in n)r[t]=(e.hasOwnProperty(t)?e:n)[t];return r}function D(n,e){var t,r=g(n);for(t in e)r[t]=(w.und(n[t])?e:n)[t];return r}function V(n){var e,t,r,a,o,u,i;retuLine truncated
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).dayjs=e()}(this,(function(){"use strict";var t=1e3,e=6e4,n=36e5,r="millisecond",i="second",s="minute",u="hour",a="day",o="week",c="month",f="quarter",h="year",d="date",l="Invalid Date",$=/^(\d{4})[-/]?(\d{1,2})?[-/]?(\d{0,2})[Tt\s]*(\d{1,2})?:?(\d{1,2})?:?(\d{1,2})?[.:]?(\d+)?$/,y=/\[([^\]]+)]|YYYY|YY|M{1,4}|D{1,2}|d{1,4}|H{1,2}|h{1,2}|a|A|m{1,2}|s{1,2}|Z{1,2}|SSS/g,M={name:"en",weekdays:"Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),months:"January_February_March_April_May_June_July_August_September_October_November_December".split("_"),ordinal:function(t){var e=["th","st","nd","rd"],n=t%100;return"["+t+(e[(n-20)%10]||e[n]||e[0])+"]"}},m=function(t,e,n){var r=String(t);return!r||r.length>=e?t:""+Array(e+1-r.length).join(n)+t},v={s:m,z:function(t){var e=-t.utcOffset(),n=Math.abs(e),r=Math.floor(n/60),i=n%60;return(e<=0?"+":"-")+m(r,2,"0")+":"+m(i,2,"0")},m:function t(e,n){if(e.date()<n.date())return-t(n,e);var r=12*(n.year()-e.year())+(n.month()-e.month()),i=e.clone().add(r,c),s=n-i<0,u=e.clone().add(r+(s?-1:1),c);return+(-(r+(n-i)/(s?i-u:u-i))||0)},a:function(t){return t<0?Math.ceil(t)||0:Math.floor(t)},p:function(t){return{M:c,y:h,w:o,d:a,D:d,h:u,m:s,s:i,ms:r,Q:f}[t]||String(t||"").toLowerCase().replace(/s$/,"")},u:function(t){return void 0===t}},g="en",D={};D[g]=M;var p="$isDayjsObject",S=function(t){return t instanceof _||!(!t||!t[p])},w=function t(e,n,r){var i;if(!e)return g;if("string"==typeof e){var s=e.toLowerCase();D[s]&&(i=s),n&&(D[s]=n,i=s);var u=e.split("-");if(!i&&u.length>1)return t(u[0])}else{var a=e.name;D[a]=e,i=a}return!r&&i&&(g=i),i||!r&&g},O=function(t,e){if(S(t))return t.clone();var n="object"==typeof e?e:{};return n.date=t,n.args=arguments,new _(n)},b=v;b.l=w,b.i=S,b.w=function(t,e){return O(t,{locale:e.$L,utc:e.$u,x:e.$x,$offset:e.$offset})};var _=function(){function M(t){this.$L=w(t.locale,null,!0),this.parse(t),this.$x=this.$x||t.x||{},this[p]=!0}var m=M.prototype;return m.parse=function(t){this.$d=function(t){var e=t.date,n=t.utc;if(null===e)return new Date(NaN);if(b.u(e))return new Date;if(e instanceof Date)return new Date(e);if("string"==typeof e&&!/Z$/i.test(e)){var r=e.match($);if(r){var i=r[2]-1||0,s=(r[7]||"0").substring(0,3);return n?new Date(Date.UTC(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)):new Date(r[1],i,r[3]||1,r[4]||0,r[5]||0,r[6]||0,s)}}return new Date(e)}(t),this.init()},m.init=function(){var t=this.$d;this.$y=t.getFullYear(),this.$M=t.getMonth(),this.$D=t.getDate(),this.$W=t.getDay(),this.$H=t.getHours(),this.$m=t.getMinutes(),this.$s=t.getSeconds(),this.$ms=t.getMilliseconds()},m.$utils=function(){return b},m.isValid=function(){return!(this.$d.toString()===l)},m.isSame=function(t,e){var n=O(t);return this.startOf(e)<=n&&n<=this.endOf(e)},m.isAfter=function(t,e){return O(t)<this.startOf(e)},m.isBefore=function(t,e){return this.endOf(e)<O(t)},m.$g=function(t,e,n){return b.u(t)?this[e]:this.set(n,t)},m.unix=function(){return Math.floor(this.valueOf()/1e3)},m.valueOf=function(){return this.$d.getTime()},m.startOf=function(t,e){var n=this,r=!!b.u(e)||e,f=b.p(t),l=function(t,e){var i=b.w(n.$u?Date.UTC(n.$y,e,t):new Date(n.$y,e,t),n);return r?i:i.endOf(a)},$=function(t,e){return b.w(n.toDate()[t].apply(n.toDate("s"),(r?[0,0,0,0]:[23,59,59,999]).slice(e)),n)},y=this.$W,M=this.$M,m=this.$D,v="set"+(this.$u?"UTC":"");switch(f){case h:return r?l(1,0):l(31,11);case c:return r?l(1,M):l(0,M+1);case o:var g=this.$locale().weekStart||0,D=(y<g?y+7:y)-g;return l(r?m-D:m+(6-D),M);case a:case d:return $(v+"Hours",0);case u:return $(v+"Minutes",1);case s:return $(v+"Seconds",2);case i:return $(v+"Milliseconds",3);default:return this.clone()}},m.endOf=function(t){return this.startOf(t,!1)},m.$set=function(t,e){var n,o=b.p(t),f="set"+(this.$u?"UTC":""),l=(n={},n[a]=f+"Date",n[d]=f+"Date",n[c]=f+"Month",n[h]=f+"FullYear",n[u]=f+"Hours",n[s]=f+"Minutes",n[i]=f+"Seconds",n[r]=f+"Milliseconds",n)[o],$=o===a?this.$D+(e-this.$W):e;if(o===c||o===h){var y=this.clone().set(d,1);y.$d[l]($),y.init(),this.$d=y.set(d,Math.min(this.$D,y.daysInMonth())).$d}else l&&this.$d[l]($);return this.init(),this},m.set=function(t,e){return this.clone().$set(t,e)},m.get=function(t){return this[b.p(t)]()},m.add=function(r,f){var d,l=this;r=Number(r);var $=b.p(f),y=function(t){var e=O(l);return b.w(e.date(e.date()+Math.round(t*r)),l)};if($===c)return this.set(c,this.$M+r);if($===h)return this.set(h,this.$y+r);if($===a)return y(1);if($===o)return y(7);var M=(d={},d[s]=e,d[u]=n,d[i]=t,d)[$]||1,m=this.$d.getTime()+r*M;return b.w(m,this)},m.subtract=function(t,e){return this.add(-1*t,e)},m.format=function(t){var e=this,n=this.$locale();if(!this.isValid())return n.invalidDate||l;var r=t||"YYYY-MM-DDTHH:mm:ssZ",i=b.z(this),s=this.$H,u=this.$m,a=this.$M,o=n.weekdays,c=n.months,f=n.meridiem,h=function(t,n,i,s){retLine truncated
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
var echarts=(()=>{var Oh=Object.defineProperty;var QT=Object.getOwnPropertyDescriptor;var JT=Object.getOwnPropertyNames;var $T=Object.prototype.hasOwnProperty;var Ae=(r,t)=>{for(var e in t)Oh(r,e,{get:t[e],enumerable:!0})},tC=(r,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of JT(t))!$T.call(r,a)&&a!==e&&Oh(r,a,{get:()=>t[a],enumerable:!(i=QT(t,a))||i.enumerable});return r};var eC=r=>tC(Oh({},"__esModule",{value:!0}),r);var tN={};Ae(tN,{default:()=>$2,dispose:()=>J2,getInstanceByDom:()=>Q2,graphic:()=>K2,init:()=>X2,registerTheme:()=>j2,use:()=>q2});var Dd={};Ae(Dd,{Axis:()=>_o,ChartView:()=>Pt,ComponentModel:()=>ct,ComponentView:()=>At,List:()=>hr,Model:()=>wt,PRIORITY:()=>Vv,SeriesModel:()=>kt,color:()=>ql,connect:()=>aP,dataTool:()=>fP,dependencies:()=>FL,disConnect:()=>nP,disconnect:()=>US,dispose:()=>Wv,env:()=>tt,extendChartView:()=>DI,extendComponentModel:()=>wI,extendComponentView:()=>TI,extendSeriesModel:()=>CI,format:()=>wd,getCoordinateSystemDimensions:()=>sP,getInstanceByDom:()=>qs,getInstanceById:()=>oP,getMap:()=>uP,graphic:()=>sl,helper:()=>dd,init:()=>Hv,innerDrawElementOnCanvas:()=>ho,matrix:()=>jr,number:()=>Sd,parseGeoJSON:()=>Xf,parseGeoJson:()=>Xf,registerAction:()=>Fr,registerCoordinateSystem:()=>Xv,registerLayout:()=>qv,registerLoading:()=>Rf,registerLocale:()=>Bu,registerMap:()=>jv,registerPostInit:()=>Yv,registerPostUpdate:()=>Zv,registerPreprocessor:()=>Pf,registerProcessor:()=>If,registerTheme:()=>Ks,registerTransform:()=>Qv,registerUpdateLifecycle:()=>js,registerVisual:()=>vi,setCanvasCreator:()=>lP,setPlatformAPI:()=>Dl,throttle:()=>Ja,time:()=>bd,use:()=>zt,util:()=>Td,vector:()=>Be,version:()=>VL,zrUtil:()=>$,zrender:()=>nu});var Nh=function(r,t){return Nh=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,i){e.__proto__=i}||function(e,i){for(var a in i)Object.prototype.hasOwnProperty.call(i,a)&&(e[a]=i[a])},Nh(r,t)};function P(r,t){if(typeof t!="function"&&t!==null)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");Nh(r,t);function e(){this.constructor=r}r.prototype=t===null?Object.create(t):(e.prototype=t.prototype,new e)}var nu={};Ae(nu,{dispose:()=>ND,disposeAll:()=>kD,getElementSSRData:()=>UD,getInstance:()=>zD,init:()=>au,registerPainter:()=>Lc,registerSSRDataGetter:()=>Pc,version:()=>BD});var rC=(function(){function r(){this.firefox=!1,this.ie=!1,this.edge=!1,this.newEdge=!1,this.weChat=!1}return r})(),iC=(function(){function r(){this.browser=new rC,this.node=!1,this.wxa=!1,this.worker=!1,this.svgSupported=!1,this.touchEventsSupported=!1,this.pointerEventsSupported=!1,this.domSupported=!1,this.transformSupported=!1,this.transform3dSupported=!1,this.hasGlobalWindow=typeof window<"u"}return r})(),gi=new iC;typeof wx=="object"&&typeof wx.getSystemInfoSync=="function"?(gi.wxa=!0,gi.touchEventsSupported=!0):typeof document>"u"&&typeof self<"u"?gi.worker=!0:!gi.hasGlobalWindow||"Deno"in window?(gi.node=!0,gi.svgSupported=!0):aC(navigator.userAgent,gi);function aC(r,t){var e=t.browser,i=r.match(/Firefox\/([\d.]+)/),a=r.match(/MSIE\s([\d.]+)/)||r.match(/Trident\/.+?rv:(([\d.]+))/),n=r.match(/Edge?\/([\d.]+)/),o=/micromessenger/i.test(r);i&&(e.firefox=!0,e.version=i[1]),a&&(e.ie=!0,e.version=a[1]),n&&(e.edge=!0,e.version=n[1],e.newEdge=+n[1].split(".")[0]>18),o&&(e.weChat=!0),t.svgSupported=typeof SVGRect<"u",t.touchEventsSupported="ontouchstart"in window&&!e.ie&&!e.edge,t.pointerEventsSupported="onpointerdown"in window&&(e.edge||e.ie&&+e.version>=11),t.domSupported=typeof document<"u";var s=document.documentElement.style;t.transform3dSupported=(e.ie&&"transition"in s||e.edge||"WebKitCSSMatrix"in window&&"m11"in new WebKitCSSMatrix||"MozPerspective"in s)&&!("OTransition"in s),t.transformSupported=t.transform3dSupported||e.ie&&+e.version>=9}var tt=gi;var $={};Ae($,{HashMap:()=>ig,RADIAN_TO_DEGREE:()=>El,assert:()=>te,bind:()=>X,clone:()=>K,concatArray:()=>Gh,createCanvas:()=>mC,createHashMap:()=>Y,createObject:()=>Zr,curry:()=>lt,defaults:()=>q,disableUserSelect:()=>No,each:()=>T,eqNaN:()=>ea,extend:()=>N,filter:()=>Tt,find:()=>Bh,guid:()=>Po,hasOwn:()=>qt,indexOf:()=>at,inherits:()=>Io,isArray:()=>k,isArrayLike:()=>Ot,isBuiltInObject:()=>kh,isDom:()=>$i,isFunction:()=>G,isGradientObject:()=>Yr,isImagePatternObject:()=>Vh,isNumber:()=>et,isObject:()=>H,isPrimitive:()=>gn,isRegExp:()=>Fh,isString:()=>B,isStringSafe:()=>_n,isTypedArray:()=>Nt,keys:()=>pt,logError:()=>ta,map:()=>U,merge:()=>it,mergeAll:()=>dC,mixin:()=>Ut,noop:()=>Bt,normalizeCssArray:()=>Oo,reduce:()=>ce,retrieve:()=>Dr,retrieve2:()=>Q,retrieve3:()=>Mr,setAsPrimitive:()=>yi,slice:()=>Ro,trim:()=>ee});var Cl=12,nC="sans-serif",dr=Cl+"px "+nC,oC=20,sC=100,lC="007LLmW'55;N0500LLLLLLLLLL00NNNLzWW\\\\WQb\\0FWLg\\bWb\\WQ\\WrWWQ000CL5LLFLL0LL**F*gLLLL5F0LF\\FFF5.5N";function uC(r){var t={};if(typeof JSON>"u")return t;for(var e=0;e<r.length;e++){var i=String.fromCharCode(e+32),a=(r.charCodeAt(e)-oC)/sC;t[i]=a}return t}var fC=uC(lC),be={createCanvas:funcLine truncated
|
||||||
|
`),n=a.length;if(n===1)return ry(a[0],t,e,i);for(var o=new nt(0,0,0,0),s=0;s<a.length;s++){var l=ry(a[s],t,e,i);s===0?o.copy(l):o.union(l)}return o}function En(r,t,e){return e==="right"?r-=t:e==="center"&&(r-=t/2),r}function ya(r,t,e){return e==="middle"?r-=t/2:e==="bottom"&&(r-=t),r}function eu(r){return Le("\u56FD",r)}function er(r,t){return typeof r=="string"?r.lastIndexOf("%")>=0?parseFloat(r)/100*t:parseFloat(r):r}function _a(r,t,e){var i=t.position||"inside",a=t.distance!=null?t.distance:5,n=e.height,o=e.width,s=n/2,l=e.x,u=e.y,f="left",h="top";if(i instanceof Array)l+=er(i[0],e.width),u+=er(i[1],e.height),f=null,h=null;else switch(i){case"left":l-=a,u+=s,f="right",h="middle";break;case"right":l+=a+o,u+=s,h="middle";break;case"top":l+=o/2,u-=a,f="center",h="bottom";break;case"bottom":l+=o/2,u+=n+a,f="center";break;case"inside":l+=o/2,u+=s,f="center",h="middle";break;case"insideLeft":l+=a,u+=s,h="middle";break;case"insideRight":l+=o-a,u+=s,f="right",h="middle";break;case"insideTop":l+=o/2,u+=a,f="center";break;case"insideBottom":l+=o/2,u+=n-a,f="center",h="bottom";break;case"insideTopLeft":l+=a,u+=a;break;case"insideTopRight":l+=o-a,u+=a,f="right";break;case"insideBottomLeft":l+=a,u+=n-a,h="bottom";break;case"insideBottomRight":l+=o-a,u+=n-a,f="right",h="bottom";break}return r=r||{},r.x=l,r.y=u,r.align=f,r.verticalAlign=h,r}var Tc="__zr_normal__",Cc=ga.concat(["ignore"]),DD=ce(ga,function(r,t){return r[t]=!0,r},{ignore:!1}),Ln={},MD=new nt(0,0,0,0),Ac=(function(){function r(t){this.id=Po(),this.animators=[],this.currentStates=[],this.states={},this._init(t)}return r.prototype._init=function(t){this.attr(t)},r.prototype.drift=function(t,e,i){switch(this.draggable){case"horizontal":e=0;break;case"vertical":t=0;break}var a=this.transform;a||(a=this.transform=[1,0,0,1,0,0]),a[4]+=t,a[5]+=e,this.decomposeTransform(),this.markRedraw()},r.prototype.beforeUpdate=function(){},r.prototype.afterUpdate=function(){},r.prototype.update=function(){this.updateTransform(),this.__dirty&&this.updateInnerText()},r.prototype.updateInnerText=function(t){var e=this._textContent;if(e&&(!e.ignore||t)){this.textConfig||(this.textConfig={});var i=this.textConfig,a=i.local,n=e.innerTransformable,o=void 0,s=void 0,l=!1;n.parent=a?this:null;var u=!1;if(n.copyTransform(e),i.position!=null){var f=MD;i.layoutRect?f.copy(i.layoutRect):f.copy(this.getBoundingRect()),a||f.applyTransform(this.transform),this.calculateTextPosition?this.calculateTextPosition(Ln,i,f):_a(Ln,i,f),n.x=Ln.x,n.y=Ln.y,o=Ln.align,s=Ln.verticalAlign;var h=i.origin;if(h&&i.rotation!=null){var p=void 0,c=void 0;h==="center"?(p=f.width*.5,c=f.height*.5):(p=er(h[0],f.width),c=er(h[1],f.height)),u=!0,n.originX=-n.x+p+(a?0:f.x),n.originY=-n.y+c+(a?0:f.y)}}i.rotation!=null&&(n.rotation=i.rotation);var v=i.offset;v&&(n.x+=v[0],n.y+=v[1],u||(n.originX=-v[0],n.originY=-v[1]));var m=i.inside==null?typeof i.position=="string"&&i.position.indexOf("inside")>=0:i.inside,d=this._innerTextDefaultStyle||(this._innerTextDefaultStyle={}),g=void 0,y=void 0,_=void 0;m&&this.canBeInsideText()?(g=i.insideFill,y=i.insideStroke,(g==null||g==="auto")&&(g=this.getInsideTextFill()),(y==null||y==="auto")&&(y=this.getInsideTextStroke(g),_=!0)):(g=i.outsideFill,y=i.outsideStroke,(g==null||g==="auto")&&(g=this.getOutsideFill()),(y==null||y==="auto")&&(y=this.getOutsideStroke(g),_=!0)),g=g||"#000",(g!==d.fill||y!==d.stroke||_!==d.autoStroke||o!==d.align||s!==d.verticalAlign)&&(l=!0,d.fill=g,d.stroke=y,d.autoStroke=_,d.align=o,d.verticalAlign=s,e.setDefaultTextStyle(d)),e.__dirty|=Zt,l&&e.dirtyStyle(!0)}},r.prototype.canBeInsideText=function(){return!0},r.prototype.getInsideTextFill=function(){return"#fff"},r.prototype.getInsideTextStroke=function(t){return"#000"},r.prototype.getOutsideFill=function(){return this.__zr&&this.__zr.isDarkMode()?$o:Jo},r.prototype.getOutsideStroke=function(t){var e=this.__zr&&this.__zr.getBackgroundColor(),i=typeof e=="string"&&pe(e);i||(i=[255,255,255,1]);for(var a=i[3],n=this.__zr.isDarkMode(),o=0;o<3;o++)i[o]=i[o]*a+(n?0:255)*(1-a);return i[3]=1,Lr(i,"rgba")},r.prototype.traverse=function(t,e){},r.prototype.attrKV=function(t,e){t==="textConfig"?this.setTextConfig(e):t==="textContent"?this.setTextContent(e):t==="clipPath"?this.setClipPath(e):t==="extra"?(this.extra=this.extra||{},N(this.extra,e)):this[t]=e},r.prototype.hide=function(){this.ignore=!0,this.markRedraw()},r.prototype.show=function(){this.ignore=!1,this.markRedraw()},r.prototype.attr=function(t,e){if(typeof t=="string")this.attrKV(t,e);else if(H(t))for(var i=t,a=pt(i),n=0;n<a.length;n++){var o=a[n];this.attrKV(o,t[o])}return this.markRedraw(),this},r.prototype.saveCurrentToNormalState=function(t){this._innerSaveToNormal(t);for(var e=this._normalState,i=0;i<this.animators.length;i++){var a=this.animators[i],n=a.__fromStateTransition;if(!(a.getLoop()||n&&n!==Tc)){var o=a.targetName,s=o?e[o]:e;a.saveTo(s)}}},r.prototype._innerSaveToNormal=function(t){var e=this._normalState;e||(e=this._normalState={}),t.textC
Line truncated
|
||||||
|
`);n=Py(e,i,a,n);for(var s=!1,l={},u=0,f=o.length;u<f;u++)Iy(l,o[u],n),o[u]=l.textLine,s=s||l.isTruncated;r.text=o.join(`
|
||||||
|
`),r.isTruncated=s}function Py(r,t,e,i){i=i||{};var a=N({},i);a.font=t,e=Q(e,"..."),a.maxIterations=Q(i.maxIterations,2);var n=a.minChar=Q(i.minChar,0);a.cnCharWidth=Le("\u56FD",t);var o=a.ascCharWidth=Le("a",t);a.placeholder=Q(i.placeholder,"");for(var s=r=Math.max(0,r-1),l=0;l<n&&s>=o;l++)s-=o;var u=Le(e,t);return u>s&&(e="",u=0),s=r-u,a.ellipsis=e,a.ellipsisWidth=u,a.contentWidth=s,a.containerWidth=r,a}function Iy(r,t,e){var i=e.containerWidth,a=e.font,n=e.contentWidth;if(!i){r.textLine="",r.isTruncated=!1;return}var o=Le(t,a);if(o<=i){r.textLine=t,r.isTruncated=!1;return}for(var s=0;;s++){if(o<=n||s>=e.maxIterations){t+=e.ellipsis;break}var l=s===0?oM(t,n,e.ascCharWidth,e.cnCharWidth):o>0?Math.floor(t.length*n/o):0;t=t.substr(0,l),o=Le(t,a)}t===""&&(t=e.placeholder),r.textLine=t,r.isTruncated=!0}function oM(r,t,e,i){for(var a=0,n=0,o=r.length;n<o&&a<t;n++){var s=r.charCodeAt(n);a+=0<=s&&s<=127?e:i}return n}function Ry(r,t){r!=null&&(r+="");var e=t.overflow,i=t.padding,a=t.font,n=e==="truncate",o=eu(a),s=Q(t.lineHeight,o),l=!!t.backgroundColor,u=t.lineOverflow==="truncate",f=!1,h=t.width,p;h!=null&&(e==="break"||e==="breakAll")?p=r?Ny(r,t.font,h,e==="breakAll",0).lines:[]:p=r?r.split(`
|
||||||
|
`):[];var c=p.length*s,v=Q(t.height,c);if(c>v&&u){var m=Math.floor(v/s);f=f||p.length>m,p=p.slice(0,m)}if(r&&n&&h!=null)for(var d=Py(h,a,t.ellipsis,{minChar:t.truncateMinChar,placeholder:t.placeholder}),g={},y=0;y<p.length;y++)Iy(g,p[y],d),p[y]=g.textLine,f=f||g.isTruncated;for(var _=v,x=0,y=0;y<p.length;y++)x=Math.max(Le(p[y],a),x);h==null&&(h=x);var S=x;return i&&(_+=i[0]+i[2],S+=i[1]+i[3],h+=i[1]+i[3]),l&&(S=h),{lines:p,height:v,outerWidth:S,outerHeight:_,lineHeight:s,calculatedLineHeight:o,contentWidth:x,contentHeight:c,width:h,isTruncated:f}}var sM=(function(){function r(){}return r})(),Ey=(function(){function r(t){this.tokens=[],t&&(this.tokens=t)}return r})(),lM=(function(){function r(){this.width=0,this.height=0,this.contentWidth=0,this.contentHeight=0,this.outerWidth=0,this.outerHeight=0,this.lines=[],this.isTruncated=!1}return r})();function Oy(r,t){var e=new lM;if(r!=null&&(r+=""),!r)return e;for(var i=t.width,a=t.height,n=t.overflow,o=(n==="break"||n==="breakAll")&&i!=null?{width:i,accumWidth:0,breakAll:n==="breakAll"}:null,s=Vc.lastIndex=0,l;(l=Vc.exec(r))!=null;){var u=l.index;u>s&&Fc(e,r.substring(s,u),t,o),Fc(e,l[2],t,o,l[1]),s=Vc.lastIndex}s<r.length&&Fc(e,r.substring(s,r.length),t,o);var f=[],h=0,p=0,c=t.padding,v=n==="truncate",m=t.lineOverflow==="truncate",d={};function g(W,Z,J){W.width=Z,W.lineHeight=J,h+=J,p=Math.max(p,Z)}t:for(var y=0;y<e.lines.length;y++){for(var _=e.lines[y],x=0,S=0,b=0;b<_.tokens.length;b++){var w=_.tokens[b],C=w.styleName&&t.rich[w.styleName]||{},M=w.textPadding=C.padding,A=M?M[1]+M[3]:0,D=w.font=C.font||t.font;w.contentHeight=eu(D);var E=Q(C.height,w.contentHeight);if(w.innerHeight=E,M&&(E+=M[0]+M[2]),w.height=E,w.lineHeight=Mr(C.lineHeight,t.lineHeight,E),w.align=C&&C.align||t.align,w.verticalAlign=C&&C.verticalAlign||"middle",m&&a!=null&&h+w.lineHeight>a){var L=e.lines.length;b>0?(_.tokens=_.tokens.slice(0,b),g(_,S,x),e.lines=e.lines.slice(0,y+1)):e.lines=e.lines.slice(0,y),e.isTruncated=e.isTruncated||e.lines.length<L;break t}var I=C.width,R=I==null||I==="auto";if(typeof I=="string"&&I.charAt(I.length-1)==="%")w.percentWidth=I,f.push(w),w.contentWidth=Le(w.text,D);else{if(R){var O=C.backgroundColor,V=O&&O.image;V&&(V=Ay(V),zn(V)&&(w.width=Math.max(w.width,V.width*E/V.height)))}var z=v&&i!=null?i-S:null;z!=null&&z<w.width?!R||z<A?(w.text="",w.width=w.contentWidth=0):(Ly(d,w.text,z-A,D,t.ellipsis,{minChar:t.truncateMinChar}),w.text=d.text,e.isTruncated=e.isTruncated||d.isTruncated,w.width=w.contentWidth=Le(w.text,D)):w.contentWidth=Le(w.text,D)}w.width+=A,S+=w.width,C&&(x=Math.max(x,w.lineHeight))}g(_,S,x)}e.outerWidth=e.width=Q(i,p),e.outerHeight=e.height=Q(a,h),e.contentHeight=h,e.contentWidth=p,c&&(e.outerWidth+=c[1]+c[3],e.outerHeight+=c[0]+c[2]);for(var y=0;y<f.length;y++){var w=f[y],F=w.percentWidth;w.width=parseInt(F,10)/100*e.width}return e}function Fc(r,t,e,i,a){var n=t==="",o=a&&e.rich[a]||{},s=r.lines,l=o.font||e.font,u=!1,f,h;if(i){var p=o.padding,c=p?p[1]+p[3]:0;if(o.width!=null&&o.width!=="auto"){var v=er(o.width,i.width)+c;s.length>0&&v+i.accumWidth>i.width&&(f=t.split(`
|
||||||
|
`),u=!0),i.accumWidth=v}else{var m=Ny(t,l,i.width,i.breakAll,i.accumWidth);i.accumWidth=m.accumWidth+c,h=m.linesWidths,f=m.lines}}else f=t.split(`
|
||||||
|
`);for(var d=0;d<f.length;d++){var g=f[d],y=new sM;if(y.styleName=a,y.text=g,y.isLineHolder=!g&&!n,typeof o.width=="number"?y.width=o.width:y.width=h?h[d]:Le(g,l),!d&&!u){var _=(s[s.length-1]||(s[0]=new Ey)).tokens,x=_.length;x===1&&_[0].isLineHolder?_[0]=y:(g||!x||n)&&_.push(y)}else s.push(new Ey([y]))}}function uM(r){var t=r.charCodeAt(0);return t>=32&&t<=591||t>=880&&t<=4351||t>=4608&&t<=5119||t>=7680&&t<=8303}var fM=ce(",&?/;] ".split(""),function(r,t){return r[t]=!0,r},{});function hM(r){return uM(r)?!!fM[r]:!0}function Ny(r,t,e,i,a){for(var n=[],o=[],s="",l="",u=0,f=0,h=0;h<r.length;h++){var p=r.charAt(h);if(p===`
|
||||||
|
`){l&&(s+=l,f+=u),n.push(s),o.push(f),s="",l="",u=0,f=0;continue}var c=Le(p,t),v=i?!1:!hM(p);if(n.length?f+c>e:a+f+c>e){f?(s||l)&&(v?(s||(s=l,l="",u=0,f=u),n.push(s),o.push(f-u),l+=p,u+=c,s="",f=u):(l&&(s+=l,l="",u=0),n.push(s),o.push(f),s=p,f=c)):v?(n.push(l),o.push(u),l=p,u=c):(n.push(p),o.push(c));continue}f+=c,v?(l+=p,u+=c):(l&&(s+=l,l="",u=0),s+=p)}return!n.length&&!s&&(s=r,l="",u=0),l&&(s+=l),s&&(n.push(s),o.push(f)),n.length===1&&(f+=a),{accumWidth:f,lines:n,linesWidths:o}}var Yc="__zr_style_"+Math.round(Math.random()*10),Ir={shadowBlur:0,shadowOffsetX:0,shadowOffsetY:0,shadowColor:"#000",opacity:1,blend:"source-over"},Ta={style:{shadowBlur:!0,shadowOffsetX:!0,shadowOffsetY:!0,shadowColor:!0,opacity:!0}};Ir[Yc]=!0;var ky=["z","z2","invisible"],cM=["invisible"],pM=(function(r){P(t,r);function t(e){return r.call(this,e)||this}return t.prototype._init=function(e){for(var i=pt(e),a=0;a<i.length;a++){var n=i[a];n==="style"?this.useStyle(e[n]):r.prototype.attrKV.call(this,n,e[n])}this.style||this.useStyle({})},t.prototype.beforeBrush=function(){},t.prototype.afterBrush=function(){},t.prototype.innerBeforeBrush=function(){},t.prototype.innerAfterBrush=function(){},t.prototype.shouldBePainted=function(e,i,a,n){var o=this.transform;if(this.ignore||this.invisible||this.style.opacity===0||this.culling&&vM(this,e,i)||o&&!o[0]&&!o[3])return!1;if(a&&this.__clipPaths){for(var s=0;s<this.__clipPaths.length;++s)if(this.__clipPaths[s].isZeroArea())return!1}if(n&&this.parent)for(var l=this.parent;l;){if(l.ignore)return!1;l=l.parent}return!0},t.prototype.contain=function(e,i){return this.rectContain(e,i)},t.prototype.traverse=function(e,i){e.call(i,this)},t.prototype.rectContain=function(e,i){var a=this.transformCoordToLocal(e,i),n=this.getBoundingRect();return n.contain(a[0],a[1])},t.prototype.getPaintRect=function(){var e=this._paintRect;if(!this._paintRect||this.__dirty){var i=this.transform,a=this.getBoundingRect(),n=this.style,o=n.shadowBlur||0,s=n.shadowOffsetX||0,l=n.shadowOffsetY||0;e=this._paintRect||(this._paintRect=new nt(0,0,0,0)),i?nt.applyTransform(e,a,i):e.copy(a),(o||s||l)&&(e.width+=o*2+Math.abs(s),e.height+=o*2+Math.abs(l),e.x=Math.min(e.x,e.x+s-o),e.y=Math.min(e.y,e.y+l-o));var u=this.dirtyRectTolerance;e.isZero()||(e.x=Math.floor(e.x-u),e.y=Math.floor(e.y-u),e.width=Math.ceil(e.width+1+u*2),e.height=Math.ceil(e.height+1+u*2))}return e},t.prototype.setPrevPaintRect=function(e){e?(this._prevPaintRect=this._prevPaintRect||new nt(0,0,0,0),this._prevPaintRect.copy(e)):this._prevPaintRect=null},t.prototype.getPrevPaintRect=function(){return this._prevPaintRect},t.prototype.animateStyle=function(e){return this.animate("style",e)},t.prototype.updateDuringAnimation=function(e){e==="style"?this.dirtyStyle():this.markRedraw()},t.prototype.attrKV=function(e,i){e!=="style"?r.prototype.attrKV.call(this,e,i):this.style?this.setStyle(i):this.useStyle(i)},t.prototype.setStyle=function(e,i){return typeof e=="string"?this.style[e]=i:N(this.style,e),this.dirtyStyle(),this},t.prototype.dirtyStyle=function(e){e||this.markRedraw(),this.__dirty|=ua,this._rect&&(this._rect=null)},t.prototype.dirty=function(){this.dirtyStyle()},t.prototype.styleChanged=function(){return!!(this.__dirty&ua)},t.prototype.styleUpdated=function(){this.__dirty&=~ua},t.prototype.createStyle=function(e){return Zr(Ir,e)},t.prototype.useStyle=function(e){e[Yc]||(e=this.createStyle(e)),this.__inHover?this.__hoverStyle=e:this.style=e,this.dirtyStyle()},t.prototype.isStyleObject=function(e){return e[Yc]},t.prototype._innerSaveToNormal=function(e){r.prototype._innerSaveToNormal.call(this,e);var i=this._normalState;e.style&&!i.style&&(i.style=this._mergeStyle(this.createStyle(),this.style)),this._savePrimaryToNormal(e,i,ky)},t.prototype._applyStateObj=function(e,i,a,n,o,s){r.prototype._applyStateObj.call(this,e,i,a,n,o,s);var l=!(i&&n),u;if(i&&i.style?o?n?u=i.style:(u=this._mergeStyle(this.createStyle(),a.style),this._mergeStyle(u,i.style)):(u=this._mergeStyle(this.createStyle(),n?this.style:a.style),this._mergeStyle(u,i.style)):l&&(u=a.style),u)if(o){var f=this.style;if(this.style=this.createStyle(l?{}:f),l)for(var h=pt(f),p=0;p<h.length;p++){var c=h[p];c in u&&(u[c]=u[c],this.style[c]=f[c])}for(var v=pt(u),p=0;p<v.length;p++){var c=v[p];this.style[c]=this.style[c]}this._transitionState(e,{style:u},s,this.getAnimationStyleProps())}else this.useStyle(u);for(var m=this.__inHover?cM:ky,p=0;p<m.length;p++){var c=m[p];i&&i[c]!=null?this[c]=i[c]:l&&a[c]!=null&&(this[c]=a[c])}},t.prototype._mergeStates=function(e){for(var i=r.prototype._mergeStates.call(this,e),a,n=0;n<e.length;n++){var o=e[n];o.style&&(a=a||{},this._mergeStyle(a,o.style))}return a&&(i.style=a),i},t.prototype._mergeStyle=function(e,i){return N(e,i),e},t.prototype.getAnimationStyleProps=function(){return Ta},t.initDefaultProps=(function(){var e=t.prototype;e.type="displayable",e.invisible=!1,e.z=0,e.z2=0,e.zlevel=0,e.culling=!1,e.cursor="pointer",e.rectHover=!1,e.incremental=!1,e._rect=null,e.dir
Line truncated
|
||||||
|
yyyy`);var i=re(t),a=e?"getUTC":"get",n=i[a+"FullYear"](),o=i[a+"Month"]()+1,s=i[a+"Date"](),l=i[a+"Hours"](),u=i[a+"Minutes"](),f=i[a+"Seconds"](),h=i[a+"Milliseconds"]();return r=r.replace("MM",ye(o,2)).replace("M",o).replace("yyyy",n).replace("yy",ye(n%100+"",2)).replace("dd",ye(s,2)).replace("d",s).replace("hh",ye(l,2)).replace("h",l).replace("mm",ye(u,2)).replace("m",u).replace("ss",ye(f,2)).replace("s",f).replace("SSS",ye(h,3)),r}function A_(r){return r&&r.charAt(0).toUpperCase()+r.substr(1)}function Sr(r,t){return t=t||"transparent",B(r)?r:H(r)&&r.colorStops&&(r.colorStops[0]||{}).color||t}function jp(r,t){if(t==="_blank"||t==="blank"){var e=window.open();e.opener=null,e.location.href=r}else window.open(r,t)}var qu=T,HA=["left","right","top","bottom","width","height"],Xu=[["width","left","right"],["height","top","bottom"]];function Qp(r,t,e,i,a){var n=0,o=0;i==null&&(i=1/0),a==null&&(a=1/0);var s=0;t.eachChild(function(l,u){var f=l.getBoundingRect(),h=t.childAt(u+1),p=h&&h.getBoundingRect(),c,v;if(r==="horizontal"){var m=f.width+(p?-p.x+f.x:0);c=n+m,c>i||l.newline?(n=0,c=m,o+=s+e,s=f.height):s=Math.max(s,f.height)}else{var d=f.height+(p?-p.y+f.y:0);v=o+d,v>a||l.newline?(n+=s+e,o=0,v=d,s=f.width):s=Math.max(s,f.width)}l.newline||(l.x=n,l.y=o,l.markRedraw(),r==="horizontal"?n=c+e:o=v+e)})}var Xa=Qp,TV=lt(Qp,"vertical"),CV=lt(Qp,"horizontal");function De(r,t,e){e=Ur(e||0);var i=t.width,a=t.height,n=j(r.left,i),o=j(r.top,a),s=j(r.right,i),l=j(r.bottom,a),u=j(r.width,i),f=j(r.height,a),h=e[2]+e[0],p=e[1]+e[3],c=r.aspect;switch(isNaN(u)&&(u=i-s-p-n),isNaN(f)&&(f=a-l-h-o),c!=null&&(isNaN(u)&&isNaN(f)&&(c>i/a?u=i*.8:f=a*.8),isNaN(u)&&(u=c*f),isNaN(f)&&(f=u/c)),isNaN(n)&&(n=i-s-u-p),isNaN(o)&&(o=a-l-f-h),r.left||r.right){case"center":n=i/2-u/2-e[3];break;case"right":n=i-u-p;break}switch(r.top||r.bottom){case"middle":case"center":o=a/2-f/2-e[0];break;case"bottom":o=a-f-h;break}n=n||0,o=o||0,isNaN(u)&&(u=i-p-n-(s||0)),isNaN(f)&&(f=a-h-o-(l||0));var v=new nt(n+e[3],o+e[0],u,f);return v.margin=e,v}function Ni(r){var t=r.layoutMode||r.constructor.layoutMode;return H(t)?t:t?{type:t}:null}function Br(r,t,e){var i=e&&e.ignoreSize;!k(i)&&(i=[i,i]);var a=o(Xu[0],0),n=o(Xu[1],1);u(Xu[0],r,a),u(Xu[1],r,n);function o(f,h){var p={},c=0,v={},m=0,d=2;if(qu(f,function(_){v[_]=r[_]}),qu(f,function(_){s(t,_)&&(p[_]=v[_]=t[_]),l(p,_)&&c++,l(v,_)&&m++}),i[h])return l(t,f[1])?v[f[2]]=null:l(t,f[2])&&(v[f[1]]=null),v;if(m===d||!c)return v;if(c>=d)return p;for(var g=0;g<f.length;g++){var y=f[g];if(!s(p,y)&&s(r,y)){p[y]=r[y];break}}return p}function s(f,h){return f.hasOwnProperty(h)}function l(f,h){return f[h]!=null&&f[h]!=="auto"}function u(f,h,p){qu(f,function(c){h[c]=p[c]})}}function Vr(r){return WA({},r)}function WA(r,t){return t&&r&&qu(HA,function(e){t.hasOwnProperty(e)&&(r[e]=t[e])}),r}var YA=ft(),ro=(function(r){P(t,r);function t(e,i,a){var n=r.call(this,e,i,a)||this;return n.uid=Ri("ec_cpt_model"),n}return t.prototype.init=function(e,i,a){this.mergeDefaultAndTheme(e,a)},t.prototype.mergeDefaultAndTheme=function(e,i){var a=Ni(this),n=a?Vr(e):{},o=i.getTheme();it(e,o.get(this.mainType)),it(e,this.getDefaultOption()),a&&Br(e,n,a)},t.prototype.mergeOption=function(e,i){it(this.option,e,!0);var a=Ni(this);a&&Br(this.option,e,a)},t.prototype.optionUpdated=function(e,i){},t.prototype.getDefaultOption=function(){var e=this.constructor;if(!Ty(e))return e.defaultOption;var i=YA(this);if(!i.defaultOption){for(var a=[],n=e;n;){var o=n.prototype.defaultOption;o&&a.push(o),n=n.superClass}for(var s={},l=a.length-1;l>=0;l--)s=it(s,a[l],!0);i.defaultOption=s}return i.defaultOption},t.prototype.getReferringComponents=function(e,i){var a=e+"Index",n=e+"Id";return Ti(this.ecModel,e,{index:this.get(a,!0),id:this.get(n,!0)},i)},t.prototype.getBoxLayoutParams=function(){var e=this;return{left:e.get("left"),top:e.get("top"),right:e.get("right"),bottom:e.get("bottom"),width:e.get("width"),height:e.get("height")}},t.prototype.getZLevelKey=function(){return""},t.prototype.setZLevel=function(e){this.option.zlevel=e},t.protoInitialize=(function(){var e=t.prototype;e.type="component",e.id="",e.name="",e.mainType="",e.subType="",e.componentIndex=0})(),t})(wt);fu(ro,wt);Di(ro);v_(ro);d_(ro,ZA);function ZA(r){var t=[];return T(ro.getClassesByMainType(r),function(e){t=t.concat(e.dependencies||e.prototype.dependencies||[])}),t=U(t,function(e){return Pe(e).main}),r!=="dataset"&&at(t,"dataset")<=0&&t.unshift("dataset"),t}var ct=ro;var E_="";typeof navigator<"u"&&(E_=navigator.platform||"");var io="rgba(0, 0, 0, 0.2)",L_={darkMode:"auto",colorBy:"series",color:["#5470c6","#91cc75","#fac858","#ee6666","#73c0de","#3ba272","#fc8452","#9a60b4","#ea7ccc"],gradientColor:["#f6efa6","#d88273","#bf444c"],aria:{decal:{decals:[{color:io,dashArrayX:[1,0],dashArrayY:[2,5],symbolSize:1,rotation:Math.PI/6},{color:io,symbol:"circle",dashArrayX:[[8,8],[0,8,8,0]],dashArrayY:[6,0],symbolSize:.8},{color:io,dashArrayX:[1,0],dashArrayY:[4,3],rotation:-Math.PI/4},{color:io,dashArrayX:
Line truncated
|
||||||
|
`,`
|
||||||
|
|
||||||
|
`,`
|
||||||
|
|
||||||
|
|
||||||
|
`];function Ze(r,t){return t.type=r,t}function dv(r){return r.type==="section"}function gx(r){return dv(r)?VE:FE}function yx(r){if(dv(r)){var t=0,e=r.blocks.length,i=e>1||e>0&&!r.noHeader;return T(r.blocks,function(a){var n=yx(a);n>=t&&(t=n+ +(i&&(!n||dv(a)&&!a.noHeader)))}),t}return 0}function VE(r,t,e,i){var a=t.noHeader,n=GE(yx(t)),o=[],s=t.blocks||[];te(!s||k(s)),s=s||[];var l=r.orderMode;if(t.sortBlocks&&l){s=s.slice();var u={valueAsc:"asc",valueDesc:"desc"};if(qt(u,l)){var f=new sf(u[l],null);s.sort(function(m,d){return f.evaluate(m.sortParam,d.sortParam)})}else l==="seriesDesc"&&s.reverse()}T(s,function(m,d){var g=t.valueFormatter,y=gx(m)(g?N(N({},r),{valueFormatter:g}):r,m,d>0?n.html:0,i);y!=null&&o.push(y)});var h=r.renderMode==="richText"?o.join(n.richText):mv(i,o.join(""),a?e:n.html);if(a)return h;var p=Wu(t.header,"ordinal",r.useUTC),c=mx(i,r.renderMode).nameStyle,v=dx(i);return r.renderMode==="richText"?_x(r,p,c)+n.richText+h:mv(i,'<div style="'+c+";"+v+';">'+jt(p)+"</div>"+h,e)}function FE(r,t,e,i){var a=r.renderMode,n=t.noName,o=t.noValue,s=!t.markerType,l=t.name,u=r.useUTC,f=t.valueFormatter||r.valueFormatter||function(x){return x=k(x)?x:[x],U(x,function(S,b){return Wu(S,k(c)?c[b]:c,u)})};if(!(n&&o)){var h=s?"":r.markupStyleCreator.makeTooltipMarker(t.markerType,t.markerColor||"#333",a),p=n?"":Wu(l,"ordinal",u),c=t.valueType,v=o?[]:f(t.value,t.dataIndex),m=!s||!n,d=!s&&n,g=mx(i,a),y=g.nameStyle,_=g.valueStyle;return a==="richText"?(s?"":h)+(n?"":_x(r,p,y))+(o?"":YE(r,v,m,d,_)):mv(i,(s?"":h)+(n?"":HE(p,!s,y))+(o?"":WE(v,m,d,_)),e)}}function gv(r,t,e,i,a,n){if(r){var o=gx(r),s={useUTC:a,renderMode:e,orderMode:i,markupStyleCreator:t,valueFormatter:r.valueFormatter};return o(s,r,0,n)}}function GE(r){return{html:UE[r],richText:BE[r]}}function mv(r,t,e){var i='<div style="clear:both"></div>',a="margin: "+e+"px 0 0",n=dx(r);return'<div style="'+a+";"+n+';">'+t+i+"</div>"}function HE(r,t,e){var i=t?"margin-left:2px":"";return'<span style="'+e+";"+i+'">'+jt(r)+"</span>"}function WE(r,t,e,i){var a=e?"10px":"20px",n=t?"float:right;margin-left:"+a:"";return r=k(r)?r:[r],'<span style="'+n+";"+i+'">'+U(r,function(o){return jt(o)}).join(" ")+"</span>"}function _x(r,t,e){return r.markupStyleCreator.wrapRichTextStyle(t,e)}function YE(r,t,e,i,a){var n=[a],o=i?10:20;return e&&n.push({padding:[0,0,0,o],align:"right"}),r.markupStyleCreator.wrapRichTextStyle(k(t)?t.join(" "):t,n)}function hf(r,t){var e=r.getData().getItemVisual(t,"style"),i=e[r.visualDrawType];return Sr(i)}function cf(r,t){var e=r.get("padding");return e??(t==="richText"?[8,10]:10)}var pf=(function(){function r(){this.richTextStyles={},this._nextStyleNameId=su()}return r.prototype._generateStyleName=function(){return"__EC_aUTo_"+this._nextStyleNameId++},r.prototype.makeTooltipMarker=function(t,e,i){var a=i==="richText"?this._generateStyleName():null,n=Yu({color:e,type:t,renderMode:i,markerId:a});return B(n)?n:(this.richTextStyles[a]=n.style,n.content)},r.prototype.wrapRichTextStyle=function(t,e){var i={};k(e)?T(e,function(n){return N(i,n)}):N(i,e);var a=this._generateStyleName();return this.richTextStyles[a]=i,"{"+a+"|"+t+"}"},r})();function xx(r){var t=r.series,e=r.dataIndex,i=r.multipleSeries,a=t.getData(),n=a.mapDimensionsAll("defaultedTooltip"),o=n.length,s=t.getRawValue(e),l=k(s),u=hf(t,e),f,h,p,c;if(o>1||l&&!o){var v=ZE(s,t,e,n,u);f=v.inlineValues,h=v.inlineValueTypes,p=v.blocks,c=v.inlineValues[0]}else if(o){var m=a.getDimensionInfo(n[0]);c=f=ci(a,e,n[0]),h=m.type}else c=f=l?s[0]:s;var d=Nn(t),g=d&&t.name||"",y=a.getName(e),_=i?g:y;return Ze("section",{header:g,noHeader:i||!d,sortParam:c,blocks:[Ze("nameValue",{markerType:"item",markerColor:u,name:_,noName:!ee(_),value:f,valueType:h,dataIndex:e})].concat(p||[])})}function ZE(r,t,e,i,a){var n=t.getData(),o=ce(r,function(h,p,c){var v=n.getDimensionInfo(c);return h=h||v&&v.tooltip!==!1&&v.displayName!=null},!1),s=[],l=[],u=[];i.length?T(i,function(h){f(ci(n,e,h),h)}):T(r,f);function f(h,p){var c=n.getDimensionInfo(p);!c||c.otherDims.tooltip===!1||(o?u.push(Ze("nameValue",{markerType:"subItem",markerColor:a,name:c.displayName,value:h,valueType:c.type})):(s.push(h),l.push(c.type)))}return{inlineValues:s,inlineValueTypes:l,blocks:u}}var zi=ft();function vf(r,t){return r.getName(t)||r.getId(t)}var XE="__universalTransitionEnabled",df=(function(r){P(t,r);function t(){var e=r!==null&&r.apply(this,arguments)||this;return e._selectedDataIndicesMap={},e}return t.prototype.init=function(e,i,a){this.seriesIndex=this.componentIndex,this.dataTask=ki({count:KE,reset:jE}),this.dataTask.context={model:this},this.mergeDefaultAndTheme(e,a);var n=zi(this).sourceManager=new ff(this);n.prepareSource();var o=this.getInitialData(e,a);bx(o,this),this.dataTask.context.data=o,zi(this).dataBeforeProcessed=o,Sx(this),this._initSelectedMapFromData(o)},t.prototype.mergeDefaultAndTheme=function(e,i){var a=Ni(this),n=a?Vr(e):{},o=this.subType;ct.hasClass(o)&&(o+="Series"),it(e,i.getTheme().get(this.subType)),it
Line truncated
|
||||||
|
|
||||||
|
`:"<br/>",g=h.join(d);this._showOrMove(s,function(){this._updateContentNotChangedOnAxis(e,u)?this._updatePosition(s,c,o[0],o[1],this._tooltipContent,u):this._showTooltipContent(s,g,u,Math.random()+"",o[0],o[1],c,null,p)})},t.prototype._showSeriesItemTooltip=function(e,i,a){var n=this._ecModel,o=ot(i),s=o.seriesIndex,l=n.getSeriesByIndex(s),u=o.dataModel||l,f=o.dataIndex,h=o.dataType,p=u.getData(h),c=this._renderMode,v=e.positionDefault,m=gl([p.getItemModel(f),u,l&&(l.coordinateSystem||{}).model],this._tooltipModel,v?{position:v}:null),d=m.get("trigger");if(!(d!=null&&d!=="item")){var g=u.getDataParams(f,h),y=new pf;g.marker=y.makeTooltipMarker("item",Sr(g.color),c);var _=fv(u.formatTooltip(f,!1,h)),x=m.get("order"),S=m.get("valueFormatter"),b=_.frag,w=b?gv(S?N({valueFormatter:S},b):b,y,c,x,n.get("useUTC"),m.get("textStyle")):_.text,C="item_"+u.name+"_"+f;this._showOrMove(m,function(){this._showTooltipContent(m,w,g,C,e.offsetX,e.offsetY,e.position,e.target,y)}),a({type:"showTip",dataIndexInside:f,dataIndex:p.getRawIndex(f),seriesIndex:s,from:this.uid})}},t.prototype._showComponentItemTooltip=function(e,i,a){var n=this._renderMode==="html",o=ot(i),s=o.tooltipConfig,l=s.option||{},u=l.encodeHTMLContent;if(B(l)){var f=l;l={content:f,formatter:f},u=!0}u&&n&&l.content&&(l=K(l),l.content=jt(l.content));var h=[l],p=this._ecModel.getComponent(o.componentMainType,o.componentIndex);p&&h.push(p),h.push({formatter:l.content});var c=e.positionDefault,v=gl(h,this._tooltipModel,c?{position:c}:null),m=v.get("content"),d=Math.random()+"",g=new pf;this._showOrMove(v,function(){var y=K(v.get("formatterParams")||{});this._showTooltipContent(v,m,y,d,e.offsetX,e.offsetY,e.position,i,g)}),a({type:"showTip",from:this.uid})},t.prototype._showTooltipContent=function(e,i,a,n,o,s,l,u,f){if(this._ticket="",!(!e.get("showContent")||!e.get("show"))){var h=this._tooltipContent;h.setEnterable(e.get("enterable"));var p=e.get("formatter");l=l||e.get("position");var c=i,v=this._getNearestPoint([o,s],a,e.get("trigger"),e.get("borderColor")),m=v.color;if(p)if(B(p)){var d=e.ecModel.get("useUTC"),g=k(a)?a[0]:a,y=g&&g.axisType&&g.axisType.indexOf("time")>=0;c=p,y&&(c=ui(g.axisValue,c,d)),c=eo(c,a,!0)}else if(G(p)){var _=X(function(x,S){x===this._ticket&&(h.setContent(S,f,e,m,l),this._updatePosition(e,l,o,s,h,a,u))},this);this._ticket=n,c=p(a,n,_)}else c=p;h.setContent(c,f,e,m,l),h.show(e,m),this._updatePosition(e,l,o,s,h,a,u)}},t.prototype._getNearestPoint=function(e,i,a,n){if(a==="axis"||k(i))return{color:n||(this._renderMode==="html"?"#fff":"none")};if(!k(i))return{color:n||i.color||i.borderColor}},t.prototype._updatePosition=function(e,i,a,n,o,s,l){var u=this._api.getWidth(),f=this._api.getHeight();i=i||e.get("position");var h=o.getSize(),p=e.get("align"),c=e.get("verticalAlign"),v=l&&l.getBoundingRect().clone();if(l&&v.applyTransform(l.transform),G(i)&&(i=i([a,n],s,o.el,v,{viewSize:[u,f],contentSize:h.slice()})),k(i))a=j(i[0],u),n=j(i[1],f);else if(H(i)){var m=i;m.width=h[0],m.height=h[1];var d=De(m,{width:u,height:f});a=d.x,n=d.y,p=null,c=null}else if(B(i)&&l){var g=XO(i,v,h,e.get("borderWidth"));a=g[0],n=g[1]}else{var g=YO(a,n,o,u,f,p?null:20,c?null:20);a=g[0],n=g[1]}if(p&&(a-=sT(p)?h[0]/2:p==="right"?h[0]:0),c&&(n-=sT(c)?h[1]/2:c==="bottom"?h[1]:0),_h(e)){var g=ZO(a,n,o,u,f);a=g[0],n=g[1]}o.moveTo(a,n)},t.prototype._updateContentNotChangedOnAxis=function(e,i){var a=this._lastDataByCoordSys,n=this._cbParamsList,o=!!a&&a.length===e.length;return o&&T(a,function(s,l){var u=s.dataByAxis||[],f=e[l]||{},h=f.dataByAxis||[];o=o&&u.length===h.length,o&&T(u,function(p,c){var v=h[c]||{},m=p.seriesDataIndices||[],d=v.seriesDataIndices||[];o=o&&p.value===v.value&&p.axisType===v.axisType&&p.axisId===v.axisId&&m.length===d.length,o&&T(m,function(g,y){var _=d[y];o=o&&g.seriesIndex===_.seriesIndex&&g.dataIndex===_.dataIndex}),n&&T(p.seriesDataIndices,function(g){var y=g.seriesIndex,_=i[y],x=n[y];_&&x&&x.data!==_.data&&(o=!1)})})}),this._lastDataByCoordSys=e,this._cbParamsList=i,!!o},t.prototype._hide=function(e){this._lastDataByCoordSys=null,e({type:"hideTip",from:this.uid})},t.prototype.dispose=function(e,i){tt.node||!i.getDom()||($a(this,"_updatePosition"),this._tooltipContent.dispose(),vl("itemTooltip",i))},t.type="tooltip",t})(At);function gl(r,t,e){var i=t.ecModel,a;e?(a=new wt(e,i,i),a=new wt(t.option,a,i)):a=t;for(var n=r.length-1;n>=0;n--){var o=r[n];o&&(o instanceof wt&&(o=o.get("tooltip",!0)),B(o)&&(o={formatter:o}),o&&(a=new wt(o,a,i)))}return a}function oT(r,t){return r.dispatchAction||X(t.dispatchAction,t)}function YO(r,t,e,i,a,n,o){var s=e.getSize(),l=s[0],u=s[1];return n!=null&&(r+l+n+2>i?r-=l+n:r+=n),o!=null&&(t+u+o>a?t-=u+o:t+=o),[r,t]}function ZO(r,t,e,i,a){var n=e.getSize(),o=n[0],s=n[1];return r=Math.min(r+o,i)-o,t=Math.min(t+s,a)-s,r=Math.max(r,0),t=Math.max(t,0),[r,t]}function XO(r,t,e,i){var a=e[0],n=e[1],o=Math.ceil(Math.SQRT2*i)+8,s=0,l=0,u=t.width,f=t.height;switch(r){case"inside":s=t.x+u/2-a/2,l=t.y+f/2-n/2;break;case"top":s=t.x+u
Line truncated
|
||||||
|
`)){var d=new Ah;d.newline=!0,u.add(d);return}var g=a.getSeriesByName(m)[0];if(!f.get(m))if(g){var y=g.getData(),_=y.getVisual("legendLineStyle")||{},x=y.getVisual("legendIcon"),S=y.getVisual("style"),b=this._createItem(g,m,v,c,i,e,_,S,x,h,n);b.on("click",Ao(gT,m,null,n,p)).on("mouseover",Ao(Nm,g.name,null,n,p)).on("mouseout",Ao(km,g.name,null,n,p)),a.ssr&&b.eachChild(function(w){var C=ot(w);C.seriesIndex=g.seriesIndex,C.dataIndex=v,C.ssrType="legend"}),f.set(m,!0)}else a.eachRawSeries(function(w){if(!f.get(m)&&w.legendVisualProvider){var C=w.legendVisualProvider;if(!C.containName(m))return;var M=C.indexOfName(m),A=C.getItemVisual(M,"style"),D=C.getItemVisual(M,"legendIcon"),E=pe(A.fill);E&&E[3]===0&&(E[3]=.2,A=N(N({},A),{fill:Lr(E,"rgba")}));var L=this._createItem(w,m,v,c,i,e,{},A,D,h,n);L.on("click",Ao(gT,null,m,n,p)).on("mouseover",Ao(Nm,null,m,n,p)).on("mouseout",Ao(km,null,m,n,p)),a.ssr&&L.eachChild(function(I){var R=ot(I);R.seriesIndex=w.seriesIndex,R.dataIndex=v,R.ssrType="legend"}),f.set(m,!0)}},this)},this),o&&this._createSelector(o,i,n,s,l)},t.prototype._createSelector=function(e,i,a,n,o){var s=this.getSelectorGroup();Om(e,function(u){var f=u.type,h=new yt({style:{x:0,y:0,align:"center",verticalAlign:"middle"},onclick:function(){a.dispatchAction({type:f==="all"?"legendAllSelect":"legendInverseSelect",legendId:i.id})}});s.add(h);var p=i.getModel("selectorLabel"),c=i.getModel(["emphasis","selectorLabel"]);Re(h,{normal:p,emphasis:c},{defaultText:u.title}),Ii(h)})},t.prototype._createItem=function(e,i,a,n,o,s,l,u,f,h,p){var c=e.visualDrawType,v=o.get("itemWidth"),m=o.get("itemHeight"),d=o.isSelected(i),g=n.get("symbolRotate"),y=n.get("symbolKeepAspect"),_=n.get("icon");f=_||f||"roundRect";var x=c2(f,n,l,u,c,d,p),S=new Ah,b=n.getModel("textStyle");if(G(e.getLegendIcon)&&(!_||_==="inherit"))S.add(e.getLegendIcon({itemWidth:v,itemHeight:m,icon:f,iconRotate:g,itemStyle:x.itemStyle,lineStyle:x.lineStyle,symbolKeepAspect:y}));else{var w=_==="inherit"&&e.getData().getVisual("symbol")?g==="inherit"?e.getData().getVisual("symbolRotate"):g:0;S.add(p2({itemWidth:v,itemHeight:m,icon:f,iconRotate:w,itemStyle:x.itemStyle,lineStyle:x.lineStyle,symbolKeepAspect:y}))}var C=s==="left"?v+5:-5,M=s,A=o.get("formatter"),D=i;B(A)&&A?D=A.replace("{name}",i??""):G(A)&&(D=A(i));var E=d?b.getTextColor():n.get("inactiveColor");S.add(new yt({style:Wt(b,{text:D,x:C,y:m/2,fill:E,align:M,verticalAlign:"middle"},{inheritColor:E})}));var L=new mt({shape:S.getBoundingRect(),style:{fill:"transparent"}}),I=n.getModel("tooltip");return I.get("show")&&jn({el:L,componentModel:o,itemName:i,itemTooltipOption:I.option}),S.add(L),S.eachChild(function(R){R.silent=!0}),L.silent=!h,this.getContentGroup().add(S),Ii(S),S.__legendDataIndex=a,S},t.prototype.layoutInner=function(e,i,a,n,o,s){var l=this.getContentGroup(),u=this.getSelectorGroup();Xa(e.get("orient"),l,e.get("itemGap"),a.width,a.height);var f=l.getBoundingRect(),h=[-f.x,-f.y];if(u.markRedraw(),l.markRedraw(),o){Xa("horizontal",u,e.get("selectorItemGap",!0));var p=u.getBoundingRect(),c=[-p.x,-p.y],v=e.get("selectorButtonGap",!0),m=e.getOrient().index,d=m===0?"width":"height",g=m===0?"height":"width",y=m===0?"y":"x";s==="end"?c[m]+=f[d]+v:h[m]+=p[d]+v,c[1-m]+=f[g]/2-p[g]/2,u.x=c[0],u.y=c[1],l.x=h[0],l.y=h[1];var _={x:0,y:0};return _[d]=f[d]+v+p[d],_[g]=Math.max(f[g],p[g]),_[y]=Math.min(0,p[y]+c[1-m]),_}else return l.x=h[0],l.y=h[1],this.group.getBoundingRect()},t.prototype.remove=function(){this.getContentGroup().removeAll(),this._isFirstRender=!0},t.type="legend.plain",t})(At);function c2(r,t,e,i,a,n,o){function s(d,g){d.lineWidth==="auto"&&(d.lineWidth=g.lineWidth>0?2:0),Om(d,function(y,_){d[_]==="inherit"&&(d[_]=g[_])})}var l=t.getModel("itemStyle"),u=l.getItemStyle(),f=r.lastIndexOf("empty",0)===0?"fill":"stroke",h=l.getShallow("decal");u.decal=!h||h==="inherit"?i.decal:Ws(h,o),u.fill==="inherit"&&(u.fill=i[a]),u.stroke==="inherit"&&(u.stroke=i[f]),u.opacity==="inherit"&&(u.opacity=(a==="fill"?i:e).opacity),s(u,i);var p=t.getModel("lineStyle"),c=p.getLineStyle();if(s(c,e),u.fill==="auto"&&(u.fill=i.fill),u.stroke==="auto"&&(u.stroke=i.fill),c.stroke==="auto"&&(c.stroke=i.fill),!n){var v=t.get("inactiveBorderWidth"),m=u[f];u.lineWidth=v==="auto"?i.lineWidth>0&&m?2:0:u.lineWidth,u.fill=t.get("inactiveColor"),u.stroke=t.get("inactiveBorderColor"),c.stroke=p.get("inactiveColor"),c.lineWidth=p.get("inactiveWidth")}return{itemStyle:u,lineStyle:c}}function p2(r){var t=r.icon||"roundRect",e=It(t,0,0,r.itemWidth,r.itemHeight,r.itemStyle.fill,r.symbolKeepAspect);return e.setStyle(r.itemStyle),e.rotation=(r.iconRotate||0)*Math.PI/180,e.setOrigin([r.itemWidth/2,r.itemHeight/2]),t.indexOf("empty")>-1&&(e.style.stroke=e.style.fill,e.style.fill="#fff",e.style.lineWidth=2),e}function gT(r,t,e,i){km(r,t,e,i),e.dispatchAction({type:"legendToggleSelect",name:r??t}),Nm(r,t,e,i)}function yT(r){for(var t=r.getZr().storage.getDisplayList(),e,i=0,a=t.length;i<a&&!(e=t[i].states.emphasis);)i++;return e&&e.hove
Line truncated
|
||||||
|
`||a==="")){var n=r.isSelected(a);qt(e,a)?e[a]=e[a]&&n:e[a]=n}}),e}function xT(r){r.registerAction("legendToggleSelect","legendselectchanged",lt(bl,"toggleSelected")),r.registerAction("legendAllSelect","legendselectall",lt(bl,"allSelect")),r.registerAction("legendInverseSelect","legendinverseselect",lt(bl,"inverseSelect")),r.registerAction("legendSelect","legendselected",lt(bl,"select")),r.registerAction("legendUnSelect","legendunselected",lt(bl,"unSelect"))}function Lh(r){r.registerComponentModel(Sl),r.registerComponentView(Eh),r.registerProcessor(r.PRIORITY.PROCESSOR.SERIES_FILTER,zm),r.registerSubTypeDefaulter("legend",function(){return"plain"}),xT(r)}var v2=(function(r){P(t,r);function t(){var e=r!==null&&r.apply(this,arguments)||this;return e.type=t.type,e}return t.prototype.setScrollDataIndex=function(e){this.option.scrollDataIndex=e},t.prototype.init=function(e,i,a){var n=Vr(e);r.prototype.init.call(this,e,i,a),ST(this,e,n)},t.prototype.mergeOption=function(e,i){r.prototype.mergeOption.call(this,e,i),ST(this,this.option,e)},t.type="legend.scroll",t.defaultOption=Oi(Sl.defaultOption,{scrollDataIndex:0,pageButtonItemGap:5,pageButtonGap:null,pageButtonPosition:"end",pageFormatter:"{current}/{total}",pageIcons:{horizontal:["M0,0L12,-10L12,10z","M0,0L-12,-10L-12,10z"],vertical:["M0,0L20,0L10,-20z","M0,0L20,0L10,20z"]},pageIconColor:"#2f4554",pageIconInactiveColor:"#aaa",pageIconSize:15,pageTextStyle:{color:"#333"},animationDurationUpdate:800}),t})(Sl);function ST(r,t,e){var i=r.getOrient(),a=[1,1];a[i.index]=0,Br(t,e,{type:"box",ignoreSize:!!a})}var bT=v2;var wT=ut,Um=["width","height"],Bm=["x","y"],d2=(function(r){P(t,r);function t(){var e=r!==null&&r.apply(this,arguments)||this;return e.type=t.type,e.newlineDisabled=!0,e._currentIndex=0,e}return t.prototype.init=function(){r.prototype.init.call(this),this.group.add(this._containerGroup=new wT),this._containerGroup.add(this.getContentGroup()),this.group.add(this._controllerGroup=new wT)},t.prototype.resetInner=function(){r.prototype.resetInner.call(this),this._controllerGroup.removeAll(),this._containerGroup.removeClipPath(),this._containerGroup.__rectSize=null},t.prototype.renderInner=function(e,i,a,n,o,s,l){var u=this;r.prototype.renderInner.call(this,e,i,a,n,o,s,l);var f=this._controllerGroup,h=i.get("pageIconSize",!0),p=k(h)?h:[h,h];v("pagePrev",0);var c=i.getModel("pageTextStyle");f.add(new yt({name:"pageText",style:{text:"xx/xx",fill:c.getTextColor(),font:c.getFont(),verticalAlign:"middle",align:"center"},silent:!0})),v("pageNext",1);function v(m,d){var g=m+"DataIndex",y=Ga(i.get("pageIcons",!0)[i.getOrient().name][d],{onclick:X(u._pageGo,u,g,i,n)},{x:-p[0]/2,y:-p[1]/2,width:p[0],height:p[1]});y.name=m,f.add(y)}},t.prototype.layoutInner=function(e,i,a,n,o,s){var l=this.getSelectorGroup(),u=e.getOrient().index,f=Um[u],h=Bm[u],p=Um[1-u],c=Bm[1-u];o&&Xa("horizontal",l,e.get("selectorItemGap",!0));var v=e.get("selectorButtonGap",!0),m=l.getBoundingRect(),d=[-m.x,-m.y],g=K(a);o&&(g[f]=a[f]-m[f]-v);var y=this._layoutContentAndController(e,n,g,u,f,p,c,h);if(o){if(s==="end")d[u]+=y[f]+v;else{var _=m[f]+v;d[u]-=_,y[h]-=_}y[f]+=m[f]+v,d[1-u]+=y[c]+y[p]/2-m[p]/2,y[p]=Math.max(y[p],m[p]),y[c]=Math.min(y[c],m[c]+d[1-u]),l.x=d[0],l.y=d[1],l.markRedraw()}return y},t.prototype._layoutContentAndController=function(e,i,a,n,o,s,l,u){var f=this.getContentGroup(),h=this._containerGroup,p=this._controllerGroup;Xa(e.get("orient"),f,e.get("itemGap"),n?a.width:null,n?null:a.height),Xa("horizontal",p,e.get("pageButtonItemGap",!0));var c=f.getBoundingRect(),v=p.getBoundingRect(),m=this._showController=c[o]>a[o],d=[-c.x,-c.y];i||(d[n]=f[u]);var g=[0,0],y=[-v.x,-v.y],_=Q(e.get("pageButtonGap",!0),e.get("itemGap",!0));if(m){var x=e.get("pageButtonPosition",!0);x==="end"?y[n]+=a[o]-v[o]:g[n]+=v[o]+_}y[1-n]+=c[s]/2-v[s]/2,f.setPosition(d),h.setPosition(g),p.setPosition(y);var S={x:0,y:0};if(S[o]=m?a[o]:c[o],S[s]=Math.max(c[s],v[s]),S[l]=Math.min(0,v[l]+y[1-n]),h.__rectSize=a[o],m){var b={x:0,y:0};b[o]=Math.max(a[o]-v[o]-_,0),b[s]=S[s],h.setClipPath(new mt({shape:b})),h.__rectSize=b[o]}else p.eachChild(function(C){C.attr({invisible:!0,silent:!0})});var w=this._getPageInfo(e);return w.pageIndex!=null&&xt(f,{x:w.contentPosition[0],y:w.contentPosition[1]},m?e:null),this._updatePageInfoView(e,w),S},t.prototype._pageGo=function(e,i,a){var n=this._getPageInfo(i)[e];n!=null&&a.dispatchAction({type:"legendScroll",scrollDataIndex:n,legendId:i.id})},t.prototype._updatePageInfoView=function(e,i){var a=this._controllerGroup;T(["pagePrev","pageNext"],function(f){var h=f+"DataIndex",p=i[h]!=null,c=a.childOfName(f);c&&(c.setStyle("fill",p?e.get("pageIconColor",!0):e.get("pageIconInactiveColor",!0)),c.cursor=p?"pointer":"default")});var n=a.childOfName("pageText"),o=e.get("pageFormatter"),s=i.pageIndex,l=s!=null?s+1:0,u=i.pageCount;n&&o&&n.setStyle("text",B(o)?o.replace("{current}",l==null?"":l+"").replace("{total}",u==null?"":u+""):o({current:l,total:u}))},t.prototype._getPageInfo=function(e){v
Line truncated
|
||||||
|
/*! Bundled license information:
|
||||||
|
|
||||||
|
tslib/tslib.es6.js:
|
||||||
|
(*! *****************************************************************************
|
||||||
|
Copyright (c) Microsoft Corporation.
|
||||||
|
|
||||||
|
Permission to use, copy, modify, and/or distribute this software for any
|
||||||
|
purpose with or without fee is hereby granted.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
||||||
|
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
||||||
|
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
||||||
|
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
||||||
|
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
||||||
|
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
||||||
|
PERFORMANCE OF THIS SOFTWARE.
|
||||||
|
***************************************************************************** *)
|
||||||
|
|
||||||
|
zrender/lib/zrender.js:
|
||||||
|
(*!
|
||||||
|
* ZRender, a high performance 2d drawing library.
|
||||||
|
*
|
||||||
|
* Copyright (c) 2013, Baidu Inc.
|
||||||
|
* All rights reserved.
|
||||||
|
*
|
||||||
|
* LICENSE
|
||||||
|
* https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
|
||||||
|
*)
|
||||||
|
*/
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
!function e(t){var r,i;r=this,i=function(){"use strict";function r(e,t){(null==t||t>e.length)&&(t=e.length);for(var r=0,i=Array(t);r<t;r++)i[r]=e[r];return i}function i(e,t){for(var r=0;r<t.length;r++){var i=t[r];i.enumerable=i.enumerable||!1,i.configurable=!0,"value"in i&&(i.writable=!0),Object.defineProperty(e,g(i.key),i)}}function a(e,t,r){return t&&i(e.prototype,t),r&&i(e,r),Object.defineProperty(e,"prototype",{writable:!1}),e}function n(e,t){var i="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(i)return(i=i.call(e)).next.bind(i);if(Array.isArray(e)||(i=function(e,t){if(e){if("string"==typeof e)return r(e,t);var i={}.toString.call(e).slice(8,-1);return"Object"===i&&e.constructor&&(i=e.constructor.name),"Map"===i||"Set"===i?Array.from(e):"Arguments"===i||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(i)?r(e,t):void 0}}(e))||t){i&&(e=i);var a=0;return function(){return a>=e.length?{done:!0}:{done:!1,value:e[a++]}}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}function s(e,t,r){return(t=g(t))in e?Object.defineProperty(e,t,{value:r,enumerable:!0,configurable:!0,writable:!0}):e[t]=r,e}function o(){return o=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var i in r)({}).hasOwnProperty.call(r,i)&&(e[i]=r[i])}return e},o.apply(null,arguments)}function l(e){return l=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},l(e)}function u(e,t){e.prototype=Object.create(t.prototype),e.prototype.constructor=e,c(e,t)}function d(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){})))}catch(e){}return(d=function(){return!!e})()}function h(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);t&&(i=i.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),r.push.apply(r,i)}return r}function f(e){for(var t=1;t<arguments.length;t++){var r=null!=arguments[t]?arguments[t]:{};t%2?h(Object(r),!0).forEach((function(t){s(e,t,r[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(r)):h(Object(r)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(r,t))}))}return e}function c(e,t){return c=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},c(e,t)}function g(e){var t=function(e,t){if("object"!=typeof e||!e)return e;var r=e[Symbol.toPrimitive];if(void 0!==r){var i=r.call(e,t);if("object"!=typeof i)return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)}(e,"string");return"symbol"==typeof t?t:t+""}function v(e){var t="function"==typeof Map?new Map:void 0;return v=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf("[native code]")}catch(t){return"function"==typeof e}}(e))return e;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return function(e,t,r){if(d())return Reflect.construct.apply(null,arguments);var i=[null];i.push.apply(i,t);var a=new(e.bind.apply(e,i));return r&&c(a,r.prototype),a}(e,arguments,l(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),c(r,e)},v(e)}function m(e){return e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer}var p="utf-16",y="utf-16be",E="utf-16le",T="utf-8";function S(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var L,R,A={exports:{}},b=(L||(L=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function i(){}function a(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function n(e,t,i,n,s){if("function"!=typeof i)throw new TypeError("The listener must be a function");var o=new a(i,n||e,s),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],o]:e._events[l].push(o):(e._events[l]=o,e._eventsCount++),e}function s(e,t){0==--e._eventsCount?e._events=new i:delete e._events[t]}function o(){this._events=new i,this._eventsCount=0}Object.create&&(i.prototype=Object.create(null),(new i).__proto__||(r=!1)),o.prototype.eventNames=function(){var e,i,a=[];if(0===this._eventsCount)return a;for(i in e=this._events)t.call(e,i)&&a.push(r?i.slice(1):i);return Object.getOwnPropertySymbols?a.concat(Object.getOwnPropertySymbols(e)):a},o.prototype.listeners=function(e){var t=r?r+e:e,i=this._events[t];if(!i)return[];if(i.fn)return[i.fn];for(var a=0,n=i.length,s=new Array(n);a<n;a++)s[a]=i[a].fn;return s},o.prototype.listenerCount=function(e){var t=r?r+e:e,i=this._events[t];return i?i.fn?1:i.length:0},o.prototype.emit=function(e,t,i,a,n,s){var o=r?r+e:e;if(!this._events[o])return!1;varLine truncated
|
||||||
|
//# sourceMappingURL=hls.light.min.js.map
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?module.exports=e():"function"==typeof define&&define.amd?define(e):(t="undefined"!=typeof globalThis?globalThis:t||self).Konva=e()}(this,(function(){"use strict";
|
||||||
|
/*
|
||||||
|
* Konva JavaScript Framework v9.3.22
|
||||||
|
* http://konvajs.org/
|
||||||
|
* Licensed under the MIT
|
||||||
|
* Date: Tue Jul 08 2025
|
||||||
|
*
|
||||||
|
* Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS)
|
||||||
|
* Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva)
|
||||||
|
*
|
||||||
|
* @license
|
||||||
|
*/const t=Math.PI/180;const e="undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope?self:{},i={_global:e,version:"9.3.22",isBrowser:"undefined"!=typeof window&&("[object Window]"==={}.toString.call(window)||"[object global]"==={}.toString.call(window)),isUnminified:/param/.test(function(t){}.toString()),dblClickWindow:400,getAngle:e=>i.angleDeg?e*t:e,enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_fixTextRendering:!1,pixelRatio:"undefined"!=typeof window&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging:()=>i.DD.isDragging,isTransforming(){var t;return null===(t=i.Transformer)||void 0===t?void 0:t.isTransforming()},isDragReady:()=>!!i.DD.node,releaseCanvasOnDestroy:!0,document:e.document,_injectGlobal(t){e.Konva=t}},n=t=>{i[t.prototype.getClassName()]=t};i._injectGlobal(i);class s{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new s(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const e=this.m;return{x:e[0]*t.x+e[2]*t.y+e[4],y:e[1]*t.x+e[3]*t.y+e[5]}}translate(t,e){return this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e,this}scale(t,e){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),n=this.m[0]*e+this.m[2]*i,s=this.m[1]*e+this.m[3]*i,r=this.m[0]*-i+this.m[2]*e,a=this.m[1]*-i+this.m[3]*e;return this.m[0]=n,this.m[1]=s,this.m[2]=r,this.m[3]=a,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,e){const i=this.m[0]+this.m[2]*e,n=this.m[1]+this.m[3]*e,s=this.m[2]+this.m[0]*t,r=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=n,this.m[2]=s,this.m[3]=r,this}multiply(t){const e=this.m[0]*t.m[0]+this.m[2]*t.m[1],i=this.m[1]*t.m[0]+this.m[3]*t.m[1],n=this.m[0]*t.m[2]+this.m[2]*t.m[3],s=this.m[1]*t.m[2]+this.m[3]*t.m[3],r=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],a=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=e,this.m[1]=i,this.m[2]=n,this.m[3]=s,this.m[4]=r,this.m[5]=a,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,i=-this.m[1]*t,n=-this.m[2]*t,s=this.m[0]*t,r=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),a=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=e,this.m[1]=i,this.m[2]=n,this.m[3]=s,this.m[4]=r,this.m[5]=a,this}getMatrix(){return this.m}decompose(){const t=this.m[0],e=this.m[1],i=this.m[2],n=this.m[3],s=t*n-e*i,r={x:this.m[4],y:this.m[5],rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(0!=t||0!=e){const a=Math.sqrt(t*t+e*e);r.rotation=e>0?Math.acos(t/a):-Math.acos(t/a),r.scaleX=a,r.scaleY=s/a,r.skewX=(t*i+e*n)/s,r.skewY=0}else if(0!=i||0!=n){const a=Math.sqrt(i*i+n*n);r.rotation=Math.PI/2-(n>0?Math.acos(-i/a):-Math.acos(i/a)),r.scaleX=s/a,r.scaleY=a,r.skewX=0,r.skewY=(t*i+e*n)/s}return r.rotation=g._getRotation(r.rotation),r}}const r=Math.PI/180,a=180/Math.PI,o="Konva error: ",h={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,2Line truncated
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
var _=(()=>{var St=Object.defineProperty;var Wa=Object.getOwnPropertyDescriptor;var Ka=Object.getOwnPropertyNames;var qa=Object.prototype.hasOwnProperty;var Ha=(r,t)=>{for(var e in t)St(r,e,{get:t[e],enumerable:!0})},$a=(r,t,e,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of Ka(t))!qa.call(r,a)&&a!==e&&St(r,a,{get:()=>t[a],enumerable:!(o=Wa(t,a))||o.enumerable});return r};var za=r=>$a(St({},"__esModule",{value:!0}),r);var Ll={};Ha(Ll,{chunk:()=>Et,clamp:()=>Mt,cloneDeep:()=>jt,debounce:()=>Lr,get:()=>Mr,groupBy:()=>Bt,keyBy:()=>Ft,meanBy:()=>Rt,merge:()=>Nt,omit:()=>Dt,orderBy:()=>Gt,pick:()=>Ut,range:()=>Wt,round:()=>Kt,set:()=>qt,sortBy:()=>Ht,sumBy:()=>$t,throttle:()=>zt,uniq:()=>Yt,uniqBy:()=>Xt});var Ya=typeof global=="object"&&global&&global.Object===Object&&global,Nr=Ya;var Xa=typeof self=="object"&&self&&self.Object===Object&&self,Za=Nr||Xa||Function("return this")(),h=Za;var Ja=h.Symbol,_=Ja;var Jt=Object.prototype,Qa=Jt.hasOwnProperty,Va=Jt.toString,Pr=_?_.toStringTag:void 0;function ka(r){var t=Qa.call(r,Pr),e=r[Pr];try{r[Pr]=void 0;var o=!0}catch{}var a=Va.call(r);return o&&(t?r[Pr]=e:delete r[Pr]),a}var Qt=ka;var rf=Object.prototype,tf=rf.toString;function ef(r){return tf.call(r)}var Vt=ef;var of="[object Null]",af="[object Undefined]",kt=_?_.toStringTag:void 0;function ff(r){return r==null?r===void 0?af:of:kt&&kt in Object(r)?Qt(r):Vt(r)}var w=ff;function nf(r){return r!=null&&typeof r=="object"}var O=nf;var pf="[object Symbol]";function mf(r){return typeof r=="symbol"||O(r)&&w(r)==pf}var j=mf;function uf(r,t){for(var e=-1,o=r==null?0:r.length,a=Array(o);++e<o;)a[e]=t(r[e],e,r);return a}var Q=uf;var sf=Array.isArray,d=sf;var lf=1/0,re=_?_.prototype:void 0,te=re?re.toString:void 0;function ee(r){if(typeof r=="string")return r;if(d(r))return Q(r,ee)+"";if(j(r))return te?te.call(r):"";var t=r+"";return t=="0"&&1/r==-lf?"-0":t}var oe=ee;var df=/\s/;function cf(r){for(var t=r.length;t--&&df.test(r.charAt(t)););return t}var ae=cf;var xf=/^\s+/;function gf(r){return r&&r.slice(0,ae(r)+1).replace(xf,"")}var fe=gf;function hf(r){var t=typeof r;return r!=null&&(t=="object"||t=="function")}var c=hf;var ne=NaN,yf=/^[-+]0x[0-9a-f]+$/i,bf=/^0b[01]+$/i,vf=/^0o[0-7]+$/i,Af=parseInt;function Tf(r){if(typeof r=="number")return r;if(j(r))return ne;if(c(r)){var t=typeof r.valueOf=="function"?r.valueOf():r;r=c(t)?t+"":t}if(typeof r!="string")return r===0?r:+r;r=fe(r);var e=bf.test(r);return e||vf.test(r)?Af(r.slice(2),e?2:8):yf.test(r)?ne:+r}var L=Tf;var ie=1/0,Of=17976931348623157e292;function _f(r){if(!r)return r===0?r:0;if(r=L(r),r===ie||r===-ie){var t=r<0?-1:1;return t*Of}return r===r?r:0}var mr=_f;function Sf(r){var t=mr(r),e=t%1;return t===t?e?t-e:t:0}var Dr=Sf;function If(r){return r}var V=If;var wf="[object AsyncFunction]",Pf="[object Function]",Cf="[object GeneratorFunction]",Ef="[object Proxy]";function Mf(r){if(!c(r))return!1;var t=w(r);return t==Pf||t==Cf||t==wf||t==Ef}var ur=Mf;var jf=h["__core-js_shared__"],Gr=jf;var pe=(function(){var r=/[^.]+$/.exec(Gr&&Gr.keys&&Gr.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function Lf(r){return!!pe&&pe in r}var me=Lf;var Bf=Function.prototype,Ff=Bf.toString;function Rf(r){if(r!=null){try{return Ff.call(r)}catch{}try{return r+""}catch{}}return""}var K=Rf;var Nf=/[\\^$.*+?()[\]{}|]/g,Df=/^\[object .+?Constructor\]$/,Gf=Function.prototype,Uf=Object.prototype,Wf=Gf.toString,Kf=Uf.hasOwnProperty,qf=RegExp("^"+Wf.call(Kf).replace(Nf,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Hf(r){if(!c(r)||me(r))return!1;var t=ur(r)?qf:Df;return t.test(K(r))}var ue=Hf;function $f(r,t){return r==null?void 0:r[t]}var se=$f;function zf(r,t){var e=se(r,t);return ue(e)?e:void 0}var I=zf;var Yf=I(h,"WeakMap"),Ur=Yf;var le=Object.create,Xf=(function(){function r(){}return function(t){if(!c(t))return{};if(le)return le(t);r.prototype=t;var e=new r;return r.prototype=void 0,e}})(),de=Xf;function Zf(r,t,e){switch(e.length){case 0:return r.call(t);case 1:return r.call(t,e[0]);case 2:return r.call(t,e[0],e[1]);case 3:return r.call(t,e[0],e[1],e[2])}return r.apply(t,e)}var ce=Zf;function Jf(){}var xe=Jf;function Qf(r,t){var e=-1,o=r.length;for(t||(t=Array(o));++e<o;)t[e]=r[e];return t}var Wr=Qf;var Vf=800,kf=16,rn=Date.now;function tn(r){var t=0,e=0;return function(){var o=rn(),a=kf-(o-e);if(e=o,a>0){if(++t>=Vf)return arguments[0]}else t=0;return r.apply(void 0,arguments)}}var ge=tn;function en(r){return function(){return r}}var he=en;var on=(function(){try{var r=I(Object,"defineProperty");return r({},"",{}),r}catch{}})(),sr=on;var an=sr?function(r,t){return sr(r,"toString",{configurable:!0,enumerable:!1,value:he(t),writable:!0})}:V,ye=an;var fn=ge(ye),Kr=fn;function nn(r,t){for(var e=-1,o=r==null?0:r.length;++e<o&&t(r[e],e,r)!==!1;);return r}var be=nn;function pn(r,t,e,o){for(var a=r.length,f=e+(o?1:-1);o?f--:++f<a;)if(t(r[f],f,r))return f;return-1}var ve=pn;function mn(r){return r!==r}var Ae=mn;function un(r,t,e){for(Line truncated
|
||||||
|
/*! Bundled license information:
|
||||||
|
|
||||||
|
lodash-es/lodash.js:
|
||||||
|
(**
|
||||||
|
* @license
|
||||||
|
* Lodash (Custom Build) <https://lodash.com/>
|
||||||
|
* Build: `lodash modularize exports="es" --repo lodash/lodash#4.18.1 -o ./`
|
||||||
|
* Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
|
||||||
|
* Released under MIT license <https://lodash.com/license>
|
||||||
|
* Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
|
||||||
|
* Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
|
||||||
|
*)
|
||||||
|
*/
|
||||||
@@ -0,0 +1,128 @@
|
|||||||
|
{
|
||||||
|
"plyr": {
|
||||||
|
"global": "Plyr",
|
||||||
|
"category": "media-player",
|
||||||
|
"js": {
|
||||||
|
"file": "plyr.min.js",
|
||||||
|
"raw_kb": 111.3,
|
||||||
|
"gzip_kb": 32.5
|
||||||
|
},
|
||||||
|
"css": {
|
||||||
|
"file": "plyr.css",
|
||||||
|
"raw_kb": 31.8,
|
||||||
|
"gzip_kb": 5
|
||||||
|
},
|
||||||
|
"note": "首选轻量无依赖播放器 UI,配合 hls 播放 m3u8 直播/点播"
|
||||||
|
},
|
||||||
|
"hls": {
|
||||||
|
"global": "Hls",
|
||||||
|
"category": "streaming",
|
||||||
|
"js": {
|
||||||
|
"file": "hls.light.min.js",
|
||||||
|
"raw_kb": 379.8,
|
||||||
|
"gzip_kb": 117.3
|
||||||
|
},
|
||||||
|
"note": "HLS (m3u8) 离线精简版流媒体引擎"
|
||||||
|
},
|
||||||
|
"echarts": {
|
||||||
|
"global": "echarts",
|
||||||
|
"category": "charts",
|
||||||
|
"heavy": true,
|
||||||
|
"js": {
|
||||||
|
"file": "echarts.custom.min.js",
|
||||||
|
"raw_kb": 610.5,
|
||||||
|
"gzip_kb": 203.1
|
||||||
|
},
|
||||||
|
"note": "按需裁剪版 ECharts(含折线/柱状/饼图/仪表盘/雷达/散点 + CanvasRenderer),仅在需要复杂图表时按需加载"
|
||||||
|
},
|
||||||
|
"konva": {
|
||||||
|
"global": "Konva",
|
||||||
|
"category": "canvas-2d",
|
||||||
|
"js": {
|
||||||
|
"file": "konva.min.js",
|
||||||
|
"raw_kb": 171.2,
|
||||||
|
"gzip_kb": 50
|
||||||
|
},
|
||||||
|
"note": "2D 交互画布引擎,适合矢量对象编排与实时动效看板"
|
||||||
|
},
|
||||||
|
"three": {
|
||||||
|
"global": "THREE",
|
||||||
|
"category": "canvas-3d",
|
||||||
|
"heavy": true,
|
||||||
|
"js": {
|
||||||
|
"file": "three.min.js",
|
||||||
|
"raw_kb": 669,
|
||||||
|
"gzip_kb": 170.9
|
||||||
|
},
|
||||||
|
"note": "Three.js 3D 渲染库,体积较大,机顶盒/低端 GPU 慎用,仅明确需要 3D 时加载"
|
||||||
|
},
|
||||||
|
"rough": {
|
||||||
|
"global": "rough",
|
||||||
|
"category": "sketch",
|
||||||
|
"js": {
|
||||||
|
"file": "rough.min.js",
|
||||||
|
"raw_kb": 27.3,
|
||||||
|
"gzip_kb": 9.2
|
||||||
|
},
|
||||||
|
"note": "手绘风格 Canvas/SVG 绘制库(超轻量 <9KB)"
|
||||||
|
},
|
||||||
|
"tailwind": {
|
||||||
|
"category": "css",
|
||||||
|
"css": {
|
||||||
|
"file": "tailwind-lite.min.css",
|
||||||
|
"raw_kb": 4.7,
|
||||||
|
"gzip_kb": 1.6
|
||||||
|
},
|
||||||
|
"note": "离线预编译 Tailwind 实用工具类 CSS(零 JS 运行时开销,Android 11 WebView 兼容)"
|
||||||
|
},
|
||||||
|
"dayjs": {
|
||||||
|
"global": "dayjs",
|
||||||
|
"category": "datetime",
|
||||||
|
"js": {
|
||||||
|
"file": "dayjs.min.js",
|
||||||
|
"raw_kb": 7,
|
||||||
|
"gzip_kb": 3
|
||||||
|
},
|
||||||
|
"note": "超轻量日期时间格式化与计算库(~2KB)"
|
||||||
|
},
|
||||||
|
"lodash": {
|
||||||
|
"global": "_",
|
||||||
|
"category": "utils",
|
||||||
|
"js": {
|
||||||
|
"file": "lodash-lite.min.js",
|
||||||
|
"raw_kb": 32.2,
|
||||||
|
"gzip_kb": 12.1
|
||||||
|
},
|
||||||
|
"note": "按需 Tree-Shaking 的 lodash-es 常用工具函数集(window._)"
|
||||||
|
},
|
||||||
|
"zustand": {
|
||||||
|
"global": "Zustand",
|
||||||
|
"category": "state",
|
||||||
|
"js": {
|
||||||
|
"file": "zustand.min.js",
|
||||||
|
"raw_kb": 0.8,
|
||||||
|
"gzip_kb": 0.5
|
||||||
|
},
|
||||||
|
"note": "极简跨组件状态共享库(window.Zustand.createStore,~1KB)"
|
||||||
|
},
|
||||||
|
"anime": {
|
||||||
|
"global": "anime",
|
||||||
|
"category": "animation",
|
||||||
|
"js": {
|
||||||
|
"file": "anime.min.js",
|
||||||
|
"raw_kb": 17,
|
||||||
|
"gzip_kb": 6.9
|
||||||
|
},
|
||||||
|
"note": "轻量动效库(仅在 CSS 动画不够用时按需引入)"
|
||||||
|
},
|
||||||
|
"icons": {
|
||||||
|
"global": "PwIcons",
|
||||||
|
"category": "icons",
|
||||||
|
"js": {
|
||||||
|
"file": "pw-icons.min.js",
|
||||||
|
"raw_kb": 2.3,
|
||||||
|
"gzip_kb": 1.2
|
||||||
|
},
|
||||||
|
"note": "超轻量离线 SVG 图标运行时(<2KB,支持 PwIcons.svg(\"cpu\", 20) 或 data-pw-icon 属性)"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
@charset "UTF-8";@keyframes plyr-progress{to{background-position:25px 0;background-position:var(--plyr-progress-loading-size,25px) 0}}@keyframes plyr-popup{0%{opacity:.5;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@keyframes plyr-fade-in{0%{opacity:0}to{opacity:1}}.plyr{-moz-osx-font-smoothing:grayscale;-webkit-font-smoothing:antialiased;align-items:center;direction:ltr;display:flex;flex-direction:column;font-family:inherit;font-family:var(--plyr-font-family,inherit);font-variant-numeric:tabular-nums;font-weight:400;font-weight:var(--plyr-font-weight-regular,400);line-height:1.7;line-height:var(--plyr-line-height,1.7);max-width:100%;min-width:200px;position:relative;text-shadow:none;transition:box-shadow .3s ease;z-index:0}.plyr audio,.plyr iframe,.plyr video{display:block;height:100%;width:100%}.plyr button{font:inherit;line-height:inherit;width:auto}.plyr:focus{outline:0}.plyr--full-ui{box-sizing:border-box}.plyr--full-ui *,.plyr--full-ui :after,.plyr--full-ui :before{box-sizing:inherit}.plyr--full-ui a,.plyr--full-ui button,.plyr--full-ui input,.plyr--full-ui label{touch-action:manipulation}.plyr__badge{background:#4a5464;background:var(--plyr-badge-background,#4a5464);border-radius:2px;border-radius:var(--plyr-badge-border-radius,2px);color:#fff;color:var(--plyr-badge-text-color,#fff);font-size:9px;font-size:var(--plyr-font-size-badge,9px);line-height:1;padding:3px 4px}.plyr--full-ui ::-webkit-media-text-track-container{display:none}.plyr__captions{animation:plyr-fade-in .3s ease;bottom:0;display:none;font-size:13px;font-size:var(--plyr-font-size-small,13px);left:0;padding:10px;padding:var(--plyr-control-spacing,10px);position:absolute;text-align:center;transition:transform .4s ease-in-out;width:100%}.plyr__captions span:empty{display:none}@media (min-width:480px){.plyr__captions{font-size:15px;font-size:var(--plyr-font-size-base,15px);padding:20px;padding:calc(2 * var(--plyr-control-spacing, 10px))}}@media (min-width:768px){.plyr__captions{font-size:18px;font-size:var(--plyr-font-size-large,18px)}}.plyr--captions-active .plyr__captions{display:block}.plyr:not(.plyr--hide-controls) .plyr__controls:not(:empty)~.plyr__captions{transform:translateY(calc(-40px));transform:translateY(calc(-4 * var(--plyr-control-spacing, 10px)))}.plyr__caption{background:#000c;background:var(--plyr-captions-background,#000c);border-radius:4px;-webkit-box-decoration-break:clone;box-decoration-break:clone;color:#fff;color:var(--plyr-captions-text-color,#fff);line-height:185%;padding:.2em .5em;white-space:pre-wrap}.plyr__caption div{display:inline}.plyr__control{background:#0000;border:0;border-radius:4px;border-radius:var(--plyr-control-radius,4px);color:inherit;cursor:pointer;flex-shrink:0;overflow:visible;padding:7px;padding:calc(.7 * var(--plyr-control-spacing, 10px));position:relative;transition:all .1s ease-in-out}.plyr__control svg{display:block;fill:currentColor;height:18px;height:var(--plyr-control-icon-size,18px);pointer-events:none;width:18px;width:var(--plyr-control-icon-size,18px)}.plyr__control:focus{outline:0}.plyr__control:focus-visible{outline:2px dashed #00b2ff;outline:2px dashed var(--plyr-focus-visible-color,var(--plyr-color-main,var(--plyr-color-main,#00b2ff)));outline-offset:2px}a.plyr__control{text-decoration:none}.plyr__control.plyr__control--pressed .icon--not-pressed,.plyr__control.plyr__control--pressed .label--not-pressed,.plyr__control:not(.plyr__control--pressed) .icon--pressed,.plyr__control:not(.plyr__control--pressed) .label--pressed,a.plyr__control:after,a.plyr__control:before{display:none}.plyr--full-ui ::-webkit-media-controls{display:none}.plyr__controls{align-items:center;display:flex;justify-content:flex-end;text-align:center}.plyr__controls .plyr__progress__container{flex:1;min-width:0}.plyr__controls .plyr__controls__item{margin-left:2.5px;margin-left:calc(.25 * var(--plyr-control-spacing, 10px))}.plyr__controls .plyr__controls__item:first-child{margin-left:0;margin-right:auto}.plyr__controls .plyr__controls__item.plyr__progress__container{padding-left:2.5px;padding-left:calc(.25 * var(--plyr-control-spacing, 10px))}.plyr__controls .plyr__controls__item.plyr__time{padding:0 5px;padding:0 calc(.5 * var(--plyr-control-spacing, 10px))}.plyr__controls .plyr__controls__item.plyr__progress__container:first-child,.plyr__controls .plyr__controls__item.plyr__time+.plyr__time,.plyr__controls .plyr__controls__item.plyr__time:first-child{padding-left:0}.plyr [data-plyr=airplay],.plyr [data-plyr=captions],.plyr [data-plyr=fullscreen],.plyr [data-plyr=pip],.plyr__controls:empty{display:none}.plyr--airplay-supported [data-plyr=airplay],.plyr--captions-enabled [data-plyr=captions],.plyr--fullscreen-enabled [data-plyr=fullscreen],.plyr--pip-supported [data-plyr=pip]{display:inline-block}.plyr__menu{display:flex;position:relative}.plyr__menu .plyr__control svg{transition:transform .3s ease}.plyr__menu .plyr__control[aria-expanded=true] svg{transform:rotate(90deg)}.plyr__menu .plyr__cLine truncated
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
"object"==typeof navigator&&function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):(e="undefined"!=typeof globalThis?globalThis:e||self).Plyr=t()}(this,function(){var e=Object.create,t=Object.defineProperty,i=Object.getOwnPropertyDescriptor,s=Object.getOwnPropertyNames,n=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,l=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),r=(l,r,o)=>(o=null!=l?e(n(l)):{},((e,n,l,r)=>{if(n&&"object"==typeof n||"function"==typeof n)for(var o,c=s(n),u=0,h=c.length;u<h;u++)o=c[u],a.call(e,o)||o===l||t(e,o,{get:(e=>n[e]).bind(null,o),enumerable:!(r=i(n,o))||r.enumerable});return e})(!r&&l&&l.__esModule&&a.call(l,"default")?o:t(o,"default",{value:l,enumerable:!0}),l)),o=l((e,t)=>{var i,s;i=e,s=function(){"use strict";function e(e,t){for(var i=0;i<t.length;i++){var s=t[i];s.enumerable=s.enumerable||!1,s.configurable=!0,"value"in s&&(s.writable=!0),Object.defineProperty(e,s.key,s)}}function t(e,t,i){return t in e?Object.defineProperty(e,t,{value:i,enumerable:!0,configurable:!0,writable:!0}):e[t]=i,e}function i(e,t){var i=Object.keys(e);if(Object.getOwnPropertySymbols){var s=Object.getOwnPropertySymbols(e);t&&(s=s.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),i.push.apply(i,s)}return i}function s(e){for(var s=1;s<arguments.length;s++){var n=null!=arguments[s]?arguments[s]:{};s%2?i(Object(n),!0).forEach(function(i){t(e,i,n[i])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):i(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var n={addCSS:!0,thumbWidth:15,watch:!0},a=function(e){return null!=e?e.constructor:null},l=function(e,t){return!!(e&&t&&e instanceof t)},r=function(e){return a(e)===String},o=function(e){return Array.isArray(e)},c=function(e){return l(e,NodeList)},u=r,h=o,d=c,m=function(e){return l(e,Element)},p=function(e){return l(e,Event)},g=function(e){return function(e){return null==e}(e)||(r(e)||o(e)||c(e))&&!e.length||function(e){return a(e)===Object}(e)&&!Object.keys(e).length};return function(){function t(e,i){(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")})(this,t),m(e)?this.element=e:u(e)&&(this.element=document.querySelector(e)),m(this.element)&&g(this.element.rangeTouch)&&(this.config=s({},n,{},i),this.init())}return i=t,l=[{key:"setup",value:function(e){var i=1<arguments.length&&void 0!==arguments[1]?arguments[1]:{},a=null;if(g(e)||u(e)?a=Array.from(document.querySelectorAll(u(e)?e:'input[type="range"]')):m(e)?a=[e]:d(e)?a=Array.from(e):h(e)&&(a=e.filter(m)),g(a))return null;var l=s({},n,{},i);return u(e)&&l.watch&&new MutationObserver(function(i){Array.from(i).forEach(function(i){Array.from(i.addedNodes).forEach(function(i){m(i)&&function(e,t){return function(){return Array.from(document.querySelectorAll(t)).includes(this)}.call(e,t)}(i,e)&&new t(i,l)})})}).observe(document.body,{childList:!0,subtree:!0}),a.map(function(e){return new t(e,i)})}},{key:"enabled",get:function(){return"ontouchstart"in document.documentElement}}],(a=[{key:"init",value:function(){t.enabled&&(this.config.addCSS&&(this.element.style.userSelect="none",this.element.style.webKitUserSelect="none",this.element.style.touchAction="manipulation"),this.listeners(!0),this.element.rangeTouch=this)}},{key:"destroy",value:function(){t.enabled&&(this.config.addCSS&&(this.element.style.userSelect="",this.element.style.webKitUserSelect="",this.element.style.touchAction=""),this.listeners(!1),this.element.rangeTouch=null)}},{key:"listeners",value:function(e){var t=this,i=e?"addEventListener":"removeEventListener";["touchstart","touchmove","touchend"].forEach(function(e){t.element[i](e,function(e){return t.set(e)},!1)})}},{key:"get",value:function(e){if(!t.enabled||!p(e))return null;var i,s=e.target,n=e.changedTouches[0],a=parseFloat(s.getAttribute("min"))||0,l=parseFloat(s.getAttribute("max"))||100,r=parseFloat(s.getAttribute("step"))||1,o=s.getBoundingClientRect(),c=100/o.width*(this.config.thumbWidth/2)/100;return 0>(i=100/o.width*(n.clientX-o.left))?i=0:100<i&&(i=100),50>i?i-=(100-2*i)*c:50<i&&(i+=2*(i-50)*c),a+function(e,t){if(1>t){var i=function(e){var t="".concat(e).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);return t?Math.max(0,(t[1]?t[1].length:0)-(t[2]?+t[2]:0)):0}(t);return parseFloat(e.toFixed(i))}return Math.round(e/t)*t}(i/100*(l-a),r)}},{key:"set",value:function(e){t.enabled&&p(e)&&!e.target.disabled&&(e.preventDefault(),e.target.value=this.get(e),function(e,t){if(e&&t){var i=new Event(t,{bubbles:!0});e.dispatchEvent(i)}}(e.target,"touchend"===e.type?"change":"input"))}}])&&e(i.prototype,a),l&&e(i,l),t;var i,a,l}()},"object"==typeof e&&void 0!==t?t.exports=s():"function"==typeof define&&define.amd?define("RangeTouch",s):(i=i||self).RangeTouch=s()}),c=r(o(),1),u=e=>null!=e?e.constructor:null,h=(e,t)=>Boolean(e&&t&&Line truncated
|
||||||
|
//# sourceMappingURL=plyr.min.js.map
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
(function(g){
|
||||||
|
var P={
|
||||||
|
cpu:"M9 2v2M15 2v2M9 20v2M15 20v2M2 9h2M2 15h2M20 9h2M20 15h2M6 6h12v12H6zM9 9h6v6H9z",
|
||||||
|
thermometer:"M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z",
|
||||||
|
battery:"M2 7h16v10H2zM22 11v2",
|
||||||
|
wifi:"M5 12.55a11 11 0 0 1 14.08 0M1.42 9a16 16 0 0 1 21.16 0M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01",
|
||||||
|
bell:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0",
|
||||||
|
alert:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4M12 17h.01",
|
||||||
|
check:"M20 6L9 17l-5-5",
|
||||||
|
x:"M18 6L6 18M6 6l12 12",
|
||||||
|
play:"M5 3l14 9-14 9V3z",
|
||||||
|
pause:"M6 4h4v16H6zM14 4h4v16h-4z",
|
||||||
|
tv:"M2 7h20v13H2zM17 2l-5 5-5-5",
|
||||||
|
server:"M2 2h20v8H2zM2 14h20v8H2zM6 6h.01M6 18h.01",
|
||||||
|
activity:"M22 12h-4l-3 9L9 3l-3 9H2",
|
||||||
|
clock:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zM12 6v6l4 2",
|
||||||
|
settings:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4",
|
||||||
|
refresh:"M23 4v6h-6M1 20v-6h6M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15",
|
||||||
|
home:"M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",
|
||||||
|
sun:"M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42",
|
||||||
|
cloud:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",
|
||||||
|
database:"M12 2C6.5 2 2 3.8 2 6v12c0 2.2 4.5 4 10 4s10-1.8 10-4V6c0-2.2-4.5-4-10-4zM2 12c0 2.2 4.5 4 10 4s10-1.8 10-4",
|
||||||
|
terminal:"M4 17l6-6-6-6M12 19h8",
|
||||||
|
volume:"M11 5L6 9H2v6h4l5 4V5zM19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07",
|
||||||
|
zap:"M13 2L3 14h9l-1 8 10-12h-9l1-8z",
|
||||||
|
shield:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",
|
||||||
|
chart:"M18 20V10M12 20V4M6 20v-6"
|
||||||
|
};
|
||||||
|
function svg(n,s,c){var d=P[n]||P.activity;s=s||20;return '<svg width="'+s+'" height="'+s+'" viewBox="0 0 24 24" fill="none" stroke="'+(c||"currentColor")+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="'+d+'"/></svg>';}
|
||||||
|
function hydrate(root){(root||document).querySelectorAll("[data-pw-icon]").forEach(function(el){el.innerHTML=svg(el.getAttribute("data-pw-icon"),el.getAttribute("data-size")||20,el.getAttribute("data-color"));});}
|
||||||
|
g.PwIcons={names:Object.keys(P),svg:svg,hydrate:hydrate};
|
||||||
|
})(window);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
var rough=(()=>{var tt=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var $t=Object.prototype.hasOwnProperty;var Rt=(a,t)=>{for(var s in t)tt(a,s,{get:t[s],enumerable:!0})},jt=(a,t,s,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Gt(t))!$t.call(a,n)&&n!==s&&tt(a,n,{get:()=>t[n],enumerable:!(e=Et(t,n))||e.enumerable});return a};var qt=a=>jt(tt({},"__esModule",{value:!0}),a);var te={};Rt(te,{canvas:()=>Ut,default:()=>Kt,generator:()=>Yt,svg:()=>Xt});function et(a,t,s){if(a&&a.length){let[e,n]=t,o=Math.PI/180*s,r=Math.cos(o),h=Math.sin(o);for(let i of a){let[l,c]=i;i[0]=(l-e)*r-(c-n)*h+e,i[1]=(l-e)*h+(c-n)*r+n}}}function Ft(a,t){return a[0]===t[0]&&a[1]===t[1]}function Vt(a,t,s,e=1){let n=s,o=Math.max(t,.1),r=a[0]&&a[0][0]&&typeof a[0][0]=="number"?[a]:a,h=[0,0];if(n)for(let l of r)et(l,h,n);let i=(function(l,c,d){let p=[];for(let M of l){let m=[...M];Ft(m[0],m[m.length-1])||m.push([m[0][0],m[0][1]]),m.length>2&&p.push(m)}let u=[];c=Math.max(c,.1);let f=[];for(let M of p)for(let m=0;m<M.length-1;m++){let P=M[m],w=M[m+1];if(P[1]!==w[1]){let x=Math.min(P[1],w[1]);f.push({ymin:x,ymax:Math.max(P[1],w[1]),x:x===P[1]?P[0]:w[0],islope:(w[0]-P[0])/(w[1]-P[1])})}}if(f.sort(((M,m)=>M.ymin<m.ymin?-1:M.ymin>m.ymin?1:M.x<m.x?-1:M.x>m.x?1:M.ymax===m.ymax?0:(M.ymax-m.ymax)/Math.abs(M.ymax-m.ymax))),!f.length)return u;let g=[],k=f[0].ymin,b=0;for(;g.length||f.length;){if(f.length){let M=-1;for(let m=0;m<f.length&&!(f[m].ymin>k);m++)M=m;f.splice(0,M+1).forEach((m=>{g.push({s:k,edge:m})}))}if(g=g.filter((M=>!(M.edge.ymax<=k))),g.sort(((M,m)=>M.edge.x===m.edge.x?0:(M.edge.x-m.edge.x)/Math.abs(M.edge.x-m.edge.x))),(d!==1||b%c==0)&&g.length>1)for(let M=0;M<g.length;M+=2){let m=M+1;if(m>=g.length)break;let P=g[M].edge,w=g[m].edge;u.push([[Math.round(P.x),k],[Math.round(w.x),k]])}k+=d,g.forEach((M=>{M.edge.x=M.edge.x+d*M.edge.islope})),b++}return u})(r,o,e);if(n){for(let l of r)et(l,h,-n);(function(l,c,d){let p=[];l.forEach((u=>p.push(...u))),et(p,c,d)})(i,h,-n)}return i}function F(a,t){var s;let e=t.hachureAngle+90,n=t.hachureGap;n<0&&(n=4*t.strokeWidth),n=Math.round(Math.max(n,.1));let o=1;return t.roughness>=1&&(((s=t.randomizer)===null||s===void 0?void 0:s.next())||Math.random())>.7&&(o=n),Vt(a,n,e,o||1)}var q=class{constructor(t){this.helper=t}fillPolygons(t,s){return this._fillPolygons(t,s)}_fillPolygons(t,s){let e=F(t,s);return{type:"fillSketch",ops:this.renderLines(e,s)}}renderLines(t,s){let e=[];for(let n of t)e.push(...this.helper.doubleLineOps(n[0][0],n[0][1],n[1][0],n[1][1],s));return e}};function Y(a){let t=a[0],s=a[1];return Math.sqrt(Math.pow(t[0]-s[0],2)+Math.pow(t[1]-s[1],2))}var ht=class extends q{fillPolygons(t,s){let e=s.hachureGap;e<0&&(e=4*s.strokeWidth),e=Math.max(e,.1);let n=F(t,Object.assign({},s,{hachureGap:e})),o=Math.PI/180*s.hachureAngle,r=[],h=.5*e*Math.cos(o),i=.5*e*Math.sin(o);for(let[l,c]of n)Y([l,c])&&r.push([[l[0]-h,l[1]+i],[...c]],[[l[0]+h,l[1]-i],[...c]]);return{type:"fillSketch",ops:this.renderLines(r,s)}}},rt=class extends q{fillPolygons(t,s){let e=this._fillPolygons(t,s),n=Object.assign({},s,{hachureAngle:s.hachureAngle+90}),o=this._fillPolygons(t,n);return e.ops=e.ops.concat(o.ops),e}},it=class{constructor(t){this.helper=t}fillPolygons(t,s){let e=F(t,s=Object.assign({},s,{hachureAngle:0}));return this.dotsOnLines(e,s)}dotsOnLines(t,s){let e=[],n=s.hachureGap;n<0&&(n=4*s.strokeWidth),n=Math.max(n,.1);let o=s.fillWeight;o<0&&(o=s.strokeWidth/2);let r=n/4;for(let h of t){let i=Y(h),l=i/n,c=Math.ceil(l)-1,d=i-c*n,p=(h[0][0]+h[1][0])/2-n/4,u=Math.min(h[0][1],h[1][1]);for(let f=0;f<c;f++){let g=u+d+f*n,k=p-r+2*Math.random()*r,b=g-r+2*Math.random()*r,M=this.helper.ellipse(k,b,o,o,s);e.push(...M.ops)}}return{type:"fillSketch",ops:e}}},ct=class{constructor(t){this.helper=t}fillPolygons(t,s){let e=F(t,s);return{type:"fillSketch",ops:this.dashedLine(e,s)}}dashedLine(t,s){let e=s.dashOffset<0?s.hachureGap<0?4*s.strokeWidth:s.hachureGap:s.dashOffset,n=s.dashGap<0?s.hachureGap<0?4*s.strokeWidth:s.hachureGap:s.dashGap,o=[];return t.forEach((r=>{let h=Y(r),i=Math.floor(h/(e+n)),l=(h+n-i*(e+n))/2,c=r[0],d=r[1];c[0]>d[0]&&(c=r[1],d=r[0]);let p=Math.atan((d[1]-c[1])/(d[0]-c[0]));for(let u=0;u<i;u++){let f=u*(e+n),g=f+e,k=[c[0]+f*Math.cos(p)+l*Math.cos(p),c[1]+f*Math.sin(p)+l*Math.sin(p)],b=[c[0]+g*Math.cos(p)+l*Math.cos(p),c[1]+g*Math.sin(p)+l*Math.sin(p)];o.push(...this.helper.doubleLineOps(k[0],k[1],b[0],b[1],s))}})),o}},lt=class{constructor(t){this.helper=t}fillPolygons(t,s){let e=s.hachureGap<0?4*s.strokeWidth:s.hachureGap,n=s.zigzagOffset<0?e:s.zigzagOffset,o=F(t,s=Object.assign({},s,{hachureGap:e+n}));return{type:"fillSketch",ops:this.zigzagLines(o,n,s)}}zigzagLines(t,s,e){let n=[];return t.forEach((o=>{let r=Y(o),h=Math.round(r/(2*s)),i=o[0],l=o[1];i[0]>l[0]&&(i=o[1],l=o[0]);let c=Math.atan((l[1]-i[1])/(l[0]-i[0]));for(let d=0;d<h;d++){let p=2*d*s,u=2*(d+1)*s,f=Math.sqrt(2*Math.pow(s,2)),g=[i[0]+p*Math.cos(c),i[1]+p*Math.sin(c)],k=[i[0]+uLine truncated
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
/* PulseWall Prebuilt Tailwind-Compatible Utility Subset (Android 11 WebView safe, zero JS runtime) */
|
||||||
|
.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.block{display:block}.inline-block{display:inline-block}.hidden{display:none}
|
||||||
|
.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}
|
||||||
|
.items-center{align-items:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-stretch{align-items:stretch}
|
||||||
|
.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}
|
||||||
|
.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}
|
||||||
|
.col-span-2{grid-column:span 2/span 2}.col-span-full{grid-column:1/-1}
|
||||||
|
.gap-1{gap:4px}.gap-2{gap:8px}.gap-3{gap:12px}.gap-4{gap:16px}.gap-5{gap:20px}.gap-6{gap:24px}
|
||||||
|
.space-y-2>*+*{margin-top:8px}.space-y-3>*+*{margin-top:12px}.space-y-4>*+*{margin-top:16px}
|
||||||
|
.p-1{padding:4px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.p-5{padding:20px}.p-6{padding:24px}
|
||||||
|
.px-2{padding-left:8px;padding-right:8px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-5{padding-left:20px;padding-right:20px}
|
||||||
|
.py-1{padding-top:4px;padding-bottom:4px}.py-2{padding-top:8px;padding-bottom:8px}.py-3{padding-top:12px;padding-bottom:12px}.py-4{padding-top:16px;padding-bottom:16px}
|
||||||
|
.m-0{margin:0}.mt-1{margin-top:4px}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.mt-4{margin-top:16px}.mb-2{margin-bottom:8px}.mb-3{margin-bottom:12px}.mb-4{margin-bottom:16px}.mx-auto{margin-left:auto;margin-right:auto}
|
||||||
|
.w-full{width:100%}.h-full{height:100%}.min-h-screen{min-height:100vh}.max-w-full{max-width:100%}.aspect-video{aspect-ratio:16/9}
|
||||||
|
.relative{position:relative}.absolute{position:absolute}.inset-0{top:0;right:0;bottom:0;left:0}.overflow-hidden{overflow:hidden}.overflow-auto{overflow:auto}
|
||||||
|
.rounded{border-radius:6px}.rounded-lg{border-radius:10px}.rounded-xl{border-radius:14px}.rounded-2xl{border-radius:18px}.rounded-full{border-radius:9999px}
|
||||||
|
.border{border:1px solid rgba(148,163,184,0.22)}.border-slate-700{border-color:#334155}.border-slate-800{border-color:#1e293b}.border-cyan-500{border-color:#06b6d4}.border-teal-400{border-color:#2dd4bf}.border-amber-500{border-color:#f59e0b}.border-red-500{border-color:#ef4444}
|
||||||
|
.text-xs{font-size:12px;line-height:16px}.text-sm{font-size:14px;line-height:20px}.text-base{font-size:16px;line-height:24px}.text-lg{font-size:18px;line-height:26px}.text-xl{font-size:20px;line-height:28px}.text-2xl{font-size:24px;line-height:32px}.text-3xl{font-size:30px;line-height:36px}.text-4xl{font-size:36px;line-height:40px}
|
||||||
|
.font-medium{font-weight:500}.font-semibold{font-weight:600}.font-bold{font-weight:700}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
||||||
|
.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.text-white{color:#fff}.text-slate-200{color:#e2e8f0}.text-slate-300{color:#cbd5e1}.text-slate-400{color:#94a3b8}.text-slate-500{color:#64748b}
|
||||||
|
.text-teal-400{color:#2dd4bf}.text-cyan-400{color:#22d3ee}.text-sky-400{color:#38bdf8}.text-emerald-400{color:#34d399}.text-amber-400{color:#fbbf24}.text-red-400{color:#f87171}.text-rose-400{color:#fb7185}
|
||||||
|
.bg-slate-950{background-color:#020617}.bg-slate-900{background-color:#0f172a}.bg-slate-800{background-color:#1e293b}.bg-slate-700{background-color:#334155}
|
||||||
|
.bg-teal-500{background-color:#14b8a6}.bg-cyan-500{background-color:#06b6d4}.bg-sky-500{background-color:#0ea5e9}.bg-emerald-500{background-color:#10b981}.bg-amber-500{background-color:#f59e0b}.bg-red-600{background-color:#dc2626}
|
||||||
|
.bg-slate-900\/80{background-color:rgba(15,23,42,0.8)}.bg-slate-800\/80{background-color:rgba(30,41,59,0.8)}
|
||||||
|
.shadow-lg{box-shadow:0 10px 24px rgba(0,0,0,0.35)}.opacity-60{opacity:0.6}.opacity-80{opacity:0.8}
|
||||||
|
.cursor-pointer{cursor:pointer}.transition{transition:all 0.15s ease}
|
||||||
|
@keyframes pw-pulse{0%,100%{opacity:1}50%{opacity:.45}}.animate-pulse{animation:pw-pulse 1.8s cubic-bezier(.4,0,.6,1) infinite}
|
||||||
|
@keyframes pw-spin{to{transform:rotate(360deg)}}.animate-spin{animation:pw-spin 1s linear infinite}
|
||||||
|
@media(min-width:640px){.sm\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}
|
||||||
|
@media(min-width:900px){.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}
|
||||||
+3833
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1 @@
|
|||||||
|
var Zustand=(()=>{var r=Object.defineProperty;var p=Object.getOwnPropertyDescriptor;var d=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var x=(e,t)=>{for(var n in t)r(e,n,{get:t[n],enumerable:!0})},I=(e,t,n,c)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of d(t))!j.call(e,o)&&o!==n&&r(e,o,{get:()=>t[o],enumerable:!(c=p(t,o))||c.enumerable});return e};var m=e=>I(r({},"__esModule",{value:!0}),e);var y={};x(y,{createStore:()=>b});var u=e=>{let t,n=new Set,c=(s,S)=>{let i=typeof s=="function"?s(t):s;if(!Object.is(i,t)){let f=t;t=S??(typeof i!="object"||i===null)?i:Object.assign({},t,i),n.forEach(g=>g(t,f))}},o=()=>t,a={setState:c,getState:o,getInitialState:()=>l,subscribe:s=>(n.add(s),()=>n.delete(s))},l=t=e(c,o,a);return a},b=(e=>e?u(e):u);return m(y);})();
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
:root {
|
||||||
|
--pw-bg: #0a0f1d;
|
||||||
|
--pw-surface: #121a2e;
|
||||||
|
--pw-surface-2: #18233d;
|
||||||
|
--pw-border: rgba(148, 163, 184, 0.18);
|
||||||
|
--pw-text: #eef4ff;
|
||||||
|
--pw-muted: #93a4c3;
|
||||||
|
--pw-accent: #38bdf8;
|
||||||
|
--pw-ok: #22c55e;
|
||||||
|
--pw-warn: #f59e0b;
|
||||||
|
--pw-danger: #ef4444;
|
||||||
|
--safe-top: 28px;
|
||||||
|
--safe-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
-webkit-tap-highlight-color: transparent;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
width: 100%;
|
||||||
|
min-height: 100%;
|
||||||
|
background: var(--pw-bg);
|
||||||
|
color: var(--pw-text);
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Noto Sans CJK SC", sans-serif;
|
||||||
|
overflow-x: hidden;
|
||||||
|
word-wrap: break-word;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pw-shell {
|
||||||
|
padding: calc(var(--safe-top) + 46px) 14px calc(var(--safe-bottom) + 18px) 14px;
|
||||||
|
max-width: 100%;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pw-shell.pw-fullscreen-mode {
|
||||||
|
padding: 0 !important;
|
||||||
|
margin: 0 !important;
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
#pw-shell.pw-fullscreen-mode #pw-canvas,
|
||||||
|
#pw-shell.pw-fullscreen-mode #pw-sandbox-root {
|
||||||
|
width: 100%;
|
||||||
|
min-height: 100vh;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pw-stack { display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.pw-row { display: flex; flex-direction: row; align-items: center; gap: 10px; flex-wrap: wrap; }
|
||||||
|
.pw-between { justify-content: space-between; }
|
||||||
|
|
||||||
|
.pw-grid-2 {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.pw-grid-auto {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
@media (max-width: 360px) {
|
||||||
|
.pw-grid-2 { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.pw-card {
|
||||||
|
background: linear-gradient(160deg, rgba(24, 35, 61, 0.92), rgba(16, 24, 43, 0.96));
|
||||||
|
border: 1px solid var(--pw-border);
|
||||||
|
border-radius: 16px;
|
||||||
|
padding: 14px 16px;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
.pw-hero {
|
||||||
|
border-color: rgba(56, 189, 248, 0.35);
|
||||||
|
background: linear-gradient(145deg, rgba(16, 36, 66, 0.95), rgba(14, 21, 38, 0.96));
|
||||||
|
}
|
||||||
|
|
||||||
|
.pw-muted { color: var(--pw-muted); font-size: 13px; }
|
||||||
|
.pw-metric { font-size: 26px; font-weight: 700; margin-top: 6px; letter-spacing: 0.3px; }
|
||||||
|
.pw-ok-text { color: var(--pw-ok); }
|
||||||
|
.pw-warn-text { color: var(--pw-warn); }
|
||||||
|
.pw-danger-text { color: var(--pw-danger); }
|
||||||
|
|
||||||
|
.pw-pill {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.4px;
|
||||||
|
background: rgba(56, 189, 248, 0.16);
|
||||||
|
color: var(--pw-accent);
|
||||||
|
}
|
||||||
|
.pw-pill.pw-ok { background: rgba(34, 197, 94, 0.18); color: var(--pw-ok); }
|
||||||
|
.pw-pill.pw-warn { background: rgba(245, 158, 11, 0.18); color: var(--pw-warn); }
|
||||||
|
.pw-pill.pw-danger { background: rgba(239, 68, 68, 0.22); color: #fca5a5; }
|
||||||
|
|
||||||
|
.pw-btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
padding: 10px 14px;
|
||||||
|
border-radius: 12px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.pw-btn-primary { background: var(--pw-accent); color: #041220; }
|
||||||
|
.pw-btn-danger { background: var(--pw-danger); color: #ffffff; }
|
||||||
|
.pw-btn-secondary { background: var(--pw-surface-2); color: var(--pw-text); border-color: var(--pw-border); }
|
||||||
|
|
||||||
|
.pw-code {
|
||||||
|
background: #070b15;
|
||||||
|
border: 1px solid var(--pw-border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 10px;
|
||||||
|
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #cbd5e1;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pw-feed-item {
|
||||||
|
border-left: 3px solid var(--pw-accent);
|
||||||
|
padding: 10px 12px;
|
||||||
|
background: rgba(18, 26, 46, 0.85);
|
||||||
|
border-radius: 0 12px 12px 0;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
}
|
||||||
|
.pw-feed-item.level-warning { border-left-color: var(--pw-warn); }
|
||||||
|
.pw-feed-item.level-error, .pw-feed-item.level-critical { border-left-color: var(--pw-danger); }
|
||||||
|
|
||||||
|
/* IR Remote / TV D-Pad visible focus indicator */
|
||||||
|
.pw-tv-focus {
|
||||||
|
outline: 3px solid #facc15 !important;
|
||||||
|
outline-offset: 2px;
|
||||||
|
box-shadow: 0 0 0 5px rgba(250, 204, 21, 0.35), 0 8px 24px rgba(0, 0, 0, 0.45) !important;
|
||||||
|
transform: scale(1.02);
|
||||||
|
transition: transform 0.12s ease, box-shadow 0.12s ease;
|
||||||
|
}
|
||||||
|
.pw-tv-hint {
|
||||||
|
font-size: 12px;
|
||||||
|
color: #cbd5e1;
|
||||||
|
background: rgba(15, 23, 42, 0.72);
|
||||||
|
border: 1px solid rgba(56, 189, 248, 0.22);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 8px 12px;
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
(function (g) {
|
||||||
|
var CATALOG = {
|
||||||
|
plyr: { js: "./libs/plyr.min.js", css: "./libs/plyr.css", global: "Plyr" },
|
||||||
|
hls: { js: "./libs/hls.light.min.js", global: "Hls" },
|
||||||
|
echarts: { js: "./libs/echarts.custom.min.js", global: "echarts" },
|
||||||
|
konva: { js: "./libs/konva.min.js", global: "Konva" },
|
||||||
|
three: { js: "./libs/three.min.js", global: "THREE" },
|
||||||
|
rough: { js: "./libs/rough.min.js", global: "rough" },
|
||||||
|
tailwind: { css: "./libs/tailwind-lite.min.css" },
|
||||||
|
dayjs: { js: "./libs/dayjs.min.js", global: "dayjs" },
|
||||||
|
lodash: { js: "./libs/lodash-lite.min.js", global: "_" },
|
||||||
|
zustand: { js: "./libs/zustand.min.js", global: "Zustand" },
|
||||||
|
anime: { js: "./libs/anime.min.js", global: "anime" },
|
||||||
|
icons: { js: "./libs/pw-icons.min.js", global: "PwIcons" }
|
||||||
|
};
|
||||||
|
|
||||||
|
var loadedPromises = {};
|
||||||
|
|
||||||
|
function loadCss(href) {
|
||||||
|
return new Promise(function (resolve) {
|
||||||
|
if (document.querySelector('link[data-pw-lib-css="' + href + '"]')) {
|
||||||
|
resolve();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var link = document.createElement("link");
|
||||||
|
link.rel = "stylesheet";
|
||||||
|
link.href = href;
|
||||||
|
link.setAttribute("data-pw-lib-css", href);
|
||||||
|
link.onload = function () { resolve(); };
|
||||||
|
link.onerror = function () { resolve(); };
|
||||||
|
document.head.appendChild(link);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadJs(src) {
|
||||||
|
return new Promise(function (resolve, reject) {
|
||||||
|
if (document.querySelector('script[data-pw-lib-js="' + src + '"]')) {
|
||||||
|
resolve();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
var s = document.createElement("script");
|
||||||
|
s.src = src;
|
||||||
|
s.async = false;
|
||||||
|
s.setAttribute("data-pw-lib-js", src);
|
||||||
|
s.onload = function () { resolve(); };
|
||||||
|
s.onerror = function () { reject(new Error("Failed to load local lib: " + src)); };
|
||||||
|
document.head.appendChild(s);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadOne(name) {
|
||||||
|
var key = String(name || "").toLowerCase().trim();
|
||||||
|
var entry = CATALOG[key];
|
||||||
|
if (!entry) {
|
||||||
|
return Promise.reject(new Error("Unknown local PulseWall lib: " + name));
|
||||||
|
}
|
||||||
|
if (loadedPromises[key]) return loadedPromises[key];
|
||||||
|
var tasks = [];
|
||||||
|
if (entry.css) tasks.push(loadCss(entry.css));
|
||||||
|
if (entry.js) tasks.push(loadJs(entry.js));
|
||||||
|
loadedPromises[key] = Promise.all(tasks).then(function () {
|
||||||
|
return entry.global ? g[entry.global] : true;
|
||||||
|
});
|
||||||
|
return loadedPromises[key];
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadLib(names) {
|
||||||
|
if (Array.isArray(names)) {
|
||||||
|
return Promise.all(names.map(loadOne));
|
||||||
|
}
|
||||||
|
return loadOne(names);
|
||||||
|
}
|
||||||
|
|
||||||
|
g.__pwLibLoader = {
|
||||||
|
catalog: CATALOG,
|
||||||
|
loadLib: loadLib
|
||||||
|
};
|
||||||
|
})(window);
|
||||||
@@ -0,0 +1,366 @@
|
|||||||
|
(function (g) {
|
||||||
|
if (g.__pwStageBootstrapped) return;
|
||||||
|
g.__pwStageBootstrapped = true;
|
||||||
|
|
||||||
|
var frozen = false;
|
||||||
|
var disposed = false;
|
||||||
|
var origSetInterval = g.setInterval.bind(g);
|
||||||
|
var origClearInterval = g.clearInterval.bind(g);
|
||||||
|
var origSetTimeout = g.setTimeout.bind(g);
|
||||||
|
var origClearTimeout = g.clearTimeout.bind(g);
|
||||||
|
var origRAF = g.requestAnimationFrame ? g.requestAnimationFrame.bind(g) : null;
|
||||||
|
var origCAF = g.cancelAnimationFrame ? g.cancelAnimationFrame.bind(g) : null;
|
||||||
|
|
||||||
|
var intervals = new Set();
|
||||||
|
var timeouts = new Set();
|
||||||
|
var rafIds = new Set();
|
||||||
|
var heldRafCallbacks = [];
|
||||||
|
var sockets = new Set();
|
||||||
|
var eventSources = new Set();
|
||||||
|
var observers = new Set();
|
||||||
|
|
||||||
|
g.setInterval = function (fn, delay) {
|
||||||
|
if (disposed) return 0;
|
||||||
|
var args = Array.prototype.slice.call(arguments, 2);
|
||||||
|
var wrapped = function () {
|
||||||
|
if (disposed || frozen) return;
|
||||||
|
if (typeof fn === "function") fn.apply(g, args);
|
||||||
|
else origSetTimeout(fn, 0);
|
||||||
|
};
|
||||||
|
var id = origSetInterval(wrapped, delay);
|
||||||
|
intervals.add(id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
g.clearInterval = function (id) {
|
||||||
|
intervals.delete(id);
|
||||||
|
return origClearInterval(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
g.setTimeout = function (fn, delay) {
|
||||||
|
if (disposed) return 0;
|
||||||
|
var args = Array.prototype.slice.call(arguments, 2);
|
||||||
|
var id = 0;
|
||||||
|
var wrapped = function () {
|
||||||
|
timeouts.delete(id);
|
||||||
|
if (disposed) return;
|
||||||
|
if (typeof fn === "function") fn.apply(g, args);
|
||||||
|
else origSetTimeout(fn, 0);
|
||||||
|
};
|
||||||
|
id = origSetTimeout(wrapped, delay);
|
||||||
|
timeouts.add(id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
|
||||||
|
g.clearTimeout = function (id) {
|
||||||
|
timeouts.delete(id);
|
||||||
|
return origClearTimeout(id);
|
||||||
|
};
|
||||||
|
|
||||||
|
if (origRAF) {
|
||||||
|
g.requestAnimationFrame = function (cb) {
|
||||||
|
if (disposed) return 0;
|
||||||
|
if (frozen) {
|
||||||
|
heldRafCallbacks.push(cb);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
var id = 0;
|
||||||
|
id = origRAF(function (ts) {
|
||||||
|
rafIds.delete(id);
|
||||||
|
if (disposed) return;
|
||||||
|
if (frozen) {
|
||||||
|
heldRafCallbacks.push(cb);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
cb(ts);
|
||||||
|
});
|
||||||
|
rafIds.add(id);
|
||||||
|
return id;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (origCAF) {
|
||||||
|
g.cancelAnimationFrame = function (id) {
|
||||||
|
rafIds.delete(id);
|
||||||
|
return origCAF(id);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof g.WebSocket === "function") {
|
||||||
|
var NativeWS = g.WebSocket;
|
||||||
|
g.WebSocket = function (url, protocols) {
|
||||||
|
var ws = protocols !== undefined ? new NativeWS(url, protocols) : new NativeWS(url);
|
||||||
|
sockets.add(ws);
|
||||||
|
ws.addEventListener("close", function () { sockets.delete(ws); });
|
||||||
|
return ws;
|
||||||
|
};
|
||||||
|
g.WebSocket.prototype = NativeWS.prototype;
|
||||||
|
g.WebSocket.CONNECTING = NativeWS.CONNECTING;
|
||||||
|
g.WebSocket.OPEN = NativeWS.OPEN;
|
||||||
|
g.WebSocket.CLOSING = NativeWS.CLOSING;
|
||||||
|
g.WebSocket.CLOSED = NativeWS.CLOSED;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof g.EventSource === "function") {
|
||||||
|
var NativeES = g.EventSource;
|
||||||
|
g.EventSource = function (url, cfg) {
|
||||||
|
var es = cfg !== undefined ? new NativeES(url, cfg) : new NativeES(url);
|
||||||
|
eventSources.add(es);
|
||||||
|
return es;
|
||||||
|
};
|
||||||
|
g.EventSource.prototype = NativeES.prototype;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof g.MutationObserver === "function") {
|
||||||
|
var NativeMO = g.MutationObserver;
|
||||||
|
g.MutationObserver = function (cb) {
|
||||||
|
var mo = new NativeMO(cb);
|
||||||
|
observers.add(mo);
|
||||||
|
return mo;
|
||||||
|
};
|
||||||
|
g.MutationObserver.prototype = NativeMO.prototype;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (typeof g.ResizeObserver === "function") {
|
||||||
|
var NativeRO = g.ResizeObserver;
|
||||||
|
g.ResizeObserver = function (cb) {
|
||||||
|
var ro = new NativeRO(cb);
|
||||||
|
observers.add(ro);
|
||||||
|
return ro;
|
||||||
|
};
|
||||||
|
g.ResizeObserver.prototype = NativeRO.prototype;
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureFreezeStyle() {
|
||||||
|
if (document.getElementById("__pw_freeze_style")) return;
|
||||||
|
var st = document.createElement("style");
|
||||||
|
st.id = "__pw_freeze_style";
|
||||||
|
st.textContent =
|
||||||
|
"html.__pw-frozen *, html.__pw-frozen *::before, html.__pw-frozen *::after { " +
|
||||||
|
"animation-play-state: paused !important; transition: none !important; }";
|
||||||
|
(document.head || document.documentElement).appendChild(st);
|
||||||
|
}
|
||||||
|
|
||||||
|
g.__pwSetFrozen = function (shouldFreeze) {
|
||||||
|
var next = !!shouldFreeze;
|
||||||
|
if (next === frozen || disposed) return;
|
||||||
|
frozen = next;
|
||||||
|
ensureFreezeStyle();
|
||||||
|
if (frozen) {
|
||||||
|
document.documentElement.classList.add("__pw-frozen");
|
||||||
|
document.querySelectorAll("video, audio").forEach(function (m) {
|
||||||
|
try {
|
||||||
|
if (!m.paused) {
|
||||||
|
m.dataset.pwWasPlaying = "1";
|
||||||
|
m.pause();
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
document.documentElement.classList.remove("__pw-frozen");
|
||||||
|
document.querySelectorAll("video, audio").forEach(function (m) {
|
||||||
|
try {
|
||||||
|
if (m.dataset.pwWasPlaying === "1") {
|
||||||
|
delete m.dataset.pwWasPlaying;
|
||||||
|
m.play().catch(function () {});
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
|
var toResume = heldRafCallbacks.splice(0, heldRafCallbacks.length);
|
||||||
|
toResume.forEach(function (cb) {
|
||||||
|
try { g.requestAnimationFrame(cb); } catch (_) {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
g.__pwPageDispose = function () {
|
||||||
|
if (disposed) return;
|
||||||
|
disposed = true;
|
||||||
|
frozen = true;
|
||||||
|
heldRafCallbacks.length = 0;
|
||||||
|
|
||||||
|
intervals.forEach(function (id) { try { origClearInterval(id); } catch (_) {} });
|
||||||
|
intervals.clear();
|
||||||
|
timeouts.forEach(function (id) { try { origClearTimeout(id); } catch (_) {} });
|
||||||
|
timeouts.clear();
|
||||||
|
if (origCAF) {
|
||||||
|
rafIds.forEach(function (id) { try { origCAF(id); } catch (_) {} });
|
||||||
|
}
|
||||||
|
rafIds.clear();
|
||||||
|
|
||||||
|
sockets.forEach(function (ws) { try { ws.close(); } catch (_) {} });
|
||||||
|
sockets.clear();
|
||||||
|
eventSources.forEach(function (es) { try { es.close(); } catch (_) {} });
|
||||||
|
eventSources.clear();
|
||||||
|
observers.forEach(function (ob) { try { ob.disconnect(); } catch (_) {} });
|
||||||
|
observers.clear();
|
||||||
|
|
||||||
|
try {
|
||||||
|
if (g.echarts && typeof g.echarts.getInstanceByDom === "function") {
|
||||||
|
document.querySelectorAll("div, canvas").forEach(function (el) {
|
||||||
|
try {
|
||||||
|
var inst = g.echarts.getInstanceByDom(el);
|
||||||
|
if (inst && typeof inst.dispose === "function") inst.dispose();
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
document.querySelectorAll("video, audio").forEach(function (m) {
|
||||||
|
try { m.pause(); m.removeAttribute("src"); m.load(); } catch (_) {}
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
try {
|
||||||
|
document.querySelectorAll("canvas").forEach(function (c) {
|
||||||
|
try {
|
||||||
|
var gl = c.getContext("webgl2") || c.getContext("webgl") || c.getContext("experimental-webgl");
|
||||||
|
if (gl) {
|
||||||
|
var ext = gl.getExtension("WEBGL_lose_context");
|
||||||
|
if (ext) ext.loseContext();
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
try { c.width = 0; c.height = 0; } catch (_) {}
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Wire error watchdog back to parent host/sandbox
|
||||||
|
function reportErr(source, msg, stack) {
|
||||||
|
if (disposed) return;
|
||||||
|
try {
|
||||||
|
if (g.parent && g.parent !== g && typeof g.parent.__pwOnStageError === "function") {
|
||||||
|
g.parent.__pwOnStageError(String(source || "runtime"), String(msg || "Unknown error"), String(stack || ""));
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
g.onerror = function (msg, url, line, col, err) {
|
||||||
|
reportErr("window.onerror", msg + " (" + line + ":" + col + ")", err && err.stack ? err.stack : "");
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
g.addEventListener("unhandledrejection", function (ev) {
|
||||||
|
var r = ev && ev.reason;
|
||||||
|
reportErr("unhandledrejection", r && r.message ? r.message : String(r), r && r.stack ? r.stack : "");
|
||||||
|
});
|
||||||
|
var origConsoleError = console.error;
|
||||||
|
console.error = function () {
|
||||||
|
try {
|
||||||
|
var parts = Array.prototype.slice.call(arguments).map(function (a) {
|
||||||
|
if (a instanceof Error) return a.message + "\n" + (a.stack || "");
|
||||||
|
if (typeof a === "object") { try { return JSON.stringify(a); } catch (_) { return String(a); } }
|
||||||
|
return String(a);
|
||||||
|
});
|
||||||
|
reportErr("console.error", parts.join(" "), "");
|
||||||
|
} catch (_) {}
|
||||||
|
return origConsoleError.apply(console, arguments);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Wire window.PulseWall API inside the isolated iframe
|
||||||
|
var parentPW = (g.parent && g.parent !== g && g.parent.PulseWall) ? g.parent.PulseWall : null;
|
||||||
|
g.__PW_DATA__ = (g.parent && g.parent !== g && g.parent.__PW_DATA__) ? g.parent.__PW_DATA__ : {};
|
||||||
|
g.PulseWall = {
|
||||||
|
loadLib: function (names) {
|
||||||
|
return g.__pwLibLoader ? g.__pwLibLoader.loadLib(names) : Promise.reject(new Error("LibLoader unavailable"));
|
||||||
|
},
|
||||||
|
libs: g.__pwLibLoader ? Object.keys(g.__pwLibLoader.catalog) : [],
|
||||||
|
sendAction: function (presetId, label, customText) {
|
||||||
|
if (parentPW && parentPW.sendAction) parentPW.sendAction(presetId, label, customText);
|
||||||
|
},
|
||||||
|
openSettings: function () {
|
||||||
|
if (parentPW && parentPW.openSettings) parentPW.openSettings();
|
||||||
|
},
|
||||||
|
discoverHub: function () {
|
||||||
|
if (parentPW && parentPW.discoverHub) parentPW.discoverHub();
|
||||||
|
},
|
||||||
|
checkUpdate: function () {
|
||||||
|
if (parentPW && parentPW.checkUpdate) parentPW.checkUpdate();
|
||||||
|
},
|
||||||
|
getDeviceProfile: function () {
|
||||||
|
return parentPW && parentPW.getDeviceProfile ? parentPW.getDeviceProfile() : {};
|
||||||
|
},
|
||||||
|
getTelemetry: function () {
|
||||||
|
return parentPW && parentPW.getTelemetry ? parentPW.getTelemetry() : {};
|
||||||
|
},
|
||||||
|
getDataContext: function () {
|
||||||
|
return g.__PW_DATA__ || {};
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Spatial D-Pad navigation inside the isolated iframe
|
||||||
|
var currentFocusEl = null;
|
||||||
|
function getFocusables() {
|
||||||
|
var nodes = document.querySelectorAll("button, a[href], input, select, textarea, [tabindex], [role='button'], [onclick], .pw-btn");
|
||||||
|
return Array.prototype.slice.call(nodes).filter(function (el) {
|
||||||
|
if (el.disabled) return false;
|
||||||
|
var rect = el.getBoundingClientRect();
|
||||||
|
return rect.width > 4 && rect.height > 4 && g.getComputedStyle(el).visibility !== "hidden";
|
||||||
|
});
|
||||||
|
}
|
||||||
|
function clearTvFocus() {
|
||||||
|
if (currentFocusEl) {
|
||||||
|
currentFocusEl.classList.remove("pw-tv-focus");
|
||||||
|
currentFocusEl = null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function setTvFocus(el) {
|
||||||
|
if (!el) return;
|
||||||
|
if (currentFocusEl && currentFocusEl !== el) currentFocusEl.classList.remove("pw-tv-focus");
|
||||||
|
currentFocusEl = el;
|
||||||
|
el.classList.add("pw-tv-focus");
|
||||||
|
try { el.focus({ preventScroll: true }); } catch (_) {}
|
||||||
|
try { el.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "nearest" }); } catch (_) {}
|
||||||
|
}
|
||||||
|
function findNextFocusable(dir) {
|
||||||
|
var list = getFocusables();
|
||||||
|
if (!list.length) return null;
|
||||||
|
if (!currentFocusEl || list.indexOf(currentFocusEl) === -1) return list[0];
|
||||||
|
var cur = currentFocusEl.getBoundingClientRect();
|
||||||
|
var cx = cur.left + cur.width / 2;
|
||||||
|
var cy = cur.top + cur.height / 2;
|
||||||
|
var best = null;
|
||||||
|
var bestScore = Infinity;
|
||||||
|
for (var i = 0; i < list.length; i++) {
|
||||||
|
var el = list[i];
|
||||||
|
if (el === currentFocusEl) continue;
|
||||||
|
var r = el.getBoundingClientRect();
|
||||||
|
var dx = r.left + r.width / 2 - cx;
|
||||||
|
var dy = r.top + r.height / 2 - cy;
|
||||||
|
var valid = false, primary = 0, secondary = 0;
|
||||||
|
if (dir === "right" && dx > 6) { valid = true; primary = dx; secondary = Math.abs(dy); }
|
||||||
|
else if (dir === "left" && dx < -6) { valid = true; primary = -dx; secondary = Math.abs(dy); }
|
||||||
|
else if (dir === "down" && dy > 6) { valid = true; primary = dy; secondary = Math.abs(dx); }
|
||||||
|
else if (dir === "up" && dy < -6) { valid = true; primary = -dy; secondary = Math.abs(dx); }
|
||||||
|
if (valid) {
|
||||||
|
var score = primary + secondary * 2.2;
|
||||||
|
if (score < bestScore) { bestScore = score; best = el; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
g.__pwClearTvFocus = clearTvFocus;
|
||||||
|
g.__pwFocusFirst = function () {
|
||||||
|
var list = getFocusables();
|
||||||
|
if (list.length) setTvFocus(list[0]);
|
||||||
|
};
|
||||||
|
g.__pwRemoteKey = function (dir) {
|
||||||
|
if (dir === "ok") {
|
||||||
|
if (!currentFocusEl || !document.body.contains(currentFocusEl)) g.__pwFocusFirst();
|
||||||
|
if (currentFocusEl) currentFocusEl.click();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
var next = findNextFocusable(dir);
|
||||||
|
if (next) { setTvFocus(next); return true; }
|
||||||
|
if (dir === "down") { g.scrollBy({ top: 240, behavior: "smooth" }); return true; }
|
||||||
|
if (dir === "up") { g.scrollBy({ top: -240, behavior: "smooth" }); return true; }
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("DOMContentLoaded", function () {
|
||||||
|
try {
|
||||||
|
if (g.PwIcons && g.PwIcons.hydrate) g.PwIcons.hydrate(document.body);
|
||||||
|
} catch (_) {}
|
||||||
|
});
|
||||||
|
})(window);
|
||||||
@@ -0,0 +1,164 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
|
||||||
|
<title>PulseWall Validation Sandbox</title>
|
||||||
|
<style>
|
||||||
|
html, body, #pw-sandbox-host {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
background: #0a0f1d;
|
||||||
|
}
|
||||||
|
#pw-sandbox-frame {
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
border: 0;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="pw-sandbox-host"></div>
|
||||||
|
<script>
|
||||||
|
(function () {
|
||||||
|
var BASE_HREF = "https://appassets.androidplatform.net/assets/pulsewall/";
|
||||||
|
var activeErrors = [];
|
||||||
|
var activeFrame = null;
|
||||||
|
var activeTimer = null;
|
||||||
|
|
||||||
|
window.PulseWall = {
|
||||||
|
loadLib: function () { return Promise.resolve(); },
|
||||||
|
libs: [],
|
||||||
|
sendAction: function () {},
|
||||||
|
getDeviceProfile: function () { return window.__SANDBOX_PROFILE__ || {}; },
|
||||||
|
getTelemetry: function () { return {}; },
|
||||||
|
getDataContext: function () { return window.__PW_DATA__ || {}; }
|
||||||
|
};
|
||||||
|
|
||||||
|
function recordError(source, msg) {
|
||||||
|
activeErrors.push(String(source) + ": " + String(msg));
|
||||||
|
}
|
||||||
|
|
||||||
|
window.__pwOnStageError = function (source, msg) {
|
||||||
|
recordError(source, msg);
|
||||||
|
};
|
||||||
|
|
||||||
|
function buildStageDocument(rawHtml) {
|
||||||
|
var html = String(rawHtml || "");
|
||||||
|
var headInject =
|
||||||
|
'<base href="' + BASE_HREF + '" />' +
|
||||||
|
'<link rel="stylesheet" href="./pulsewall-tokens.css" />' +
|
||||||
|
'<link rel="stylesheet" href="./libs/tailwind-lite.min.css" />' +
|
||||||
|
'<script src="./vue.global.prod.js"><\/script>' +
|
||||||
|
'<script src="./libs/dayjs.min.js"><\/script>' +
|
||||||
|
'<script src="./libs/pw-icons.min.js"><\/script>' +
|
||||||
|
'<script src="./pw-lib-loader.js"><\/script>' +
|
||||||
|
'<script src="./pw-stage-bootstrap.js"><\/script>';
|
||||||
|
|
||||||
|
if (/<\s*!doctype\b|<\s*html\b/i.test(html)) {
|
||||||
|
if (/<\s*head\b[^>]*>/i.test(html)) {
|
||||||
|
return html.replace(/<\s*head\b[^>]*>/i, function (m) { return m + "\n" + headInject + "\n"; });
|
||||||
|
}
|
||||||
|
if (/<\s*html\b[^>]*>/i.test(html)) {
|
||||||
|
return html.replace(/<\s*html\b[^>]*>/i, function (m) { return m + "\n<head>" + headInject + "</head>\n"; });
|
||||||
|
}
|
||||||
|
return "<head>" + headInject + "</head>" + html;
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
'<!DOCTYPE html><html lang="zh-CN"><head>' +
|
||||||
|
'<meta charset="UTF-8" />' +
|
||||||
|
'<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />' +
|
||||||
|
headInject +
|
||||||
|
'<style>html,body{margin:0;padding:0;width:100%;min-height:100vh;background:#0a0f1d;color:#eef4ff;overflow-x:hidden;}</style>' +
|
||||||
|
'</head><body>' + html + '</body></html>'
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function teardownSandboxFrame() {
|
||||||
|
if (activeTimer) {
|
||||||
|
clearTimeout(activeTimer);
|
||||||
|
activeTimer = null;
|
||||||
|
}
|
||||||
|
if (activeFrame) {
|
||||||
|
var old = activeFrame;
|
||||||
|
activeFrame = null;
|
||||||
|
try {
|
||||||
|
var w = old.contentWindow;
|
||||||
|
if (w && typeof w.__pwPageDispose === "function") w.__pwPageDispose();
|
||||||
|
} catch (_) {}
|
||||||
|
try { old.src = "about:blank"; } catch (_) {}
|
||||||
|
try { if (old.parentNode) old.parentNode.removeChild(old); } catch (_) {}
|
||||||
|
}
|
||||||
|
var host = document.getElementById("pw-sandbox-host");
|
||||||
|
if (host) host.innerHTML = "";
|
||||||
|
}
|
||||||
|
|
||||||
|
window.__pwResetSandbox = teardownSandboxFrame;
|
||||||
|
|
||||||
|
window.__pwValidateB64 = function (payloadB64) {
|
||||||
|
teardownSandboxFrame();
|
||||||
|
activeErrors = [];
|
||||||
|
var taskId = "";
|
||||||
|
try {
|
||||||
|
var bytes = Uint8Array.from(atob(payloadB64), function (c) { return c.charCodeAt(0); });
|
||||||
|
var payload = JSON.parse(new TextDecoder("utf-8").decode(bytes));
|
||||||
|
taskId = payload.task_id || "";
|
||||||
|
window.__PW_DATA__ = payload.data_context || {};
|
||||||
|
window.__SANDBOX_PROFILE__ = payload.display_profile || {};
|
||||||
|
|
||||||
|
var host = document.getElementById("pw-sandbox-host");
|
||||||
|
var iframe = document.createElement("iframe");
|
||||||
|
iframe.id = "pw-sandbox-frame";
|
||||||
|
host.appendChild(iframe);
|
||||||
|
activeFrame = iframe;
|
||||||
|
|
||||||
|
var doc = iframe.contentDocument || (iframe.contentWindow && iframe.contentWindow.document);
|
||||||
|
doc.open();
|
||||||
|
doc.write(buildStageDocument(payload.html || ""));
|
||||||
|
doc.close();
|
||||||
|
|
||||||
|
activeTimer = setTimeout(function () {
|
||||||
|
var overflow = 0;
|
||||||
|
try {
|
||||||
|
var d = iframe.contentDocument;
|
||||||
|
var w = iframe.contentWindow;
|
||||||
|
var body = d && d.body;
|
||||||
|
var textLen = body ? (body.innerText || "").trim().length : 0;
|
||||||
|
var childCount = body ? body.querySelectorAll("*").length : 0;
|
||||||
|
if (childCount === 0 && textLen === 0) {
|
||||||
|
recordError("empty_dom", "Rendered canvas has no visible DOM nodes.");
|
||||||
|
}
|
||||||
|
if (d && w && w.innerWidth > 100) {
|
||||||
|
overflow = Math.max(0, d.documentElement.scrollWidth - w.innerWidth);
|
||||||
|
if (overflow > 20) {
|
||||||
|
recordError("layout_overflow", "Horizontal overflow +" + overflow + "px exceeds viewport width " + w.innerWidth + "px");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
recordError("sandbox_check_error", e && e.message ? e.message : String(e));
|
||||||
|
}
|
||||||
|
var ok = activeErrors.length === 0;
|
||||||
|
var errsJson = JSON.stringify(activeErrors);
|
||||||
|
// CRITICAL: Immediately destroy the validation iframe so ZERO timers/rAF/WebGL leak in background!
|
||||||
|
teardownSandboxFrame();
|
||||||
|
if (window.SandboxBridge && window.SandboxBridge.onValidationResult) {
|
||||||
|
window.SandboxBridge.onValidationResult(taskId, ok, errsJson, overflow);
|
||||||
|
}
|
||||||
|
}, 550);
|
||||||
|
} catch (e) {
|
||||||
|
recordError("sandbox_exception", e && e.message ? e.message : String(e));
|
||||||
|
var errsJson2 = JSON.stringify(activeErrors);
|
||||||
|
teardownSandboxFrame();
|
||||||
|
if (window.SandboxBridge && window.SandboxBridge.onValidationResult) {
|
||||||
|
window.SandboxBridge.onValidationResult(taskId, false, errsJson2, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/**
|
||||||
|
* vue v3.5.13
|
||||||
|
* (c) 2018-present Yuxi (Evan) You and Vue contributors
|
||||||
|
* @license MIT
|
||||||
|
**/var Vue=function(e){"use strict";var t,n;let r,i,l,s,o,a,c,u,d,p,f,h,m;function g(e){let t=Object.create(null);for(let n of e.split(","))t[n]=1;return e=>e in t}let y={},b=[],_=()=>{},S=()=>!1,x=e=>111===e.charCodeAt(0)&&110===e.charCodeAt(1)&&(e.charCodeAt(2)>122||97>e.charCodeAt(2)),C=e=>e.startsWith("onUpdate:"),k=Object.assign,T=(e,t)=>{let n=e.indexOf(t);n>-1&&e.splice(n,1)},N=Object.prototype.hasOwnProperty,w=(e,t)=>N.call(e,t),A=Array.isArray,E=e=>"[object Map]"===V(e),I=e=>"[object Set]"===V(e),R=e=>"[object Date]"===V(e),O=e=>"[object RegExp]"===V(e),P=e=>"function"==typeof e,M=e=>"string"==typeof e,L=e=>"symbol"==typeof e,$=e=>null!==e&&"object"==typeof e,D=e=>($(e)||P(e))&&P(e.then)&&P(e.catch),F=Object.prototype.toString,V=e=>F.call(e),B=e=>V(e).slice(8,-1),U=e=>"[object Object]"===V(e),j=e=>M(e)&&"NaN"!==e&&"-"!==e[0]&&""+parseInt(e,10)===e,H=g(",key,ref,ref_for,ref_key,onVnodeBeforeMount,onVnodeMounted,onVnodeBeforeUpdate,onVnodeUpdated,onVnodeBeforeUnmount,onVnodeUnmounted"),q=g("bind,cloak,else-if,else,for,html,if,model,on,once,pre,show,slot,text,memo"),W=e=>{let t=Object.create(null);return n=>t[n]||(t[n]=e(n))},K=/-(\w)/g,z=W(e=>e.replace(K,(e,t)=>t?t.toUpperCase():"")),J=/\B([A-Z])/g,G=W(e=>e.replace(J,"-$1").toLowerCase()),X=W(e=>e.charAt(0).toUpperCase()+e.slice(1)),Q=W(e=>e?`on${X(e)}`:""),Z=(e,t)=>!Object.is(e,t),Y=(e,...t)=>{for(let n=0;n<e.length;n++)e[n](...t)},ee=(e,t,n,r=!1)=>{Object.defineProperty(e,t,{configurable:!0,enumerable:!1,writable:r,value:n})},et=e=>{let t=parseFloat(e);return isNaN(t)?e:t},en=e=>{let t=M(e)?Number(e):NaN;return isNaN(t)?e:t},er=()=>r||(r="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{}),ei=g("Infinity,undefined,NaN,isFinite,isNaN,parseFloat,parseInt,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,Math,Number,Date,Array,Object,Boolean,String,RegExp,Map,Set,JSON,Intl,BigInt,console,Error,Symbol");function el(e){if(A(e)){let t={};for(let n=0;n<e.length;n++){let r=e[n],i=M(r)?ec(r):el(r);if(i)for(let e in i)t[e]=i[e]}return t}if(M(e)||$(e))return e}let es=/;(?![^(]*\))/g,eo=/:([^]+)/,ea=/\/\*[^]*?\*\//g;function ec(e){let t={};return e.replace(ea,"").split(es).forEach(e=>{if(e){let n=e.split(eo);n.length>1&&(t[n[0].trim()]=n[1].trim())}}),t}function eu(e){let t="";if(M(e))t=e;else if(A(e))for(let n=0;n<e.length;n++){let r=eu(e[n]);r&&(t+=r+" ")}else if($(e))for(let n in e)e[n]&&(t+=n+" ");return t.trim()}let ed=g("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,hgroup,h1,h2,h3,h4,h5,h6,nav,section,div,dd,dl,dt,figcaption,figure,picture,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,summary,template,blockquote,iframe,tfoot"),ep=g("svg,animate,animateMotion,animateTransform,circle,clipPath,color-profile,defs,desc,discard,ellipse,feBlend,feColorMatrix,feComponentTransfer,feComposite,feConvolveMatrix,feDiffuseLighting,feDisplacementMap,feDistantLight,feDropShadow,feFlood,feFuncA,feFuncB,feFuncG,feFuncR,feGaussianBlur,feImage,feMerge,feMergeNode,feMorphology,feOffset,fePointLight,feSpecularLighting,feSpotLight,feTile,feTurbulence,filter,foreignObject,g,hatch,hatchpath,image,line,linearGradient,marker,mask,mesh,meshgradient,meshpatch,meshrow,metadata,mpath,path,pattern,polygon,polyline,radialGradient,rect,set,solidcolor,stop,switch,symbol,text,textPath,title,tspan,unknown,use,view"),ef=g("annotation,annotation-xml,maction,maligngroup,malignmark,math,menclose,merror,mfenced,mfrac,mfraction,mglyph,mi,mlabeledtr,mlongdiv,mmultiscripts,mn,mo,mover,mpadded,mphantom,mprescripts,mroot,mrow,ms,mscarries,mscarry,msgroup,msline,mspace,msqrt,msrow,mstack,mstyle,msub,msubsup,msup,mtable,mtd,mtext,mtr,munder,munderover,none,semantics"),eh=g("area,base,br,col,embed,hr,img,input,link,meta,param,source,track,wbr"),em=g("itemscope,allowfullscreen,formnovalidate,ismap,nomodule,novalidate,readonly");function eg(e,t){if(e===t)return!0;let n=R(e),r=R(t);if(n||r)return!!n&&!!r&&e.getTime()===t.getTime();if(n=L(e),r=L(t),n||r)return e===t;if(n=A(e),r=A(t),n||r)return!!n&&!!r&&function(e,t){if(e.length!==t.length)return!1;let n=!0;for(let r=0;n&&r<e.length;r++)n=eg(e[r],t[r]);return n}(e,t);if(n=$(e),r=$(t),n||r){if(!n||!r||Object.keys(e).length!==Object.keys(t).length)return!1;for(let n in e){let r=e.hasOwnProperty(n),i=t.hasOwnProperty(n);if(r&&!i||!r&&i||!eg(e[n],t[n]))return!1}}return String(e)===String(t)}function ey(e,t){return e.findIndex(e=>eg(e,t))}let ev=e=>!!(e&&!0===e.__v_isRef),eb=e=>M(e)?e:null==e?"":A(e)||$(e)&&(e.toString===F||!P(e.toString))?ev(e)?eb(e.value):JSON.stringify(e,e_,2):String(eLine truncated
|
||||||
|
`,-1),e.hoists.length)){let e=[su,sd,sp,sf,sh].filter(e=>c.includes(e)).map(o8).join(", ");i(`const { ${e} } = _Vue
|
||||||
|
`,-1)}(function(e,t){if(!e.length)return;t.pure=!0;let{push:n,newline:r}=t;r();for(let i=0;i<e.length;i++){let l=e[i];l&&(n(`const _hoisted_${i+1} = `),ae(l,t),r())}t.pure=!1})(e.hoists,t),l(),i("return ")})(e,n);let h=(u?["_ctx","_push","_parent","_attrs"]:["_ctx","_cache"]).join(", ");if(i(`function ${u?"ssrRender":"render"}(${h}) {`),s(),f&&(i("with (_ctx) {"),s(),p&&(i(`const { ${d.map(o8).join(", ")} } = _Vue
|
||||||
|
`,-1),a())),e.components.length&&(o5(e.components,"component",n),(e.directives.length||e.temps>0)&&a()),e.directives.length&&(o5(e.directives,"directive",n),e.temps>0&&a()),e.temps>0){i("let ");for(let t=0;t<e.temps;t++)i(`${t>0?", ":""}_temp${t}`)}return(e.components.length||e.directives.length||e.temps)&&(i(`
|
||||||
|
`,0),a()),u||i("return "),e.codegenNode?ae(e.codegenNode,n):i("null"),f&&(o(),i("}")),o(),i("}"),{ast:e,code:n.code,preamble:"",map:n.map?n.map.toJSON():void 0}}(l,i)}(e,k({},aU,t,{nodeTransforms:[aG,...aX,...t.nodeTransforms||[]],directiveTransforms:k({},aQ,t.directiveTransforms||{}),transformHoist:null}))}(e,i),s=Function(l)();return s._rc=!0,aZ[n]=s}return iU(aY),e.BaseTransition=n_,e.BaseTransitionPropsValidators=ny,e.Comment=io,e.DeprecationTypes=null,e.EffectScope=ex,e.ErrorCodes={SETUP_FUNCTION:0,0:"SETUP_FUNCTION",RENDER_FUNCTION:1,1:"RENDER_FUNCTION",NATIVE_EVENT_HANDLER:5,5:"NATIVE_EVENT_HANDLER",COMPONENT_EVENT_HANDLER:6,6:"COMPONENT_EVENT_HANDLER",VNODE_HOOK:7,7:"VNODE_HOOK",DIRECTIVE_HOOK:8,8:"DIRECTIVE_HOOK",TRANSITION_HOOK:9,9:"TRANSITION_HOOK",APP_ERROR_HANDLER:10,10:"APP_ERROR_HANDLER",APP_WARN_HANDLER:11,11:"APP_WARN_HANDLER",FUNCTION_REF:12,12:"FUNCTION_REF",ASYNC_COMPONENT_LOADER:13,13:"ASYNC_COMPONENT_LOADER",SCHEDULER:14,14:"SCHEDULER",COMPONENT_UPDATE:15,15:"COMPONENT_UPDATE",APP_UNMOUNT_CLEANUP:16,16:"APP_UNMOUNT_CLEANUP"},e.ErrorTypeStrings=null,e.Fragment=il,e.KeepAlive={name:"KeepAlive",__isKeepAlive:!0,props:{include:[String,RegExp,Array],exclude:[String,RegExp,Array],max:[String,Number]},setup(e,{slots:t}){let n=iL(),r=n.ctx,i=new Map,l=new Set,s=null,o=n.suspense,{renderer:{p:a,m:c,um:u,o:{createElement:d}}}=r,p=d("div");function f(e){nG(e),u(e,n,o,!0)}function h(e){i.forEach((t,n)=>{let r=iK(t.type);r&&!e(r)&&m(n)})}function m(e){let t=i.get(e);!t||s&&ib(t,s)?s&&nG(s):f(t),i.delete(e),l.delete(e)}r.activate=(e,t,n,r,i)=>{let l=e.component;c(e,t,n,0,o),a(l.vnode,e,t,n,l,o,r,e.slotScopeIds,i),rB(()=>{l.isDeactivated=!1,l.a&&Y(l.a);let t=e.props&&e.props.onVnodeMounted;t&&iR(t,l.parent,e)},o)},r.deactivate=e=>{let t=e.component;rz(t.m),rz(t.a),c(e,p,null,1,o),rB(()=>{t.da&&Y(t.da);let n=e.props&&e.props.onVnodeUnmounted;n&&iR(n,t.parent,e),t.isDeactivated=!0},o)},rX(()=>[e.include,e.exclude],([e,t])=>{e&&h(t=>nW(e,t)),t&&h(e=>!nW(t,e))},{flush:"post",deep:!0});let g=null,y=()=>{null!=g&&(r5(n.subTree.type)?rB(()=>{i.set(g,nX(n.subTree))},n.subTree.suspense):i.set(g,nX(n.subTree)))};return n0(y),n2(y),n3(()=>{i.forEach(e=>{let{subTree:t,suspense:r}=n,i=nX(t);if(e.type===i.type&&e.key===i.key){nG(i);let e=i.component.da;e&&rB(e,r);return}f(e)})}),()=>{if(g=null,!t.default)return s=null;let n=t.default(),r=n[0];if(n.length>1)return s=null,n;if(!iv(r)||!(4&r.shapeFlag)&&!(128&r.shapeFlag))return s=null,r;let o=nX(r);if(o.type===io)return s=null,o;let a=o.type,c=iK(nj(o)?o.type.__asyncResolved||{}:a),{include:u,exclude:d,max:p}=e;if(u&&(!c||!nW(u,c))||d&&c&&nW(d,c))return o.shapeFlag&=-257,s=o,r;let f=null==o.key?a:o.key,h=i.get(f);return o.el&&(o=iT(o),128&r.shapeFlag&&(r.ssContent=o)),g=f,h?(o.el=h.el,o.component=h.component,o.transition&&nT(o,o.transition),o.shapeFlag|=512,l.delete(f),l.add(f)):(l.add(f),p&&l.size>parseInt(p,10)&&m(l.values().next().value)),o.shapeFlag|=256,s=o,r5(r.type)?r:o}}},e.ReactiveEffect=ek,e.Static=ia,e.Suspense={name:"Suspense",__isSuspense:!0,process(e,t,n,r,i,l,s,o,a,c){if(null==e)(function(e,t,n,r,i,l,s,o,a){let{p:c,o:{createElement:u}}=a,d=u("div"),p=e.suspense=ie(e,i,r,t,d,n,l,s,o,a);c(null,p.pendingBranch=e.ssContent,d,null,r,p,l,s),p.deps>0?(r7(e,"onPending"),r7(e,"onFallback"),c(null,e.ssFallback,t,n,r,null,l,s),ii(p,e.ssFallback)):p.resolve(!1,!0)})(t,n,r,i,l,s,o,a,c);else{if(l&&l.deps>0&&!e.suspense.isInFallback){t.suspense=e.suspense,t.suspense.vnode=t,t.el=e.el;return}(function(e,t,n,r,i,l,s,o,{p:a,um:c,o:{createElement:u}}){let d=t.suspense=e.suspense;d.vnode=t,t.el=e.el;let p=t.ssContent,f=t.ssFallback,{activeBranch:h,pendingBranch:m,isInFallback:g,isHydrating:y}=d;if(m)d.pendingBranch=p,ib(p,m)?(a(m,p,d.hiddenContainer,null,i,d,l,s,o),d.deps<=0?d.resolve():g&&!y&&(a(h,f,n,r,i,null,l,s,o),ii(d,f))):(d.pendingId=r9++,y?(d.isHydrating=!1,d.activeBranch=m):c(m,i,d),d.deps=0,d.effects.length=0,d.hiddenContainer=u("div"),g?(a(null,p,d.hiddenContainer,null,i,d,l,s,o),d.deps<=0?d.resolve():(a(h,f,n,r,i,null,l,s,o),ii(d,f))):h&&ib(p,h)?(a(h,p,n,r,i,d,l,s,o),d.resolve(!0)):(a(null,p,d.hiddenContainer,null,i,d,l,s,o),d.deps<=0&&d.resolve()));else if(h&&ib(p,h))a(h,p,n,r,i,d,l,s,o),ii(d,p);else if(r7(t,"onPending"),d.pendingBranch=p,512&p.shapeFlag?d.pendingId=p.component.suspenseId:d.pendingId=r9++,a(null,p,d.hiddenContainer,null,i,d,l,s,o),d.deps<=0)d.resolve();else{let{timeout:e,pendingId:t}=d;e>0?setTimeout(()=>{d.pendingId===t&&d.fallback(f)},e):0===e&&d.fallback(f)}})(e,t,n,r,i,s,o,a,c)}},hydrate:function(e,t,n,r,i,l,s,o,a){let c=t.suspense=ie(t,r,n,e.parentNode,document.createElement("div"),null,i,l,s,o,!0),u=a(e,c.pendingBranch=t.ssContent,n,c,l,s);return 0===c.deps&&c.resolve(!1,!0),u},normalize:function(e){let{shapeFlag:t,children:n}=e,r=32&t;e.ssContent=it(r?n.default:n),e.ssFallback=r?it(n.fallback):iC(io)}},e.Teleport=nc,e.Text=is,e.TrackOpTypes={GET:"get",HAS:"has",ITERATE:"iterate"},e.Transition=i8,e.TransitionGroup=lF,e.TriggerOpTypes=
Line truncated
|
||||||
@@ -0,0 +1,965 @@
|
|||||||
|
package com.pulsewall.app
|
||||||
|
|
||||||
|
import android.annotation.SuppressLint
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.drawable.GradientDrawable
|
||||||
|
import android.graphics.drawable.StateListDrawable
|
||||||
|
import android.os.Bundle
|
||||||
|
import android.util.Base64
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.KeyEvent
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.view.WindowInsets
|
||||||
|
import android.view.WindowInsetsController
|
||||||
|
import android.view.WindowManager
|
||||||
|
import android.webkit.JavascriptInterface
|
||||||
|
import android.webkit.WebResourceRequest
|
||||||
|
import android.webkit.WebResourceResponse
|
||||||
|
import android.webkit.WebView
|
||||||
|
import android.webkit.WebViewClient
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.FrameLayout
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ScrollView
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
|
import androidx.webkit.WebViewAssetLoader
|
||||||
|
import com.pulsewall.app.alert.NativeAlertController
|
||||||
|
import com.pulsewall.app.config.AppPrefs
|
||||||
|
import com.pulsewall.app.network.HubDiscoveryClient
|
||||||
|
import com.pulsewall.app.network.HubMessageListener
|
||||||
|
import com.pulsewall.app.network.HubWebSocketClient
|
||||||
|
import com.pulsewall.app.ota.AppUpdateManager
|
||||||
|
import com.pulsewall.app.sentinel.OpenAiRepairSentinel
|
||||||
|
import com.pulsewall.app.service.PulseWallKeepAliveService
|
||||||
|
import com.pulsewall.app.telemetry.DeviceTelemetryCollector
|
||||||
|
import kotlinx.coroutines.CompletableDeferred
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.SupervisorJob
|
||||||
|
import kotlinx.coroutines.cancel
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import kotlinx.coroutines.withTimeoutOrNull
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
|
data class SandboxValidationOutcome(
|
||||||
|
val ok: Boolean,
|
||||||
|
val errors: List<String>,
|
||||||
|
val overflowPx: Int
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ActiveRenderContext(
|
||||||
|
val taskId: String,
|
||||||
|
val snapshotId: String,
|
||||||
|
val mode: String,
|
||||||
|
val title: String,
|
||||||
|
var html: String,
|
||||||
|
var dataContext: JSONObject
|
||||||
|
)
|
||||||
|
|
||||||
|
class MainActivity : AppCompatActivity(), HubMessageListener {
|
||||||
|
|
||||||
|
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Main)
|
||||||
|
private lateinit var prefs: AppPrefs
|
||||||
|
private lateinit var telemetry: DeviceTelemetryCollector
|
||||||
|
private lateinit var alertController: NativeAlertController
|
||||||
|
private lateinit var wsClient: HubWebSocketClient
|
||||||
|
private lateinit var updateManager: AppUpdateManager
|
||||||
|
private val sentinel = OpenAiRepairSentinel()
|
||||||
|
|
||||||
|
private lateinit var mainWebView: WebView
|
||||||
|
private lateinit var sandboxWebView: WebView
|
||||||
|
private lateinit var statusPill: TextView
|
||||||
|
|
||||||
|
private var mainPageReady = false
|
||||||
|
private var sandboxPageReady = false
|
||||||
|
private var sandboxLoadWaiter: CompletableDeferred<Boolean>? = null
|
||||||
|
private val sandboxMutex = Mutex()
|
||||||
|
private var wsConnected = false
|
||||||
|
private var lastConnDetail = "正在连接中心桥..."
|
||||||
|
private var initialOtaChecked = false
|
||||||
|
private var autoDiscoveryTried = false
|
||||||
|
private var isShowingCustomCanvas = false
|
||||||
|
private var lastBackPressMs = 0L
|
||||||
|
|
||||||
|
private val sandboxWaiters = ConcurrentHashMap<String, CompletableDeferred<SandboxValidationOutcome>>()
|
||||||
|
private val pendingClarificationTasks = ConcurrentHashMap<String, ActiveRenderContext>()
|
||||||
|
private var activeRender: ActiveRenderContext? = null
|
||||||
|
private var lastRuntimeRepairAtMs = 0L
|
||||||
|
|
||||||
|
@SuppressLint("SetJavaScriptEnabled")
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
|
setShowWhenLocked(true)
|
||||||
|
setTurnScreenOn(true)
|
||||||
|
|
||||||
|
prefs = AppPrefs(this)
|
||||||
|
telemetry = DeviceTelemetryCollector(this)
|
||||||
|
alertController = NativeAlertController(this) { alertId, interactionId, presetId, label, customText ->
|
||||||
|
sendInteractionReply(alertId, interactionId, presetId, label, customText)
|
||||||
|
}
|
||||||
|
updateManager = AppUpdateManager(
|
||||||
|
activity = this,
|
||||||
|
prefs = prefs,
|
||||||
|
scope = scope,
|
||||||
|
rootAvailableSupplier = { telemetry.isRootAvailable() }
|
||||||
|
)
|
||||||
|
|
||||||
|
val root = FrameLayout(this).apply {
|
||||||
|
setBackgroundColor(Color.parseColor("#0A0F1D"))
|
||||||
|
}
|
||||||
|
|
||||||
|
val assetLoader = WebViewAssetLoader.Builder()
|
||||||
|
.addPathHandler("/assets/", WebViewAssetLoader.AssetsPathHandler(this))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
// 1. Offscreen Validation Sandbox WebView (parked GONE + paused + about:blank when idle -> 0% CPU / 0MB GL)
|
||||||
|
sandboxWebView = WebView(this).apply {
|
||||||
|
alpha = 0f
|
||||||
|
visibility = View.GONE
|
||||||
|
isClickable = false
|
||||||
|
isFocusable = false
|
||||||
|
settings.javaScriptEnabled = true
|
||||||
|
settings.domStorageEnabled = true
|
||||||
|
addJavascriptInterface(SandboxJsBridge(), "SandboxBridge")
|
||||||
|
webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
return assetLoader.shouldInterceptRequest(request.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageFinished(view: WebView?, url: String?) {
|
||||||
|
if (url != null && url.contains("sandbox.html")) {
|
||||||
|
sandboxPageReady = true
|
||||||
|
sandboxLoadWaiter?.complete(true)
|
||||||
|
} else {
|
||||||
|
sandboxPageReady = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadUrl("about:blank")
|
||||||
|
onPause()
|
||||||
|
}
|
||||||
|
root.addView(
|
||||||
|
sandboxWebView,
|
||||||
|
FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 2. Main WebView Canvas
|
||||||
|
mainWebView = WebView(this).apply {
|
||||||
|
setBackgroundColor(Color.parseColor("#0A0F1D"))
|
||||||
|
settings.javaScriptEnabled = true
|
||||||
|
settings.domStorageEnabled = true
|
||||||
|
addJavascriptInterface(MainJsBridge(), "AndroidBridge")
|
||||||
|
webViewClient = object : WebViewClient() {
|
||||||
|
override fun shouldInterceptRequest(view: WebView, request: WebResourceRequest): WebResourceResponse? {
|
||||||
|
return assetLoader.shouldInterceptRequest(request.url)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onPageFinished(view: WebView?, url: String?) {
|
||||||
|
mainPageReady = true
|
||||||
|
pushStatusToWebView()
|
||||||
|
if (prefs.lastHealthyHtml.isNotBlank()) {
|
||||||
|
mountHtmlOnMain(
|
||||||
|
ActiveRenderContext(
|
||||||
|
taskId = "restored",
|
||||||
|
snapshotId = prefs.lastHealthySnapshotId.ifBlank { "restored" },
|
||||||
|
mode = "full",
|
||||||
|
title = "Restored",
|
||||||
|
html = prefs.lastHealthyHtml,
|
||||||
|
dataContext = JSONObject()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
loadUrl("https://appassets.androidplatform.net/assets/pulsewall/host.html")
|
||||||
|
}
|
||||||
|
root.addView(
|
||||||
|
mainWebView,
|
||||||
|
FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||||
|
)
|
||||||
|
|
||||||
|
// 3. Unbreakable Native Floating Status Pill (TV IR Remote Focusable + Touch Tap)
|
||||||
|
val pillFocused = GradientDrawable().apply {
|
||||||
|
setColor(Color.parseColor("#E61E3A5F"))
|
||||||
|
cornerRadius = dp(20).toFloat()
|
||||||
|
setStroke(dp(3), Color.parseColor("#FACC15"))
|
||||||
|
}
|
||||||
|
val pillNormal = GradientDrawable().apply {
|
||||||
|
setColor(Color.parseColor("#CC162038"))
|
||||||
|
cornerRadius = dp(20).toFloat()
|
||||||
|
setStroke(dp(1), Color.parseColor("#4438BDF8"))
|
||||||
|
}
|
||||||
|
val pillBg = StateListDrawable().apply {
|
||||||
|
addState(intArrayOf(android.R.attr.state_focused), pillFocused)
|
||||||
|
addState(intArrayOf(android.R.attr.state_pressed), pillFocused)
|
||||||
|
addState(intArrayOf(), pillNormal)
|
||||||
|
}
|
||||||
|
statusPill = TextView(this).apply {
|
||||||
|
text = "● 未连接 · ${prefs.deviceName} · ⚙ (MENU)"
|
||||||
|
isFocusable = true
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
textSize = 13f
|
||||||
|
val hPad = dp(14)
|
||||||
|
val vPad = dp(8)
|
||||||
|
setPadding(hPad, vPad, hPad, vPad)
|
||||||
|
background = pillBg
|
||||||
|
setOnClickListener { showSettingsDialog() }
|
||||||
|
}
|
||||||
|
val pillLp = FrameLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT,
|
||||||
|
Gravity.TOP or Gravity.END
|
||||||
|
).apply {
|
||||||
|
topMargin = dp(34)
|
||||||
|
marginEnd = dp(12)
|
||||||
|
}
|
||||||
|
root.addView(statusPill, pillLp)
|
||||||
|
setContentView(root)
|
||||||
|
applyImmersiveFullscreen()
|
||||||
|
|
||||||
|
runCatching {
|
||||||
|
startForegroundService(Intent(this, PulseWallKeepAliveService::class.java))
|
||||||
|
}
|
||||||
|
|
||||||
|
wsClient = HubWebSocketClient(
|
||||||
|
prefs = prefs,
|
||||||
|
helloSupplier = { telemetry.collectHelloPayload(prefs.deviceId, prefs.deviceName) },
|
||||||
|
telemetrySupplier = { telemetry.collectTelemetryPayload() },
|
||||||
|
listener = this
|
||||||
|
)
|
||||||
|
wsClient.start()
|
||||||
|
|
||||||
|
// If still on default placeholder IP, proactively scan LAN UDP 8766 to auto-discover Hub
|
||||||
|
if (prefs.hubWsUrl == "ws://192.168.1.100:8765") {
|
||||||
|
runLanAutoDiscovery(silentIfNotFound = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyImmersiveFullscreen() {
|
||||||
|
runCatching {
|
||||||
|
window.setDecorFitsSystemWindows(false)
|
||||||
|
window.insetsController?.let { ctrl ->
|
||||||
|
ctrl.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
|
||||||
|
ctrl.systemBarsBehavior = WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||||
|
super.onWindowFocusChanged(hasFocus)
|
||||||
|
if (hasFocus) {
|
||||||
|
applyImmersiveFullscreen()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||||
|
if (event.action == KeyEvent.ACTION_DOWN) {
|
||||||
|
when (event.keyCode) {
|
||||||
|
KeyEvent.KEYCODE_MENU,
|
||||||
|
KeyEvent.KEYCODE_SETTINGS,
|
||||||
|
KeyEvent.KEYCODE_INFO,
|
||||||
|
KeyEvent.KEYCODE_F1 -> {
|
||||||
|
showSettingsDialog()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyEvent.KEYCODE_BACK -> {
|
||||||
|
if (isShowingCustomCanvas) {
|
||||||
|
restoreHomeScreen(clearSavedSnapshot = true)
|
||||||
|
Toast.makeText(this, "已关闭动态页并返回默认首页", Toast.LENGTH_SHORT).show()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (now - lastBackPressMs > 2000L) {
|
||||||
|
lastBackPressMs = now
|
||||||
|
Toast.makeText(this, "再按一次返回键退出 PulseWall", Toast.LENGTH_SHORT).show()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
KeyEvent.KEYCODE_DPAD_UP,
|
||||||
|
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||||
|
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||||
|
KeyEvent.KEYCODE_DPAD_RIGHT,
|
||||||
|
KeyEvent.KEYCODE_DPAD_CENTER,
|
||||||
|
KeyEvent.KEYCODE_ENTER -> {
|
||||||
|
if (statusPill.visibility == View.VISIBLE && statusPill.hasFocus()) {
|
||||||
|
if (event.keyCode == KeyEvent.KEYCODE_DPAD_CENTER || event.keyCode == KeyEvent.KEYCODE_ENTER) {
|
||||||
|
showSettingsDialog()
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (event.keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
|
||||||
|
mainWebView.requestFocus()
|
||||||
|
mainWebView.evaluateJavascript("window.__pwFocusFirst && window.__pwFocusFirst();", null)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
} else if (mainPageReady) {
|
||||||
|
val dir = when (event.keyCode) {
|
||||||
|
KeyEvent.KEYCODE_DPAD_UP -> "up"
|
||||||
|
KeyEvent.KEYCODE_DPAD_DOWN -> "down"
|
||||||
|
KeyEvent.KEYCODE_DPAD_LEFT -> "left"
|
||||||
|
KeyEvent.KEYCODE_DPAD_RIGHT -> "right"
|
||||||
|
else -> "ok"
|
||||||
|
}
|
||||||
|
mainWebView.evaluateJavascript("window.__pwRemoteKey && window.__pwRemoteKey('$dir');", null)
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return super.dispatchKeyEvent(event)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runLanAutoDiscovery(silentIfNotFound: Boolean) {
|
||||||
|
if (!silentIfNotFound) {
|
||||||
|
Toast.makeText(this, "正在扫描局域网 PulseWall 中心桥 (UDP 8766)...", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
scope.launch {
|
||||||
|
val hubs = HubDiscoveryClient.discover(timeoutMs = 1800)
|
||||||
|
if (hubs.isNotEmpty()) {
|
||||||
|
val best = hubs.first()
|
||||||
|
prefs.hubWsUrl = best.wsUrl
|
||||||
|
lastConnDetail = "已自动发现中心桥: ${best.wsUrl},正在连接..."
|
||||||
|
pushStatusToWebView()
|
||||||
|
wsClient.reconnect()
|
||||||
|
Toast.makeText(this@MainActivity, "已自动发现中心桥: ${best.wsUrl}", Toast.LENGTH_LONG).show()
|
||||||
|
} else if (!silentIfNotFound) {
|
||||||
|
Toast.makeText(
|
||||||
|
this@MainActivity,
|
||||||
|
"未自动发现中心桥,请确认服务器已运行 ./hub/run_hub.sh 且放行 8765/8766 端口",
|
||||||
|
Toast.LENGTH_LONG
|
||||||
|
).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConfigurationChanged(newConfig: Configuration) {
|
||||||
|
super.onConfigurationChanged(newConfig)
|
||||||
|
pushStatusToWebView()
|
||||||
|
Thread {
|
||||||
|
val tele = telemetry.collectTelemetryPayload()
|
||||||
|
wsClient.sendFrame("device.telemetry", tele)
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun updateStatusPillText() {
|
||||||
|
val dot = if (wsConnected) "🟢 已连接" else "🟠 未连接"
|
||||||
|
statusPill.text = "$dot · ${prefs.deviceName} · ⚙ (MENU)"
|
||||||
|
if (isShowingCustomCanvas) {
|
||||||
|
if (statusPill.hasFocus()) {
|
||||||
|
mainWebView.requestFocus()
|
||||||
|
}
|
||||||
|
statusPill.visibility = View.GONE
|
||||||
|
} else {
|
||||||
|
statusPill.visibility = View.VISIBLE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onConnectionChanged(connected: Boolean, detail: String) {
|
||||||
|
wsConnected = connected
|
||||||
|
if (detail.isNotBlank()) {
|
||||||
|
lastConnDetail = detail
|
||||||
|
}
|
||||||
|
runOnUiThread {
|
||||||
|
updateStatusPillText()
|
||||||
|
pushStatusToWebView()
|
||||||
|
if (connected && !initialOtaChecked) {
|
||||||
|
initialOtaChecked = true
|
||||||
|
updateManager.checkForUpdate(silentIfLatest = true)
|
||||||
|
} else if (!connected && !autoDiscoveryTried) {
|
||||||
|
autoDiscoveryTried = true
|
||||||
|
runLanAutoDiscovery(silentIfNotFound = true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onHubFrame(type: String, payload: JSONObject) {
|
||||||
|
when (type) {
|
||||||
|
"config.push" -> {
|
||||||
|
prefs.applyHubConfigPush(payload)
|
||||||
|
wsClient.rescheduleTelemetry()
|
||||||
|
}
|
||||||
|
|
||||||
|
"ota.available" -> {
|
||||||
|
updateManager.handleHubPush(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
"feed.push" -> {
|
||||||
|
val sound = payload.optString("sound", "ding")
|
||||||
|
if (sound != "none") {
|
||||||
|
alertController.playSound(sound)
|
||||||
|
}
|
||||||
|
runOnUiThread {
|
||||||
|
val escaped = JSONObject.quote(payload.toString())
|
||||||
|
mainWebView.evaluateJavascript("window.__pwPushFeed && window.__pwPushFeed($escaped);", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"alert.trigger" -> {
|
||||||
|
alertController.showAlert(payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
"alert.dismiss" -> {
|
||||||
|
val aid = payload.optString("alert_id", "").ifBlank { null }
|
||||||
|
alertController.dismiss(aid)
|
||||||
|
}
|
||||||
|
|
||||||
|
"render.apply" -> {
|
||||||
|
val ctx = ActiveRenderContext(
|
||||||
|
taskId = payload.optString("task_id", "task_${System.currentTimeMillis()}"),
|
||||||
|
snapshotId = payload.optString("snapshot_id", "snap_${System.currentTimeMillis()}"),
|
||||||
|
mode = payload.optString("mode", "full"),
|
||||||
|
title = payload.optString("title", ""),
|
||||||
|
html = payload.optString("html", ""),
|
||||||
|
dataContext = payload.optJSONObject("data_context") ?: JSONObject()
|
||||||
|
)
|
||||||
|
scope.launch { runRenderPipeline(ctx, trigger = "initial_render", upstreamAnswers = null) }
|
||||||
|
}
|
||||||
|
|
||||||
|
"render.rollback" -> {
|
||||||
|
val snapId = payload.optString("snapshot_id", "rollback")
|
||||||
|
val html = payload.optString("html", "")
|
||||||
|
if (snapId == "home" || html.isBlank()) {
|
||||||
|
restoreHomeScreen(clearSavedSnapshot = true)
|
||||||
|
} else {
|
||||||
|
val ctx = ActiveRenderContext("rollback", snapId, "full", "Rollback", html, JSONObject())
|
||||||
|
mountHtmlOnMain(ctx)
|
||||||
|
prefs.lastHealthySnapshotId = snapId
|
||||||
|
prefs.lastHealthyHtml = html
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"render.home" -> {
|
||||||
|
restoreHomeScreen(clearSavedSnapshot = true)
|
||||||
|
}
|
||||||
|
|
||||||
|
"clarification.answer" -> {
|
||||||
|
val taskId = payload.optString("task_id", "")
|
||||||
|
val pending = pendingClarificationTasks.remove(taskId)
|
||||||
|
val updatedHtml = payload.optString("updated_html", "").ifBlank { null }
|
||||||
|
val updatedData = payload.optJSONObject("updated_data")
|
||||||
|
val answers = payload.optJSONObject("answers") ?: JSONObject()
|
||||||
|
|
||||||
|
if (pending != null) {
|
||||||
|
if (updatedData != null && updatedData.length() > 0) {
|
||||||
|
val keys = updatedData.keys()
|
||||||
|
while (keys.hasNext()) {
|
||||||
|
val k = keys.next()
|
||||||
|
pending.dataContext.put(k, updatedData.get(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (updatedHtml != null) {
|
||||||
|
pending.html = updatedHtml
|
||||||
|
scope.launch { runRenderPipeline(pending, trigger = "clarification_retry", upstreamAnswers = null) }
|
||||||
|
} else {
|
||||||
|
scope.launch { runRenderPipeline(pending, trigger = "clarification_retry", upstreamAnswers = answers) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun runRenderPipeline(
|
||||||
|
ctx: ActiveRenderContext,
|
||||||
|
trigger: String,
|
||||||
|
upstreamAnswers: JSONObject?
|
||||||
|
) {
|
||||||
|
val aiCfg = prefs.getRepairAiConfig()
|
||||||
|
val displayProfile = withContext(Dispatchers.Default) { telemetry.collectDisplayProfile() }
|
||||||
|
var candidateHtml = ctx.html
|
||||||
|
var attempts = 0
|
||||||
|
var lastFixSummary = ""
|
||||||
|
var lastErrors: List<String> = emptyList()
|
||||||
|
|
||||||
|
// If upstream answered a clarification, let end-side Repair AI integrate the answer first
|
||||||
|
if (upstreamAnswers != null && aiCfg.enabled) {
|
||||||
|
val dec = sentinel.diagnoseAndRepair(
|
||||||
|
cfg = aiCfg,
|
||||||
|
currentHtml = candidateHtml,
|
||||||
|
errors = listOf("Apply upstream clarification answers and complete the template."),
|
||||||
|
displayProfile = displayProfile,
|
||||||
|
dataContext = ctx.dataContext,
|
||||||
|
upstreamAnswers = upstreamAnswers
|
||||||
|
)
|
||||||
|
if (dec.action == "fix_locally" && !dec.fixedHtml.isNullOrBlank()) {
|
||||||
|
candidateHtml = dec.fixedHtml
|
||||||
|
lastFixSummary = dec.fixSummary
|
||||||
|
attempts++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val maxLoops = if (aiCfg.enabled) aiCfg.maxRetries + 1 else 1
|
||||||
|
for (loopIdx in 0 until maxLoops) {
|
||||||
|
val check = validateInOffscreenSandbox(ctx.taskId, candidateHtml, ctx.dataContext, displayProfile)
|
||||||
|
if (check.ok) {
|
||||||
|
ctx.html = candidateHtml
|
||||||
|
activeRender = ctx
|
||||||
|
prefs.lastHealthySnapshotId = ctx.snapshotId
|
||||||
|
prefs.lastHealthyHtml = candidateHtml
|
||||||
|
mountHtmlOnMain(ctx)
|
||||||
|
|
||||||
|
val status = if (attempts > 0) "rendered_after_local_fix" else "rendered"
|
||||||
|
sendRenderResult(ctx, trigger, status, attempts, candidateHtml, lastFixSummary, JSONArray(), emptyList())
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
lastErrors = check.errors
|
||||||
|
if (!aiCfg.enabled || loopIdx >= aiCfg.maxRetries) {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
|
||||||
|
val decision = sentinel.diagnoseAndRepair(
|
||||||
|
cfg = aiCfg,
|
||||||
|
currentHtml = candidateHtml,
|
||||||
|
errors = lastErrors,
|
||||||
|
displayProfile = displayProfile,
|
||||||
|
dataContext = ctx.dataContext
|
||||||
|
)
|
||||||
|
|
||||||
|
when (decision.action) {
|
||||||
|
"fix_locally" -> {
|
||||||
|
if (!decision.fixedHtml.isNullOrBlank()) {
|
||||||
|
candidateHtml = decision.fixedHtml
|
||||||
|
lastFixSummary = decision.fixSummary
|
||||||
|
attempts++
|
||||||
|
} else {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"ask_upstream" -> {
|
||||||
|
ctx.html = candidateHtml
|
||||||
|
pendingClarificationTasks[ctx.taskId] = ctx
|
||||||
|
sendRenderResult(
|
||||||
|
ctx = ctx,
|
||||||
|
trigger = trigger,
|
||||||
|
status = "needs_clarification",
|
||||||
|
attempts = attempts,
|
||||||
|
finalHtml = null,
|
||||||
|
fixSummary = decision.fixSummary,
|
||||||
|
questions = decision.clarificationQuestions,
|
||||||
|
errors = lastErrors
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
else -> {
|
||||||
|
lastErrors = lastErrors + listOf("RepairSentinel: ${decision.errorMessage}")
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fallback: keep/rollback last healthy snapshot
|
||||||
|
sendRenderResult(ctx, trigger, "failed_rolled_back", attempts, null, lastFixSummary, JSONArray(), lastErrors)
|
||||||
|
Toast.makeText(this, "页面校验未通过,已保持上一健康版本", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun validateInOffscreenSandbox(
|
||||||
|
taskId: String,
|
||||||
|
html: String,
|
||||||
|
dataContext: JSONObject,
|
||||||
|
displayProfile: JSONObject
|
||||||
|
): SandboxValidationOutcome {
|
||||||
|
if (html.isBlank()) {
|
||||||
|
return SandboxValidationOutcome(false, listOf("Empty HTML payload"), 0)
|
||||||
|
}
|
||||||
|
return sandboxMutex.withLock {
|
||||||
|
val deferred = CompletableDeferred<SandboxValidationOutcome>()
|
||||||
|
sandboxWaiters[taskId] = deferred
|
||||||
|
try {
|
||||||
|
// Wake sandbox WebView ONLY for the brief validation window
|
||||||
|
val loadDeferred = CompletableDeferred<Boolean>()
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
sandboxPageReady = false
|
||||||
|
sandboxLoadWaiter = loadDeferred
|
||||||
|
sandboxWebView.visibility = View.INVISIBLE
|
||||||
|
sandboxWebView.onResume()
|
||||||
|
sandboxWebView.loadUrl("https://appassets.androidplatform.net/assets/pulsewall/sandbox.html")
|
||||||
|
}
|
||||||
|
val loaded = withTimeoutOrNull(2500L) { loadDeferred.await() } ?: false
|
||||||
|
if (!loaded) {
|
||||||
|
return@withLock SandboxValidationOutcome(true, emptyList(), 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
val payload = JSONObject().apply {
|
||||||
|
put("task_id", taskId)
|
||||||
|
put("html", html)
|
||||||
|
put("data_context", dataContext)
|
||||||
|
put("display_profile", displayProfile)
|
||||||
|
}
|
||||||
|
val b64 = Base64.encodeToString(payload.toString().toByteArray(Charsets.UTF_8), Base64.NO_WRAP)
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
sandboxWebView.evaluateJavascript("window.__pwValidateB64 && window.__pwValidateB64('$b64');", null)
|
||||||
|
}
|
||||||
|
|
||||||
|
val res = withTimeoutOrNull(4000L) { deferred.await() }
|
||||||
|
res ?: SandboxValidationOutcome(false, listOf("Sandbox validation timed out (>4s)"), 0)
|
||||||
|
} finally {
|
||||||
|
sandboxWaiters.remove(taskId)
|
||||||
|
sandboxLoadWaiter = null
|
||||||
|
// CRITICAL: Always unload & freeze sandbox immediately after validation -> 0% background CPU/GL!
|
||||||
|
withContext(Dispatchers.Main) {
|
||||||
|
runCatching {
|
||||||
|
sandboxWebView.evaluateJavascript("window.__pwResetSandbox && window.__pwResetSandbox();", null)
|
||||||
|
sandboxWebView.loadUrl("about:blank")
|
||||||
|
sandboxWebView.onPause()
|
||||||
|
sandboxWebView.visibility = View.GONE
|
||||||
|
sandboxPageReady = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun mountHtmlOnMain(ctx: ActiveRenderContext) {
|
||||||
|
isShowingCustomCanvas = true
|
||||||
|
val payload = JSONObject().apply {
|
||||||
|
put("task_id", ctx.taskId)
|
||||||
|
put("snapshot_id", ctx.snapshotId)
|
||||||
|
put("mode", ctx.mode)
|
||||||
|
put("title", ctx.title)
|
||||||
|
put("html", ctx.html)
|
||||||
|
put("data_context", ctx.dataContext)
|
||||||
|
}
|
||||||
|
val b64 = Base64.encodeToString(payload.toString().toByteArray(Charsets.UTF_8), Base64.NO_WRAP)
|
||||||
|
runOnUiThread {
|
||||||
|
updateStatusPillText()
|
||||||
|
mainWebView.evaluateJavascript("window.__pwMountCanvas && window.__pwMountCanvas('$b64');", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun restoreHomeScreen(clearSavedSnapshot: Boolean) {
|
||||||
|
isShowingCustomCanvas = false
|
||||||
|
activeRender = null
|
||||||
|
if (clearSavedSnapshot) {
|
||||||
|
prefs.lastHealthyHtml = ""
|
||||||
|
prefs.lastHealthySnapshotId = ""
|
||||||
|
}
|
||||||
|
runOnUiThread {
|
||||||
|
updateStatusPillText()
|
||||||
|
mainWebView.evaluateJavascript("window.__pwRestoreHome && window.__pwRestoreHome();", null)
|
||||||
|
pushStatusToWebView()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleRuntimeConsoleError(snapshotId: String, taskId: String, source: String, message: String, stack: String) {
|
||||||
|
val report = JSONObject().apply {
|
||||||
|
put("snapshot_id", snapshotId)
|
||||||
|
put("task_id", taskId)
|
||||||
|
put("source", source)
|
||||||
|
put("message", message)
|
||||||
|
put("stack", stack.take(1000))
|
||||||
|
put("repair_status", "observed")
|
||||||
|
}
|
||||||
|
wsClient.sendFrame("console.error_report", report)
|
||||||
|
|
||||||
|
val aiCfg = prefs.getRepairAiConfig()
|
||||||
|
val cur = activeRender ?: return
|
||||||
|
val now = System.currentTimeMillis()
|
||||||
|
if (!aiCfg.enabled || now - lastRuntimeRepairAtMs < aiCfg.runtimeCooldownSec * 1000L) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
lastRuntimeRepairAtMs = now
|
||||||
|
scope.launch {
|
||||||
|
val profile = withContext(Dispatchers.Default) { telemetry.collectDisplayProfile() }
|
||||||
|
val dec = sentinel.diagnoseAndRepair(
|
||||||
|
cfg = aiCfg,
|
||||||
|
currentHtml = cur.html,
|
||||||
|
errors = listOf("Runtime $source: $message\n$stack"),
|
||||||
|
displayProfile = profile,
|
||||||
|
dataContext = cur.dataContext
|
||||||
|
)
|
||||||
|
when (dec.action) {
|
||||||
|
"fix_locally" -> {
|
||||||
|
if (!dec.fixedHtml.isNullOrBlank()) {
|
||||||
|
cur.html = dec.fixedHtml
|
||||||
|
runRenderPipeline(cur, trigger = "runtime_watchdog", upstreamAnswers = null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
"ask_upstream" -> {
|
||||||
|
pendingClarificationTasks[cur.taskId] = cur
|
||||||
|
sendRenderResult(
|
||||||
|
ctx = cur,
|
||||||
|
trigger = "runtime_watchdog",
|
||||||
|
status = "needs_clarification",
|
||||||
|
attempts = 1,
|
||||||
|
finalHtml = null,
|
||||||
|
fixSummary = dec.fixSummary,
|
||||||
|
questions = dec.clarificationQuestions,
|
||||||
|
errors = listOf("$source: $message")
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendRenderResult(
|
||||||
|
ctx: ActiveRenderContext,
|
||||||
|
trigger: String,
|
||||||
|
status: String,
|
||||||
|
attempts: Int,
|
||||||
|
finalHtml: String?,
|
||||||
|
fixSummary: String,
|
||||||
|
questions: JSONArray,
|
||||||
|
errors: List<String>
|
||||||
|
) {
|
||||||
|
val payload = JSONObject().apply {
|
||||||
|
put("task_id", ctx.taskId)
|
||||||
|
put("snapshot_id", ctx.snapshotId)
|
||||||
|
put("trigger", trigger)
|
||||||
|
put("status", status)
|
||||||
|
put("attempts", attempts)
|
||||||
|
if (finalHtml != null) put("final_html", finalHtml)
|
||||||
|
put("local_fix_summary", fixSummary)
|
||||||
|
put("clarification_questions", questions)
|
||||||
|
put("errors", JSONArray(errors))
|
||||||
|
}
|
||||||
|
wsClient.sendFrame("render.result", payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sendInteractionReply(
|
||||||
|
alertId: String,
|
||||||
|
interactionId: String,
|
||||||
|
presetId: String?,
|
||||||
|
label: String,
|
||||||
|
customText: String?
|
||||||
|
) {
|
||||||
|
val payload = JSONObject().apply {
|
||||||
|
put("alert_id", alertId)
|
||||||
|
put("interaction_id", interactionId)
|
||||||
|
put("selected_preset_id", presetId)
|
||||||
|
put("selected_label", label)
|
||||||
|
put("custom_text", customText)
|
||||||
|
put("responded_at", System.currentTimeMillis())
|
||||||
|
}
|
||||||
|
wsClient.sendFrame("interaction.reply", payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun pushStatusToWebView() {
|
||||||
|
if (!mainPageReady) return
|
||||||
|
Thread {
|
||||||
|
val prof = telemetry.collectDisplayProfile()
|
||||||
|
val tele = telemetry.collectTelemetryPayload()
|
||||||
|
val safeTop = prof.optInt("safe_area_top_dp", 28)
|
||||||
|
val safeBot = prof.optInt("safe_area_bottom_dp", 16)
|
||||||
|
val pStr = JSONObject.quote(prof.toString())
|
||||||
|
val tStr = JSONObject.quote(tele.toString())
|
||||||
|
val dStr = JSONObject.quote(lastConnDetail)
|
||||||
|
runOnUiThread {
|
||||||
|
mainWebView.evaluateJavascript("window.__pwApplySafeArea && window.__pwApplySafeArea($safeTop,$safeBot);", null)
|
||||||
|
mainWebView.evaluateJavascript("window.__pwUpdateStatus && window.__pwUpdateStatus($wsConnected,$pStr,$tStr,$dStr);", null)
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun showSettingsDialog() {
|
||||||
|
val container = LinearLayout(this).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
val p = dp(16)
|
||||||
|
setPadding(p, p, p, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun addField(label: String, initial: String): EditText {
|
||||||
|
container.addView(TextView(this).apply { text = label; textSize = 12f })
|
||||||
|
val et = EditText(this).apply { setText(initial); isSingleLine = true }
|
||||||
|
container.addView(et)
|
||||||
|
return et
|
||||||
|
}
|
||||||
|
|
||||||
|
val urlEt = addField("Python 中心桥 WebSocket 地址 (如 ws://192.168.x.x:8765)", prefs.hubWsUrl)
|
||||||
|
val discoverBtn = Button(this).apply {
|
||||||
|
text = "🔍 自动搜索局域网中心桥 (免输 IP)"
|
||||||
|
setOnClickListener {
|
||||||
|
scope.launch {
|
||||||
|
Toast.makeText(this@MainActivity, "正在搜索局域网中心桥...", Toast.LENGTH_SHORT).show()
|
||||||
|
val hubs = HubDiscoveryClient.discover(timeoutMs = 1800)
|
||||||
|
if (hubs.isNotEmpty()) {
|
||||||
|
urlEt.setText(hubs.first().wsUrl)
|
||||||
|
Toast.makeText(this@MainActivity, "已填入 ${hubs.first().wsUrl},请点【保存并重连】", Toast.LENGTH_LONG).show()
|
||||||
|
} else {
|
||||||
|
Toast.makeText(this@MainActivity, "未搜到中心桥,请确认已运行 ./hub/run_hub.sh", Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
container.addView(discoverBtn)
|
||||||
|
val idEt = addField("设备 ID (唯一标识)", prefs.deviceId)
|
||||||
|
val nameEt = addField("设备显示名称", prefs.deviceName)
|
||||||
|
val tokEt = addField("鉴权 Token (可选)", prefs.authToken)
|
||||||
|
|
||||||
|
val aiCfg = prefs.getRepairAiConfig()
|
||||||
|
container.addView(TextView(this).apply {
|
||||||
|
text = "\n连接状态: $lastConnDetail\n版本: v${BuildConfig.VERSION_NAME} (build ${BuildConfig.VERSION_CODE}) · Root: ${if (telemetry.isRootAvailable()) "已启用" else "未检测到"}\n端侧修复 AI (由中心桥热下发): " +
|
||||||
|
if (aiCfg.enabled) "已启用 (${aiCfg.model})" else "未启用"
|
||||||
|
textSize = 12f
|
||||||
|
})
|
||||||
|
|
||||||
|
val checkUpdateBtn = Button(this).apply {
|
||||||
|
text = "🔄 检查 App 自更新 (OTA)"
|
||||||
|
setOnClickListener {
|
||||||
|
updateManager.checkForUpdate(silentIfLatest = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
container.addView(checkUpdateBtn)
|
||||||
|
|
||||||
|
val homeBtn = Button(this).apply {
|
||||||
|
text = "🏠 返回默认首页(关闭当前动态页)"
|
||||||
|
setOnClickListener {
|
||||||
|
restoreHomeScreen(clearSavedSnapshot = true)
|
||||||
|
Toast.makeText(this@MainActivity, "已恢复默认首页", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
container.addView(homeBtn)
|
||||||
|
|
||||||
|
val testBtn = Button(this).apply {
|
||||||
|
text = "演练全屏红色警报"
|
||||||
|
setOnClickListener {
|
||||||
|
alertController.showAlert(
|
||||||
|
JSONObject()
|
||||||
|
.put("alert_id", "local_test")
|
||||||
|
.put("title", "本地紧急警报演练")
|
||||||
|
.put("message", "验证原生警报层、警报音、预设按钮与收起式输入框。")
|
||||||
|
.put("level", "critical")
|
||||||
|
.put("presentation", "fullscreen_alarm")
|
||||||
|
.put("sound", "siren")
|
||||||
|
.put("details_code", "RuntimeException: Demo stack trace line 42")
|
||||||
|
.put(
|
||||||
|
"interaction",
|
||||||
|
JSONObject()
|
||||||
|
.put("interaction_id", "local_int")
|
||||||
|
.put("allow_custom_input", true)
|
||||||
|
.put(
|
||||||
|
"presets",
|
||||||
|
JSONArray()
|
||||||
|
.put(JSONObject().put("id", "ack").put("label", "确认收到").put("style", "primary"))
|
||||||
|
.put(JSONObject().put("id", "fix").put("label", "通知 AI 处理").put("style", "danger"))
|
||||||
|
)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
container.addView(testBtn)
|
||||||
|
|
||||||
|
val scrollWrapper = ScrollView(this).apply { addView(container) }
|
||||||
|
AlertDialog.Builder(this)
|
||||||
|
.setTitle("PulseWall 终端设置 (遥控器上下选择)")
|
||||||
|
.setView(scrollWrapper)
|
||||||
|
.setPositiveButton("保存并重连") { _, _ ->
|
||||||
|
prefs.hubWsUrl = urlEt.text.toString()
|
||||||
|
prefs.deviceId = idEt.text.toString()
|
||||||
|
prefs.deviceName = nameEt.text.toString()
|
||||||
|
prefs.authToken = tokEt.text.toString()
|
||||||
|
wsClient.reconnect()
|
||||||
|
Toast.makeText(this, "正在重连中心桥...", Toast.LENGTH_SHORT).show()
|
||||||
|
}
|
||||||
|
.setNegativeButton("取消", null)
|
||||||
|
.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
inner class MainJsBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onWebAction(presetId: String, label: String, customText: String) {
|
||||||
|
sendInteractionReply(
|
||||||
|
alertId = "canvas",
|
||||||
|
interactionId = "canvas_${System.currentTimeMillis()}",
|
||||||
|
presetId = presetId,
|
||||||
|
label = label,
|
||||||
|
customText = customText.ifBlank { null }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onRuntimeError(snapshotId: String, taskId: String, source: String, message: String, stack: String) {
|
||||||
|
handleRuntimeConsoleError(snapshotId, taskId, source, message, stack)
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun openSettings() {
|
||||||
|
runOnUiThread { showSettingsDialog() }
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun discoverHub() {
|
||||||
|
runOnUiThread { runLanAutoDiscovery(silentIfNotFound = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun checkUpdate() {
|
||||||
|
runOnUiThread { updateManager.checkForUpdate(silentIfLatest = false) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onFocusTopBar() {
|
||||||
|
runOnUiThread {
|
||||||
|
if (!isShowingCustomCanvas && statusPill.visibility == View.VISIBLE) {
|
||||||
|
statusPill.requestFocus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inner class SandboxJsBridge {
|
||||||
|
@JavascriptInterface
|
||||||
|
fun onValidationResult(taskId: String, ok: Boolean, errorsJson: String, overflowPx: Int) {
|
||||||
|
val errs = mutableListOf<String>()
|
||||||
|
runCatching {
|
||||||
|
val arr = JSONArray(errorsJson)
|
||||||
|
for (i in 0 until arr.length()) errs.add(arr.optString(i))
|
||||||
|
}
|
||||||
|
sandboxWaiters[taskId]?.complete(SandboxValidationOutcome(ok, errs, overflowPx))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dp(v: Int): Int = (v * resources.displayMetrics.density).toInt()
|
||||||
|
|
||||||
|
override fun onStart() {
|
||||||
|
super.onStart()
|
||||||
|
runCatching {
|
||||||
|
mainWebView.onResume()
|
||||||
|
if (mainPageReady) {
|
||||||
|
mainWebView.evaluateJavascript("window.__pwFreezeActiveLayer && window.__pwFreezeActiveLayer(false);", null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStop() {
|
||||||
|
super.onStop()
|
||||||
|
// Freeze WebView rendering/animations when Activity is hidden in background (WS keep-alive service stays active)
|
||||||
|
runCatching {
|
||||||
|
if (mainPageReady) {
|
||||||
|
mainWebView.evaluateJavascript("window.__pwFreezeActiveLayer && window.__pwFreezeActiveLayer(true);", null)
|
||||||
|
}
|
||||||
|
mainWebView.onPause()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onDestroy() {
|
||||||
|
super.onDestroy()
|
||||||
|
wsClient.stop()
|
||||||
|
telemetry.close()
|
||||||
|
alertController.destroy()
|
||||||
|
runCatching {
|
||||||
|
sandboxWebView.loadUrl("about:blank")
|
||||||
|
sandboxWebView.destroy()
|
||||||
|
mainWebView.loadUrl("about:blank")
|
||||||
|
mainWebView.destroy()
|
||||||
|
}
|
||||||
|
scope.cancel()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,416 @@
|
|||||||
|
package com.pulsewall.app.alert
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.Dialog
|
||||||
|
import android.content.Context
|
||||||
|
import android.graphics.Color
|
||||||
|
import android.graphics.Typeface
|
||||||
|
import android.graphics.drawable.ColorDrawable
|
||||||
|
import android.graphics.drawable.GradientDrawable
|
||||||
|
import android.graphics.drawable.StateListDrawable
|
||||||
|
import android.media.AudioManager
|
||||||
|
import android.media.ToneGenerator
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.os.VibrationEffect
|
||||||
|
import android.os.Vibrator
|
||||||
|
import android.speech.tts.TextToSpeech
|
||||||
|
import android.view.Gravity
|
||||||
|
import android.view.View
|
||||||
|
import android.view.ViewGroup
|
||||||
|
import android.view.Window
|
||||||
|
import android.view.WindowManager
|
||||||
|
import android.widget.Button
|
||||||
|
import android.widget.EditText
|
||||||
|
import android.widget.LinearLayout
|
||||||
|
import android.widget.ScrollView
|
||||||
|
import android.widget.TextView
|
||||||
|
import android.widget.Toast
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.Locale
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Native Unbreakable Alert Layer:
|
||||||
|
* Completely independent of WebView health. Handles ding/warning/siren sounds,
|
||||||
|
* TTS speech, vibration, wake-screen, fullscreen red emergency overlay, and
|
||||||
|
* Preset-First interactive dialogs (collapsible custom input at bottom).
|
||||||
|
*/
|
||||||
|
class NativeAlertController(
|
||||||
|
private val activity: Activity,
|
||||||
|
private val onInteractionReply: (alertId: String, interactionId: String, presetId: String?, label: String, customText: String?) -> Unit
|
||||||
|
) {
|
||||||
|
private val mainHandler = Handler(Looper.getMainLooper())
|
||||||
|
private var activeDialog: Dialog? = null
|
||||||
|
private var activeAlertId: String? = null
|
||||||
|
private var sirenRunnable: Runnable? = null
|
||||||
|
private var flashRunnable: Runnable? = null
|
||||||
|
private var tts: TextToSpeech? = null
|
||||||
|
private var ttsReady = false
|
||||||
|
|
||||||
|
init {
|
||||||
|
tts = TextToSpeech(activity.applicationContext) { status ->
|
||||||
|
if (status == TextToSpeech.SUCCESS) {
|
||||||
|
tts?.language = Locale.CHINA
|
||||||
|
ttsReady = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun playSound(sound: String, ttsText: String? = null) {
|
||||||
|
stopSiren()
|
||||||
|
when (sound) {
|
||||||
|
"none" -> return
|
||||||
|
"ding" -> playTone(ToneGenerator.TONE_PROP_BEEP, 180)
|
||||||
|
"warning" -> playTone(ToneGenerator.TONE_PROP_BEEP2, 420)
|
||||||
|
"siren" -> startSirenLoop()
|
||||||
|
"tts" -> speakText(ttsText ?: "收到新提醒")
|
||||||
|
else -> playTone(ToneGenerator.TONE_PROP_BEEP, 180)
|
||||||
|
}
|
||||||
|
if (!ttsText.isNullOrBlank() && sound != "tts") {
|
||||||
|
mainHandler.postDelayed({ speakText(ttsText) }, 450)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun playTone(tone: Int, durationMs: Int) {
|
||||||
|
try {
|
||||||
|
val tg = ToneGenerator(AudioManager.STREAM_ALARM, 90)
|
||||||
|
tg.startTone(tone, durationMs)
|
||||||
|
mainHandler.postDelayed({ runCatching { tg.release() } }, (durationMs + 120).toLong())
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun startSirenLoop() {
|
||||||
|
stopSiren()
|
||||||
|
var step = 0
|
||||||
|
val r = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
val tone = if (step % 2 == 0) ToneGenerator.TONE_CDMA_EMERGENCY_RINGBACK else ToneGenerator.TONE_SUP_ERROR
|
||||||
|
playTone(tone, 480)
|
||||||
|
step++
|
||||||
|
if (step < 30) {
|
||||||
|
mainHandler.postDelayed(this, 650)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sirenRunnable = r
|
||||||
|
mainHandler.post(r)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stopSiren() {
|
||||||
|
sirenRunnable?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
sirenRunnable = null
|
||||||
|
flashRunnable?.let { mainHandler.removeCallbacks(it) }
|
||||||
|
flashRunnable = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun speakText(text: String) {
|
||||||
|
if (ttsReady) {
|
||||||
|
tts?.speak(text, TextToSpeech.QUEUE_FLUSH, null, "pw_tts_${System.currentTimeMillis()}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun triggerVibration(critical: Boolean) {
|
||||||
|
try {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val vib = activity.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator ?: return
|
||||||
|
if (!vib.hasVibrator()) return
|
||||||
|
val pattern = if (critical) longArrayOf(0, 400, 180, 400, 180, 500) else longArrayOf(0, 140)
|
||||||
|
vib.vibrate(VibrationEffect.createWaveform(pattern, -1))
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun wakeScreen() {
|
||||||
|
try {
|
||||||
|
activity.setShowWhenLocked(true)
|
||||||
|
activity.setTurnScreenOn(true)
|
||||||
|
activity.window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
|
||||||
|
val pm = activity.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
val wl = pm.newWakeLock(
|
||||||
|
PowerManager.SCREEN_BRIGHT_WAKE_LOCK or PowerManager.ACQUIRE_CAUSES_WAKEUP,
|
||||||
|
"PulseWall:EmergencyWake"
|
||||||
|
)
|
||||||
|
wl.acquire(15_000L)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun showAlert(payload: JSONObject) {
|
||||||
|
mainHandler.post {
|
||||||
|
val alertId = payload.optString("alert_id", "alert_${System.currentTimeMillis()}")
|
||||||
|
val title = payload.optString("title", "PulseWall 提醒")
|
||||||
|
val message = payload.optString("message", "")
|
||||||
|
val level = payload.optString("level", "warning")
|
||||||
|
val presentation = payload.optString("presentation", "modal")
|
||||||
|
val sound = payload.optString("sound", "warning")
|
||||||
|
val vibrate = payload.optBoolean("vibrate", true)
|
||||||
|
val wake = payload.optBoolean("wake_screen", presentation == "fullscreen_alarm")
|
||||||
|
val ttsText = payload.optString("tts_text", "").ifBlank { null }
|
||||||
|
val detailsCode = payload.optString("details_code", "").ifBlank { null }
|
||||||
|
val interaction = payload.optJSONObject("interaction")
|
||||||
|
|
||||||
|
// Synchronously clear any previous dialog/siren BEFORE starting new sound & new dialog!
|
||||||
|
dismissNowOnMain(null)
|
||||||
|
|
||||||
|
if (wake) wakeScreen()
|
||||||
|
playSound(sound, ttsText)
|
||||||
|
if (vibrate) triggerVibration(presentation == "fullscreen_alarm" || level == "critical")
|
||||||
|
|
||||||
|
if (presentation == "toast") {
|
||||||
|
Toast.makeText(activity, "$title: $message", Toast.LENGTH_LONG).show()
|
||||||
|
return@post
|
||||||
|
}
|
||||||
|
|
||||||
|
activeAlertId = alertId
|
||||||
|
|
||||||
|
val isFullscreen = presentation == "fullscreen_alarm"
|
||||||
|
val dialog = if (isFullscreen) {
|
||||||
|
Dialog(activity, android.R.style.Theme_Black_NoTitleBar_Fullscreen)
|
||||||
|
} else {
|
||||||
|
Dialog(activity)
|
||||||
|
}
|
||||||
|
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
|
||||||
|
dialog.setCancelable(!isFullscreen)
|
||||||
|
dialog.setCanceledOnTouchOutside(!isFullscreen)
|
||||||
|
|
||||||
|
val root = LinearLayout(activity).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
gravity = if (isFullscreen) Gravity.CENTER else Gravity.CENTER_HORIZONTAL
|
||||||
|
val pad = dp(20)
|
||||||
|
setPadding(pad, dp(28), pad, dp(24))
|
||||||
|
setBackgroundColor(if (isFullscreen) Color.parseColor("#8B0000") else Color.parseColor("#111A2E"))
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isFullscreen) {
|
||||||
|
var toggle = false
|
||||||
|
val flash = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
root.setBackgroundColor(if (toggle) Color.parseColor("#991B1B") else Color.parseColor("#450A0A"))
|
||||||
|
toggle = !toggle
|
||||||
|
mainHandler.postDelayed(this, 550)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flashRunnable = flash
|
||||||
|
mainHandler.post(flash)
|
||||||
|
} else {
|
||||||
|
root.background = GradientDrawable().apply {
|
||||||
|
setColor(Color.parseColor("#131C31"))
|
||||||
|
cornerRadius = dp(18).toFloat()
|
||||||
|
setStroke(dp(1), accentColorForLevel(level))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val badge = TextView(activity).apply {
|
||||||
|
text = if (isFullscreen) "🚨 紧急全屏警报 · ${level.uppercase()}" else "⚡ ${level.uppercase()}"
|
||||||
|
setTextColor(if (isFullscreen) Color.WHITE else accentColorForLevel(level))
|
||||||
|
textSize = 13f
|
||||||
|
setTypeface(null, Typeface.BOLD)
|
||||||
|
}
|
||||||
|
root.addView(badge)
|
||||||
|
|
||||||
|
val titleTv = TextView(activity).apply {
|
||||||
|
text = title
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
textSize = if (isFullscreen) 26f else 20f
|
||||||
|
setTypeface(null, Typeface.BOLD)
|
||||||
|
setPadding(0, dp(8), 0, dp(8))
|
||||||
|
}
|
||||||
|
root.addView(titleTv)
|
||||||
|
|
||||||
|
val msgTv = TextView(activity).apply {
|
||||||
|
text = message
|
||||||
|
setTextColor(Color.parseColor("#E2E8F0"))
|
||||||
|
textSize = 15f
|
||||||
|
setPadding(0, 0, 0, dp(12))
|
||||||
|
}
|
||||||
|
root.addView(msgTv)
|
||||||
|
|
||||||
|
if (detailsCode != null) {
|
||||||
|
val codeTv = TextView(activity).apply {
|
||||||
|
text = detailsCode
|
||||||
|
setTextColor(Color.parseColor("#FDE68A"))
|
||||||
|
setBackgroundColor(Color.parseColor("#CC070B14"))
|
||||||
|
typeface = Typeface.MONOSPACE
|
||||||
|
textSize = 12f
|
||||||
|
val p = dp(10)
|
||||||
|
setPadding(p, p, p, p)
|
||||||
|
}
|
||||||
|
val scroll = ScrollView(activity).apply {
|
||||||
|
layoutParams = LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
dp(130)
|
||||||
|
).apply { bottomMargin = dp(14) }
|
||||||
|
addView(codeTv)
|
||||||
|
}
|
||||||
|
root.addView(scroll)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Preset-First Interaction Section
|
||||||
|
val interactionId = interaction?.optString("interaction_id", "int_$alertId") ?: "int_$alertId"
|
||||||
|
val presets: JSONArray = interaction?.optJSONArray("presets") ?: JSONArray().apply {
|
||||||
|
put(JSONObject().put("id", "ack").put("label", "确认收到").put("style", "primary"))
|
||||||
|
}
|
||||||
|
|
||||||
|
var firstActionButton: Button? = null
|
||||||
|
for (i in 0 until presets.length()) {
|
||||||
|
val p = presets.optJSONObject(i) ?: continue
|
||||||
|
val pid = p.optString("id", "opt_$i")
|
||||||
|
val label = p.optString("label", "确认")
|
||||||
|
val style = p.optString("style", "primary")
|
||||||
|
val baseColor = when (style) {
|
||||||
|
"danger" -> Color.parseColor("#DC2626")
|
||||||
|
"secondary" -> Color.parseColor("#334155")
|
||||||
|
"success" -> Color.parseColor("#16A34A")
|
||||||
|
else -> Color.parseColor("#38BDF8")
|
||||||
|
}
|
||||||
|
val btn = Button(activity).apply {
|
||||||
|
text = label
|
||||||
|
isAllCaps = false
|
||||||
|
isFocusable = true
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
textSize = 16f
|
||||||
|
setTypeface(null, Typeface.BOLD)
|
||||||
|
setTextColor(if (style == "primary") Color.parseColor("#041220") else Color.WHITE)
|
||||||
|
background = buildFocusableButtonBg(baseColor)
|
||||||
|
layoutParams = LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
).apply { topMargin = dp(10) }
|
||||||
|
setOnClickListener {
|
||||||
|
stopSiren()
|
||||||
|
dialog.dismiss()
|
||||||
|
onInteractionReply(alertId, interactionId, pid, label, null)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (firstActionButton == null) firstActionButton = btn
|
||||||
|
root.addView(btn)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collapsible Custom Free-Text Input at the very bottom (zero friction by default)
|
||||||
|
val allowCustom = interaction?.optBoolean("allow_custom_input", false) ?: false
|
||||||
|
if (allowCustom) {
|
||||||
|
val customContainer = LinearLayout(activity).apply {
|
||||||
|
orientation = LinearLayout.VERTICAL
|
||||||
|
visibility = View.GONE
|
||||||
|
setPadding(0, dp(10), 0, 0)
|
||||||
|
}
|
||||||
|
val edit = EditText(activity).apply {
|
||||||
|
hint = interaction?.optString("custom_input_placeholder", "输入自定义说明或指令...")
|
||||||
|
setHintTextColor(Color.parseColor("#94A3B8"))
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
setBackgroundColor(Color.parseColor("#1E293B"))
|
||||||
|
val p = dp(10)
|
||||||
|
setPadding(p, p, p, p)
|
||||||
|
}
|
||||||
|
val sendBtn = Button(activity).apply {
|
||||||
|
text = "发送自定义指令"
|
||||||
|
isAllCaps = false
|
||||||
|
setTextColor(Color.WHITE)
|
||||||
|
setBackgroundColor(Color.parseColor("#0284C7"))
|
||||||
|
layoutParams = LinearLayout.LayoutParams(
|
||||||
|
ViewGroup.LayoutParams.MATCH_PARENT,
|
||||||
|
ViewGroup.LayoutParams.WRAP_CONTENT
|
||||||
|
).apply { topMargin = dp(8) }
|
||||||
|
setOnClickListener {
|
||||||
|
val txt = edit.text.toString().trim()
|
||||||
|
if (txt.isNotEmpty()) {
|
||||||
|
stopSiren()
|
||||||
|
dialog.dismiss()
|
||||||
|
onInteractionReply(alertId, interactionId, "custom_input", "自定义输入", txt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
customContainer.addView(edit)
|
||||||
|
customContainer.addView(sendBtn)
|
||||||
|
|
||||||
|
val toggleCustom = TextView(activity).apply {
|
||||||
|
text = "▾ 其他输入(手动打字)"
|
||||||
|
isFocusable = true
|
||||||
|
isFocusableInTouchMode = true
|
||||||
|
setTextColor(Color.parseColor("#CBD5E1"))
|
||||||
|
textSize = 13f
|
||||||
|
gravity = Gravity.CENTER
|
||||||
|
setPadding(dp(8), dp(12), dp(8), dp(8))
|
||||||
|
background = buildFocusableButtonBg(Color.TRANSPARENT)
|
||||||
|
setOnClickListener {
|
||||||
|
customContainer.visibility =
|
||||||
|
if (customContainer.visibility == View.GONE) View.VISIBLE else View.GONE
|
||||||
|
}
|
||||||
|
}
|
||||||
|
root.addView(toggleCustom)
|
||||||
|
root.addView(customContainer)
|
||||||
|
}
|
||||||
|
|
||||||
|
val outerScroll = ScrollView(activity).apply {
|
||||||
|
isFillViewport = isFullscreen
|
||||||
|
addView(root)
|
||||||
|
}
|
||||||
|
dialog.setContentView(outerScroll)
|
||||||
|
dialog.window?.apply {
|
||||||
|
setBackgroundDrawable(ColorDrawable(Color.TRANSPARENT))
|
||||||
|
if (isFullscreen) {
|
||||||
|
setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)
|
||||||
|
} else {
|
||||||
|
val w = (activity.resources.displayMetrics.widthPixels * 0.90).toInt()
|
||||||
|
setLayout(w, ViewGroup.LayoutParams.WRAP_CONTENT)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
dialog.setOnDismissListener { stopSiren() }
|
||||||
|
activeDialog = dialog
|
||||||
|
dialog.show()
|
||||||
|
firstActionButton?.requestFocus()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dismissNowOnMain(alertId: String?) {
|
||||||
|
if (alertId == null || alertId == activeAlertId) {
|
||||||
|
stopSiren()
|
||||||
|
runCatching { activeDialog?.dismiss() }
|
||||||
|
activeDialog = null
|
||||||
|
activeAlertId = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun dismiss(alertId: String?) {
|
||||||
|
if (Looper.myLooper() == Looper.getMainLooper()) {
|
||||||
|
dismissNowOnMain(alertId)
|
||||||
|
} else {
|
||||||
|
mainHandler.post { dismissNowOnMain(alertId) }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun destroy() {
|
||||||
|
stopSiren()
|
||||||
|
runCatching { activeDialog?.dismiss() }
|
||||||
|
runCatching { tts?.stop(); tts?.shutdown() }
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun accentColorForLevel(level: String): Int = when (level) {
|
||||||
|
"critical", "error" -> Color.parseColor("#EF4444")
|
||||||
|
"warning" -> Color.parseColor("#F59E0B")
|
||||||
|
else -> Color.parseColor("#38BDF8")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun buildFocusableButtonBg(baseColor: Int): StateListDrawable {
|
||||||
|
val focused = GradientDrawable().apply {
|
||||||
|
cornerRadius = dp(12).toFloat()
|
||||||
|
setColor(baseColor)
|
||||||
|
setStroke(dp(3), Color.parseColor("#FACC15"))
|
||||||
|
}
|
||||||
|
val normal = GradientDrawable().apply {
|
||||||
|
cornerRadius = dp(12).toFloat()
|
||||||
|
setColor(baseColor)
|
||||||
|
}
|
||||||
|
return StateListDrawable().apply {
|
||||||
|
addState(intArrayOf(android.R.attr.state_focused), focused)
|
||||||
|
addState(intArrayOf(android.R.attr.state_pressed), focused)
|
||||||
|
addState(intArrayOf(), normal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun dp(v: Int): Int = (v * activity.resources.displayMetrics.density).toInt()
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package com.pulsewall.app.config
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.os.Build
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.UUID
|
||||||
|
|
||||||
|
data class RepairAiConfig(
|
||||||
|
val enabled: Boolean = false,
|
||||||
|
val baseUrl: String = "https://api.openai.com/v1",
|
||||||
|
val apiKey: String = "",
|
||||||
|
val model: String = "gpt-4o-mini",
|
||||||
|
val timeoutSec: Int = 30,
|
||||||
|
val maxRetries: Int = 3,
|
||||||
|
val runtimeCooldownSec: Int = 30
|
||||||
|
)
|
||||||
|
|
||||||
|
class AppPrefs(context: Context) {
|
||||||
|
private val sp = context.getSharedPreferences("pulsewall_prefs", Context.MODE_PRIVATE)
|
||||||
|
|
||||||
|
var hubWsUrl: String
|
||||||
|
get() = sp.getString("hub_ws_url", "ws://192.168.1.100:8765") ?: "ws://192.168.1.100:8765"
|
||||||
|
set(v) = sp.edit().putString("hub_ws_url", v.trim().trimEnd('/')).apply()
|
||||||
|
|
||||||
|
var deviceId: String
|
||||||
|
get() {
|
||||||
|
var id = sp.getString("device_id", null)
|
||||||
|
if (id.isNullOrBlank()) {
|
||||||
|
val safeModel = (Build.MODEL ?: "android11")
|
||||||
|
.lowercase()
|
||||||
|
.replace(Regex("[^a-z0-9]+"), "-")
|
||||||
|
.trim('-')
|
||||||
|
.take(16)
|
||||||
|
id = "$safeModel-${UUID.randomUUID().toString().take(6)}"
|
||||||
|
sp.edit().putString("device_id", id).apply()
|
||||||
|
}
|
||||||
|
return id
|
||||||
|
}
|
||||||
|
set(v) = sp.edit().putString("device_id", v.trim()).apply()
|
||||||
|
|
||||||
|
var deviceName: String
|
||||||
|
get() = sp.getString("device_name", "${Build.MANUFACTURER} ${Build.MODEL}") ?: "Android 11 Wall"
|
||||||
|
set(v) = sp.edit().putString("device_name", v.trim()).apply()
|
||||||
|
|
||||||
|
var authToken: String
|
||||||
|
get() = sp.getString("auth_token", "") ?: ""
|
||||||
|
set(v) = sp.edit().putString("auth_token", v.trim()).apply()
|
||||||
|
|
||||||
|
var telemetryIntervalSec: Int
|
||||||
|
get() = sp.getInt("telemetry_interval_sec", 3).coerceIn(1, 120)
|
||||||
|
set(v) = sp.edit().putInt("telemetry_interval_sec", v.coerceIn(1, 120)).apply()
|
||||||
|
|
||||||
|
var lastHealthySnapshotId: String
|
||||||
|
get() = sp.getString("last_healthy_snapshot_id", "") ?: ""
|
||||||
|
set(v) = sp.edit().putString("last_healthy_snapshot_id", v).apply()
|
||||||
|
|
||||||
|
var lastHealthyHtml: String
|
||||||
|
get() = sp.getString("last_healthy_html", "") ?: ""
|
||||||
|
set(v) = sp.edit().putString("last_healthy_html", v).apply()
|
||||||
|
|
||||||
|
fun getRepairAiConfig(): RepairAiConfig {
|
||||||
|
return RepairAiConfig(
|
||||||
|
enabled = sp.getBoolean("ai_enabled", false),
|
||||||
|
baseUrl = sp.getString("ai_base_url", "https://api.openai.com/v1") ?: "https://api.openai.com/v1",
|
||||||
|
apiKey = sp.getString("ai_api_key", "") ?: "",
|
||||||
|
model = sp.getString("ai_model", "gpt-4o-mini") ?: "gpt-4o-mini",
|
||||||
|
timeoutSec = sp.getInt("ai_timeout_sec", 30).coerceIn(5, 120),
|
||||||
|
maxRetries = sp.getInt("ai_max_retries", 3).coerceIn(0, 5),
|
||||||
|
runtimeCooldownSec = sp.getInt("ai_runtime_cooldown_sec", 30).coerceIn(5, 300)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun applyHubConfigPush(payload: JSONObject) {
|
||||||
|
val editor = sp.edit()
|
||||||
|
val ai = payload.optJSONObject("repair_ai")
|
||||||
|
if (ai != null) {
|
||||||
|
editor.putBoolean("ai_enabled", ai.optBoolean("enabled", false))
|
||||||
|
editor.putString("ai_base_url", ai.optString("base_url", "https://api.openai.com/v1"))
|
||||||
|
editor.putString("ai_api_key", ai.optString("api_key", ""))
|
||||||
|
editor.putString("ai_model", ai.optString("model", "gpt-4o-mini"))
|
||||||
|
editor.putInt("ai_timeout_sec", ai.optInt("timeout_sec", 30))
|
||||||
|
editor.putInt("ai_max_retries", ai.optInt("max_retries", 3))
|
||||||
|
editor.putInt("ai_runtime_cooldown_sec", ai.optInt("runtime_cooldown_sec", 30))
|
||||||
|
}
|
||||||
|
if (payload.has("telemetry_interval_sec")) {
|
||||||
|
editor.putInt("telemetry_interval_sec", payload.optInt("telemetry_interval_sec", 10))
|
||||||
|
}
|
||||||
|
editor.apply()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildDeviceWsEndpoint(): String {
|
||||||
|
val base = hubWsUrl
|
||||||
|
val url = if (base.contains("/ws/device/")) base else "$base/ws/device/$deviceId"
|
||||||
|
return if (authToken.isNotBlank()) "$url?token=$authToken" else url
|
||||||
|
}
|
||||||
|
|
||||||
|
fun buildHubHttpBaseUrl(): String {
|
||||||
|
val trimmed = hubWsUrl.trim().trimEnd('/')
|
||||||
|
val withoutWsPath = trimmed.substringBefore("/ws/device/")
|
||||||
|
return when {
|
||||||
|
withoutWsPath.startsWith("wss://", ignoreCase = true) -> "https://" + withoutWsPath.substring(6)
|
||||||
|
withoutWsPath.startsWith("ws://", ignoreCase = true) -> "http://" + withoutWsPath.substring(5)
|
||||||
|
withoutWsPath.startsWith("http://", ignoreCase = true) || withoutWsPath.startsWith("https://", ignoreCase = true) -> withoutWsPath
|
||||||
|
else -> "http://$withoutWsPath"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
package com.pulsewall.app.network
|
||||||
|
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.net.DatagramPacket
|
||||||
|
import java.net.DatagramSocket
|
||||||
|
import java.net.Inet4Address
|
||||||
|
import java.net.InetAddress
|
||||||
|
import java.net.NetworkInterface
|
||||||
|
import java.net.SocketTimeoutException
|
||||||
|
|
||||||
|
data class DiscoveredHub(
|
||||||
|
val host: String,
|
||||||
|
val port: Int,
|
||||||
|
val hubName: String
|
||||||
|
) {
|
||||||
|
val wsUrl: String get() = "ws://$host:$port"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Broadcasts a LAN UDP probe on port 8766 to auto-discover PulseWall Hub without typing IPs on a TV remote.
|
||||||
|
*/
|
||||||
|
object HubDiscoveryClient {
|
||||||
|
private const val DISCOVERY_PORT = 8766
|
||||||
|
private val PROBE = "PULSEWALL_DISCOVER".toByteArray(Charsets.UTF_8)
|
||||||
|
|
||||||
|
suspend fun discover(timeoutMs: Int = 1800): List<DiscoveredHub> = withContext(Dispatchers.IO) {
|
||||||
|
val found = linkedMapOf<String, DiscoveredHub>()
|
||||||
|
var socket: DatagramSocket? = null
|
||||||
|
try {
|
||||||
|
socket = DatagramSocket().apply {
|
||||||
|
broadcast = true
|
||||||
|
soTimeout = 400
|
||||||
|
}
|
||||||
|
val targets = collectBroadcastAddresses()
|
||||||
|
for (addr in targets) {
|
||||||
|
runCatching {
|
||||||
|
val pkt = DatagramPacket(PROBE, PROBE.size, addr, DISCOVERY_PORT)
|
||||||
|
socket.send(pkt)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val deadline = System.currentTimeMillis() + timeoutMs
|
||||||
|
val buf = ByteArray(2048)
|
||||||
|
while (System.currentTimeMillis() < deadline) {
|
||||||
|
try {
|
||||||
|
val rx = DatagramPacket(buf, buf.size)
|
||||||
|
socket.receive(rx)
|
||||||
|
val text = String(rx.data, 0, rx.length, Charsets.UTF_8)
|
||||||
|
val obj = JSONObject(text)
|
||||||
|
if (obj.optString("type") == "PULSEWALL_HUB_HERE") {
|
||||||
|
val host = rx.address.hostAddress ?: continue
|
||||||
|
val port = obj.optInt("port", 8765)
|
||||||
|
val name = obj.optString("hub_name", "PulseWall Hub")
|
||||||
|
found["$host:$port"] = DiscoveredHub(host, port, name)
|
||||||
|
}
|
||||||
|
} catch (_: SocketTimeoutException) {
|
||||||
|
// keep listening until deadline
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
} finally {
|
||||||
|
runCatching { socket?.close() }
|
||||||
|
}
|
||||||
|
found.values.toList()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun collectBroadcastAddresses(): List<InetAddress> {
|
||||||
|
val addrs = linkedSetOf<InetAddress>()
|
||||||
|
runCatching { addrs.add(InetAddress.getByName("255.255.255.255")) }
|
||||||
|
runCatching {
|
||||||
|
val ifaces = NetworkInterface.getNetworkInterfaces()
|
||||||
|
while (ifaces.hasMoreElements()) {
|
||||||
|
val iface = ifaces.nextElement()
|
||||||
|
if (!iface.isUp || iface.isLoopback) continue
|
||||||
|
for (ia in iface.interfaceAddresses) {
|
||||||
|
if (ia.address is Inet4Address && ia.broadcast != null) {
|
||||||
|
addrs.add(ia.broadcast)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return addrs.toList()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,148 @@
|
|||||||
|
package com.pulsewall.app.network
|
||||||
|
|
||||||
|
import android.os.Handler
|
||||||
|
import android.os.Looper
|
||||||
|
import com.pulsewall.app.config.AppPrefs
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.Response
|
||||||
|
import okhttp3.WebSocket
|
||||||
|
import okhttp3.WebSocketListener
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.UUID
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
interface HubMessageListener {
|
||||||
|
fun onConnectionChanged(connected: Boolean, detail: String = "")
|
||||||
|
fun onHubFrame(type: String, payload: JSONObject)
|
||||||
|
}
|
||||||
|
|
||||||
|
class HubWebSocketClient(
|
||||||
|
private val prefs: AppPrefs,
|
||||||
|
private val helloSupplier: () -> JSONObject,
|
||||||
|
private val telemetrySupplier: () -> JSONObject,
|
||||||
|
private val listener: HubMessageListener
|
||||||
|
) {
|
||||||
|
private val client = OkHttpClient.Builder()
|
||||||
|
.pingInterval(20, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(0, TimeUnit.MILLISECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
private val handler = Handler(Looper.getMainLooper())
|
||||||
|
private var webSocket: WebSocket? = null
|
||||||
|
private var closedByUser = false
|
||||||
|
private var connected = false
|
||||||
|
private var retryDelayMs = 2000L
|
||||||
|
|
||||||
|
private val telemetryTick = object : Runnable {
|
||||||
|
override fun run() {
|
||||||
|
if (connected) {
|
||||||
|
Thread {
|
||||||
|
val data = runCatching { telemetrySupplier() }.getOrNull()
|
||||||
|
if (data != null) {
|
||||||
|
sendFrame("device.telemetry", data)
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
handler.postDelayed(this, prefs.telemetryIntervalSec * 1000L)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun start() {
|
||||||
|
closedByUser = false
|
||||||
|
connectNow()
|
||||||
|
handler.removeCallbacks(telemetryTick)
|
||||||
|
handler.postDelayed(telemetryTick, prefs.telemetryIntervalSec * 1000L)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun rescheduleTelemetry() {
|
||||||
|
if (closedByUser) return
|
||||||
|
handler.removeCallbacks(telemetryTick)
|
||||||
|
handler.postDelayed(telemetryTick, prefs.telemetryIntervalSec * 1000L)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun reconnect() {
|
||||||
|
disconnectInternal()
|
||||||
|
retryDelayMs = 1500L
|
||||||
|
if (!closedByUser) connectNow()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun stop() {
|
||||||
|
closedByUser = true
|
||||||
|
handler.removeCallbacksAndMessages(null)
|
||||||
|
disconnectInternal()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun disconnectInternal() {
|
||||||
|
connected = false
|
||||||
|
runCatching { webSocket?.close(1000, "Reconnect/Stop") }
|
||||||
|
webSocket = null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun connectNow() {
|
||||||
|
if (closedByUser) return
|
||||||
|
val endpoint = prefs.buildDeviceWsEndpoint()
|
||||||
|
val req = try {
|
||||||
|
Request.Builder().url(endpoint).build()
|
||||||
|
} catch (e: Throwable) {
|
||||||
|
listener.onConnectionChanged(false, "地址格式错误: $endpoint (${e.message})")
|
||||||
|
scheduleReconnect()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
webSocket = client.newWebSocket(req, object : WebSocketListener() {
|
||||||
|
override fun onOpen(webSocket: WebSocket, response: Response) {
|
||||||
|
connected = true
|
||||||
|
retryDelayMs = 2000L
|
||||||
|
listener.onConnectionChanged(true, "已连接 $endpoint")
|
||||||
|
Thread {
|
||||||
|
val hello = runCatching { helloSupplier() }.getOrNull()
|
||||||
|
if (hello != null) sendFrame("device.hello", hello)
|
||||||
|
val tele = runCatching { telemetrySupplier() }.getOrNull()
|
||||||
|
if (tele != null) sendFrame("device.telemetry", tele)
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onMessage(webSocket: WebSocket, text: String) {
|
||||||
|
try {
|
||||||
|
val frame = JSONObject(text)
|
||||||
|
val type = frame.optString("type", "")
|
||||||
|
val payload = frame.optJSONObject("payload") ?: JSONObject()
|
||||||
|
listener.onHubFrame(type, payload)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
|
||||||
|
connected = false
|
||||||
|
listener.onConnectionChanged(false, "连接已断开 ($code $reason)")
|
||||||
|
scheduleReconnect()
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
|
||||||
|
connected = false
|
||||||
|
val msg = t.message ?: t.javaClass.simpleName
|
||||||
|
listener.onConnectionChanged(false, "无法连接 ${prefs.hubWsUrl}: $msg")
|
||||||
|
scheduleReconnect()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun scheduleReconnect() {
|
||||||
|
if (closedByUser) return
|
||||||
|
val delay = retryDelayMs
|
||||||
|
retryDelayMs = (retryDelayMs * 2).coerceAtMost(20_000L)
|
||||||
|
handler.postDelayed({ connectNow() }, delay)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendFrame(type: String, payload: JSONObject): Boolean {
|
||||||
|
val ws = webSocket ?: return false
|
||||||
|
val envelope = JSONObject().apply {
|
||||||
|
put("type", type)
|
||||||
|
put("msg_id", UUID.randomUUID().toString())
|
||||||
|
put("ts", System.currentTimeMillis())
|
||||||
|
put("payload", payload)
|
||||||
|
}
|
||||||
|
return ws.send(envelope.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
package com.pulsewall.app.ota
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.AlertDialog
|
||||||
|
import android.content.Intent
|
||||||
|
import android.widget.Toast
|
||||||
|
import androidx.core.content.FileProvider
|
||||||
|
import com.pulsewall.app.BuildConfig
|
||||||
|
import com.pulsewall.app.config.AppPrefs
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.launch
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.File
|
||||||
|
import java.io.FileInputStream
|
||||||
|
import java.io.FileOutputStream
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
data class OtaReleaseInfo(
|
||||||
|
val versionCode: Int,
|
||||||
|
val versionName: String,
|
||||||
|
val sizeBytes: Long,
|
||||||
|
val sha256: String,
|
||||||
|
val changelog: String,
|
||||||
|
val downloadUrl: String
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Self-update (OTA) engine against Python Hub:
|
||||||
|
* - Auto-checks /api/ota/latest or responds to Hub `ota.available` WS push
|
||||||
|
* - Verifies SHA-256 before installation
|
||||||
|
* - Root devices: supports one-tap silent `pm install -r -S` + auto relaunch
|
||||||
|
* - Non-root devices: falls back to Android standard FileProvider package installer
|
||||||
|
*/
|
||||||
|
class AppUpdateManager(
|
||||||
|
private val activity: Activity,
|
||||||
|
private val prefs: AppPrefs,
|
||||||
|
private val scope: CoroutineScope,
|
||||||
|
private val rootAvailableSupplier: () -> Boolean
|
||||||
|
) {
|
||||||
|
private val httpClient = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(15, TimeUnit.SECONDS)
|
||||||
|
.readTimeout(120, TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var checkingOrDownloading = false
|
||||||
|
|
||||||
|
fun checkForUpdate(silentIfLatest: Boolean = false) {
|
||||||
|
if (checkingOrDownloading) return
|
||||||
|
checkingOrDownloading = true
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val base = prefs.buildHubHttpBaseUrl()
|
||||||
|
val info = fetchLatestMeta(base)
|
||||||
|
if (info == null) {
|
||||||
|
if (!silentIfLatest) {
|
||||||
|
toast("中心桥暂未发布新版安装包")
|
||||||
|
}
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
if (info.versionCode > BuildConfig.VERSION_CODE) {
|
||||||
|
promptUpdateDialog(info)
|
||||||
|
} else if (!silentIfLatest) {
|
||||||
|
toast("当前已是最新版本 v${BuildConfig.VERSION_NAME} (build ${BuildConfig.VERSION_CODE})")
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
if (!silentIfLatest) {
|
||||||
|
toast("检测更新失败: ${t.message}")
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
checkingOrDownloading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun handleHubPush(payload: JSONObject) {
|
||||||
|
val vCode = payload.optInt("version_code", 0)
|
||||||
|
if (vCode <= BuildConfig.VERSION_CODE) return
|
||||||
|
val base = prefs.buildHubHttpBaseUrl()
|
||||||
|
val dlPath = payload.optString("download_path", "/api/ota/download/pulsewall-latest.apk")
|
||||||
|
val dlUrl = if (dlPath.startsWith("http")) dlPath else "$base$dlPath"
|
||||||
|
val info = OtaReleaseInfo(
|
||||||
|
versionCode = vCode,
|
||||||
|
versionName = payload.optString("version_name", "unknown"),
|
||||||
|
sizeBytes = payload.optLong("size_bytes", 0L),
|
||||||
|
sha256 = payload.optString("sha256", ""),
|
||||||
|
changelog = payload.optString("changelog", "发现新版本"),
|
||||||
|
downloadUrl = dlUrl
|
||||||
|
)
|
||||||
|
activity.runOnUiThread { promptUpdateDialog(info) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun fetchLatestMeta(hubHttpBase: String): OtaReleaseInfo? = withContext(Dispatchers.IO) {
|
||||||
|
val req = Request.Builder().url("$hubHttpBase/api/ota/latest").get().build()
|
||||||
|
httpClient.newCall(req).execute().use { resp ->
|
||||||
|
if (!resp.isSuccessful) return@withContext null
|
||||||
|
val obj = JSONObject(resp.body?.string().orEmpty())
|
||||||
|
if (!obj.optBoolean("available", false)) return@withContext null
|
||||||
|
val dlPath = obj.optString("download_path", "/api/ota/download/pulsewall-latest.apk")
|
||||||
|
OtaReleaseInfo(
|
||||||
|
versionCode = obj.optInt("version_code", 0),
|
||||||
|
versionName = obj.optString("version_name", "0.0.0"),
|
||||||
|
sizeBytes = obj.optLong("size_bytes", 0L),
|
||||||
|
sha256 = obj.optString("sha256", ""),
|
||||||
|
changelog = obj.optString("changelog", ""),
|
||||||
|
downloadUrl = "$hubHttpBase$dlPath"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun promptUpdateDialog(info: OtaReleaseInfo) {
|
||||||
|
val hasRoot = rootAvailableSupplier()
|
||||||
|
val mb = String.format("%.2f MB", info.sizeBytes / 1048576.0)
|
||||||
|
val msg = buildString {
|
||||||
|
appendLine("当前版本: v${BuildConfig.VERSION_NAME} (build ${BuildConfig.VERSION_CODE})")
|
||||||
|
appendLine("最新版本: v${info.versionName} (build ${info.versionCode}) · $mb")
|
||||||
|
if (info.changelog.isNotBlank()) {
|
||||||
|
appendLine()
|
||||||
|
appendLine("更新内容:")
|
||||||
|
append(info.changelog)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val builder = AlertDialog.Builder(activity)
|
||||||
|
.setTitle("发现 PulseWall 新版本")
|
||||||
|
.setMessage(msg)
|
||||||
|
.setNegativeButton("稍后", null)
|
||||||
|
|
||||||
|
if (hasRoot) {
|
||||||
|
builder.setPositiveButton("⚡ Root 静默更新并重启") { _, _ ->
|
||||||
|
downloadAndInstall(info, useRootSilent = true)
|
||||||
|
}
|
||||||
|
builder.setNeutralButton("常规安装") { _, _ ->
|
||||||
|
downloadAndInstall(info, useRootSilent = false)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
builder.setPositiveButton("下载并安装") { _, _ ->
|
||||||
|
downloadAndInstall(info, useRootSilent = false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
builder.show()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun downloadAndInstall(info: OtaReleaseInfo, useRootSilent: Boolean) {
|
||||||
|
if (checkingOrDownloading) return
|
||||||
|
checkingOrDownloading = true
|
||||||
|
toast("正在下载 v${info.versionName}...")
|
||||||
|
|
||||||
|
scope.launch {
|
||||||
|
try {
|
||||||
|
val apkFile = downloadApk(info)
|
||||||
|
if (info.sha256.isNotBlank()) {
|
||||||
|
val actual = sha256Of(apkFile)
|
||||||
|
if (!actual.equals(info.sha256, ignoreCase = true)) {
|
||||||
|
apkFile.delete()
|
||||||
|
toast("校验失败:安装包 SHA-256 不匹配,已中止更新")
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (useRootSilent) {
|
||||||
|
toast("校验通过,正在 Root 静默安装并重启...")
|
||||||
|
val ok = installSilentlyWithRoot(apkFile)
|
||||||
|
if (!ok) {
|
||||||
|
toast("Root 静默安装失败,已自动切换常规安装界面")
|
||||||
|
launchStandardInstaller(apkFile)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
launchStandardInstaller(apkFile)
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
toast("更新失败: ${t.message}")
|
||||||
|
} finally {
|
||||||
|
checkingOrDownloading = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun downloadApk(info: OtaReleaseInfo): File = withContext(Dispatchers.IO) {
|
||||||
|
val dir = File(activity.cacheDir, "ota").apply { mkdirs() }
|
||||||
|
val outFile = File(dir, "pulsewall-update.apk")
|
||||||
|
val req = Request.Builder().url(info.downloadUrl).get().build()
|
||||||
|
httpClient.newCall(req).execute().use { resp ->
|
||||||
|
if (!resp.isSuccessful) {
|
||||||
|
throw IllegalStateException("HTTP ${resp.code} downloading APK")
|
||||||
|
}
|
||||||
|
val body = resp.body ?: throw IllegalStateException("Empty APK response body")
|
||||||
|
body.byteStream().use { input ->
|
||||||
|
FileOutputStream(outFile).use { output ->
|
||||||
|
val buf = ByteArray(16384)
|
||||||
|
while (true) {
|
||||||
|
val n = input.read(buf)
|
||||||
|
if (n <= 0) break
|
||||||
|
output.write(buf, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outFile
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun sha256Of(file: File): String = withContext(Dispatchers.IO) {
|
||||||
|
val md = MessageDigest.getInstance("SHA-256")
|
||||||
|
FileInputStream(file).use { fis ->
|
||||||
|
val buf = ByteArray(16384)
|
||||||
|
while (true) {
|
||||||
|
val n = fis.read(buf)
|
||||||
|
if (n <= 0) break
|
||||||
|
md.update(buf, 0, n)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
md.digest().joinToString("") { "%02x".format(it) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun installSilentlyWithRoot(apkFile: File): Boolean = withContext(Dispatchers.IO) {
|
||||||
|
try {
|
||||||
|
val size = apkFile.length()
|
||||||
|
val safePath = apkFile.absolutePath.replace("'", "'\\''")
|
||||||
|
val cmd = "cat '$safePath' | pm install -r -S $size && am start -n ${BuildConfig.APPLICATION_ID}/.MainActivity"
|
||||||
|
val proc = ProcessBuilder("su", "-c", cmd).redirectErrorStream(true).start()
|
||||||
|
val finished = proc.waitFor(60, TimeUnit.SECONDS)
|
||||||
|
if (!finished) {
|
||||||
|
proc.destroyForcibly()
|
||||||
|
return@withContext false
|
||||||
|
}
|
||||||
|
val out = proc.inputStream.bufferedReader().readText()
|
||||||
|
proc.exitValue() == 0 && out.contains("Success", ignoreCase = true)
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun launchStandardInstaller(apkFile: File) {
|
||||||
|
val uri = FileProvider.getUriForFile(activity, "${BuildConfig.APPLICATION_ID}.fileprovider", apkFile)
|
||||||
|
val intent = Intent(Intent.ACTION_VIEW).apply {
|
||||||
|
setDataAndType(uri, "application/vnd.android.package-archive")
|
||||||
|
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
|
||||||
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
activity.startActivity(intent)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun toast(msg: String) {
|
||||||
|
activity.runOnUiThread {
|
||||||
|
Toast.makeText(activity, msg, Toast.LENGTH_LONG).show()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
package com.pulsewall.app.sentinel
|
||||||
|
|
||||||
|
import com.pulsewall.app.config.RepairAiConfig
|
||||||
|
import kotlinx.coroutines.Dispatchers
|
||||||
|
import kotlinx.coroutines.withContext
|
||||||
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
|
import okhttp3.OkHttpClient
|
||||||
|
import okhttp3.Request
|
||||||
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
|
data class RepairDecision(
|
||||||
|
val action: String, // "fix_locally" | "ask_upstream" | "error"
|
||||||
|
val fixedHtml: String? = null,
|
||||||
|
val fixSummary: String = "",
|
||||||
|
val clarificationQuestions: JSONArray = JSONArray(),
|
||||||
|
val errorMessage: String? = null
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* End-Side OpenAI-Compatible Repair Sentinel.
|
||||||
|
* Fixes HTML/CSS/Vue/JS/viewport compatibility errors locally, or escalates missing/ambiguous
|
||||||
|
* business data questions back to the upstream AI via Hub.
|
||||||
|
*/
|
||||||
|
class OpenAiRepairSentinel {
|
||||||
|
|
||||||
|
suspend fun diagnoseAndRepair(
|
||||||
|
cfg: RepairAiConfig,
|
||||||
|
currentHtml: String,
|
||||||
|
errors: List<String>,
|
||||||
|
displayProfile: JSONObject,
|
||||||
|
dataContext: JSONObject,
|
||||||
|
upstreamAnswers: JSONObject? = null
|
||||||
|
): RepairDecision = withContext(Dispatchers.IO) {
|
||||||
|
if (!cfg.enabled || cfg.apiKey.isBlank() || cfg.baseUrl.isBlank()) {
|
||||||
|
return@withContext RepairDecision(
|
||||||
|
action = "error",
|
||||||
|
errorMessage = "End-side Repair AI is disabled or missing API config from Hub."
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val client = OkHttpClient.Builder()
|
||||||
|
.connectTimeout(cfg.timeoutSec.toLong(), TimeUnit.SECONDS)
|
||||||
|
.readTimeout(cfg.timeoutSec.toLong(), TimeUnit.SECONDS)
|
||||||
|
.writeTimeout(cfg.timeoutSec.toLong(), TimeUnit.SECONDS)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
val systemPrompt = """
|
||||||
|
You are the PulseWall On-Device UI Repair Sentinel running on an Android 11 WebView.
|
||||||
|
Your job:
|
||||||
|
1. If the error is caused by HTML syntax, Vue/JS code bugs, CSS layout overflow, or Android 11 WebView compatibility:
|
||||||
|
Return JSON with action="fix_locally", the complete repaired HTML fragment in "fixed_html", and a brief "fix_summary".
|
||||||
|
IMPORTANT: Never fabricate unknown business/server metric data. Keep responsive styling compatible with viewport_css_w/h and WebView version.
|
||||||
|
Available built-in CSS classes: .pw-stack, .pw-row, .pw-between, .pw-grid-2, .pw-grid-auto, .pw-card, .pw-hero, .pw-muted, .pw-metric, .pw-pill, .pw-btn, .pw-btn-primary, .pw-btn-danger, .pw-btn-secondary, .pw-code, plus preloaded Tailwind-lite utilities.
|
||||||
|
Preloaded globals: `Vue` (Vue 3), `dayjs`, `PwIcons`.
|
||||||
|
Lazy offline local libs via `await window.PulseWall.loadLib(['plyr','hls','echarts','konva','three','rough','lodash','zustand','anime'])` -> globals: `Plyr`, `Hls`, `echarts`, `Konva`, `THREE`, `rough`, `_`, `Zustand`, `anime`. Never depend on blocked external CDNs when a local lib exists.
|
||||||
|
Bridge: `window.PulseWall.sendAction(id, label, customText)`.
|
||||||
|
2. If the error or missing rendering is caused by missing/ambiguous business data fields that only the upstream AI knows:
|
||||||
|
Return JSON with action="ask_upstream" and "clarification_questions": [{"field": "...", "question": "..."}].
|
||||||
|
|
||||||
|
Respond ONLY with valid JSON matching:
|
||||||
|
{
|
||||||
|
"action": "fix_locally" | "ask_upstream",
|
||||||
|
"fixed_html": "<repaired html if fix_locally else null>",
|
||||||
|
"fix_summary": "short explanation",
|
||||||
|
"clarification_questions": [{"field": "...", "question": "..."}]
|
||||||
|
}
|
||||||
|
""".trimIndent()
|
||||||
|
|
||||||
|
val userPayload = JSONObject().apply {
|
||||||
|
put("device_display_profile", displayProfile)
|
||||||
|
put("errors", JSONArray(errors))
|
||||||
|
put("data_context", dataContext)
|
||||||
|
if (upstreamAnswers != null) {
|
||||||
|
put("upstream_clarification_answers", upstreamAnswers)
|
||||||
|
}
|
||||||
|
put("html_code", currentHtml)
|
||||||
|
}
|
||||||
|
|
||||||
|
val reqBody = JSONObject().apply {
|
||||||
|
put("model", cfg.model)
|
||||||
|
put("temperature", 0.1)
|
||||||
|
put("messages", JSONArray().apply {
|
||||||
|
put(JSONObject().put("role", "system").put("content", systemPrompt))
|
||||||
|
put(JSONObject().put("role", "user").put("content", userPayload.toString()))
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
val endpoint = cfg.baseUrl.trimEnd('/') + "/chat/completions"
|
||||||
|
val request = Request.Builder()
|
||||||
|
.url(endpoint)
|
||||||
|
.header("Authorization", "Bearer ${cfg.apiKey}")
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.post(reqBody.toString().toRequestBody("application/json; charset=utf-8".toMediaType()))
|
||||||
|
.build()
|
||||||
|
|
||||||
|
try {
|
||||||
|
client.newCall(request).execute().use { resp ->
|
||||||
|
val raw = resp.body?.string().orEmpty()
|
||||||
|
if (!resp.isSuccessful) {
|
||||||
|
return@withContext RepairDecision(
|
||||||
|
action = "error",
|
||||||
|
errorMessage = "OpenAI API HTTP ${resp.code}: ${raw.take(240)}"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val root = JSONObject(raw)
|
||||||
|
val content = root.getJSONArray("choices")
|
||||||
|
.getJSONObject(0)
|
||||||
|
.getJSONObject("message")
|
||||||
|
.getString("content")
|
||||||
|
.trim()
|
||||||
|
val jsonStr = extractJsonBlock(content)
|
||||||
|
val parsed = JSONObject(jsonStr)
|
||||||
|
val action = parsed.optString("action", "error")
|
||||||
|
RepairDecision(
|
||||||
|
action = action,
|
||||||
|
fixedHtml = if (parsed.isNull("fixed_html")) null else parsed.optString("fixed_html", ""),
|
||||||
|
fixSummary = parsed.optString("fix_summary", ""),
|
||||||
|
clarificationQuestions = parsed.optJSONArray("clarification_questions") ?: JSONArray()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
} catch (t: Throwable) {
|
||||||
|
RepairDecision(action = "error", errorMessage = t.message ?: t.javaClass.simpleName)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun extractJsonBlock(text: String): String {
|
||||||
|
val fenced = Regex("```(?:json)?\\s*([\\s\\S]*?)```").find(text)
|
||||||
|
if (fenced != null) return fenced.groupValues[1].trim()
|
||||||
|
val first = text.indexOf('{')
|
||||||
|
val last = text.lastIndexOf('}')
|
||||||
|
return if (first >= 0 && last > first) text.substring(first, last + 1) else text
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
package com.pulsewall.app.service
|
||||||
|
|
||||||
|
import android.content.BroadcastReceiver
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import com.pulsewall.app.MainActivity
|
||||||
|
|
||||||
|
class BootReceiver : BroadcastReceiver() {
|
||||||
|
override fun onReceive(context: Context, intent: Intent?) {
|
||||||
|
val action = intent?.action ?: return
|
||||||
|
if (action == Intent.ACTION_BOOT_COMPLETED || action == Intent.ACTION_LOCKED_BOOT_COMPLETED) {
|
||||||
|
runCatching {
|
||||||
|
context.startForegroundService(Intent(context, PulseWallKeepAliveService::class.java))
|
||||||
|
}
|
||||||
|
runCatching {
|
||||||
|
val launch = Intent(context, MainActivity::class.java).apply {
|
||||||
|
addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||||
|
}
|
||||||
|
context.startActivity(launch)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
package com.pulsewall.app.service
|
||||||
|
|
||||||
|
import android.app.Notification
|
||||||
|
import android.app.NotificationChannel
|
||||||
|
import android.app.NotificationManager
|
||||||
|
import android.app.Service
|
||||||
|
import android.content.Intent
|
||||||
|
import android.os.IBinder
|
||||||
|
|
||||||
|
class PulseWallKeepAliveService : Service() {
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
val channelId = "pulsewall_keepalive"
|
||||||
|
val nm = getSystemService(NotificationManager::class.java)
|
||||||
|
val ch = NotificationChannel(channelId, "PulseWall 后台保活", NotificationManager.IMPORTANCE_LOW)
|
||||||
|
nm.createNotificationChannel(ch)
|
||||||
|
val notif = Notification.Builder(this, channelId)
|
||||||
|
.setContentTitle("PulseWall 运行中")
|
||||||
|
.setContentText("已与中心桥保持实时通信")
|
||||||
|
.setSmallIcon(android.R.drawable.stat_notify_sync)
|
||||||
|
.build()
|
||||||
|
startForeground(1001, notif)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int = START_STICKY
|
||||||
|
|
||||||
|
override fun onBind(intent: Intent?): IBinder? = null
|
||||||
|
}
|
||||||
@@ -0,0 +1,398 @@
|
|||||||
|
package com.pulsewall.app.telemetry
|
||||||
|
|
||||||
|
import android.app.Activity
|
||||||
|
import android.app.ActivityManager
|
||||||
|
import android.app.UiModeManager
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.Intent
|
||||||
|
import android.content.IntentFilter
|
||||||
|
import android.content.pm.PackageManager
|
||||||
|
import android.content.res.Configuration
|
||||||
|
import android.net.wifi.WifiManager
|
||||||
|
import android.os.BatteryManager
|
||||||
|
import android.os.Build
|
||||||
|
import android.os.Environment
|
||||||
|
import android.os.PowerManager
|
||||||
|
import android.os.Process as AndroidProcess
|
||||||
|
import android.os.StatFs
|
||||||
|
import android.view.WindowInsets
|
||||||
|
import androidx.webkit.WebViewCompat
|
||||||
|
import com.pulsewall.app.BuildConfig
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.BufferedReader
|
||||||
|
import java.io.BufferedWriter
|
||||||
|
import java.io.File
|
||||||
|
import java.io.InputStreamReader
|
||||||
|
import java.io.OutputStreamWriter
|
||||||
|
import java.util.UUID
|
||||||
|
import kotlin.math.roundToInt
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Layered Android 11 (API 30) capability & telemetry collector.
|
||||||
|
* Keeps ONE persistent interactive `su` session so Magisk/SuperSU never spams
|
||||||
|
* "granted superuser rights" toasts on every 10-second telemetry tick.
|
||||||
|
*/
|
||||||
|
class DeviceTelemetryCollector(private val activity: Activity) {
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var rootChecked = false
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var hasRoot = false
|
||||||
|
|
||||||
|
private val suLock = Any()
|
||||||
|
private var suProcess: Process? = null
|
||||||
|
private var suWriter: BufferedWriter? = null
|
||||||
|
private var suReader: BufferedReader? = null
|
||||||
|
private var rootKeepAliveApplied = false
|
||||||
|
private var prevCpuTotal = -1L
|
||||||
|
private var prevCpuIdle = -1L
|
||||||
|
|
||||||
|
fun isRootAvailable(): Boolean {
|
||||||
|
if (!rootChecked) {
|
||||||
|
synchronized(suLock) {
|
||||||
|
if (!rootChecked) {
|
||||||
|
hasRoot = initPersistentSuSession()
|
||||||
|
rootChecked = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hasRoot
|
||||||
|
}
|
||||||
|
|
||||||
|
fun detectCapabilities(): JSONArray {
|
||||||
|
val arr = JSONArray()
|
||||||
|
arr.put("basic")
|
||||||
|
if (isRootAvailable()) {
|
||||||
|
arr.put("root")
|
||||||
|
}
|
||||||
|
return arr
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun initPersistentSuSession(): Boolean {
|
||||||
|
val candidates = listOf(
|
||||||
|
"/system/bin/su",
|
||||||
|
"/system/xbin/su",
|
||||||
|
"/sbin/su",
|
||||||
|
"/su/bin/su",
|
||||||
|
"/data/adb/ksu/bin/su",
|
||||||
|
"/data/adb/magisk/magisk"
|
||||||
|
)
|
||||||
|
if (candidates.none { File(it).exists() }) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val proc = ProcessBuilder("su").redirectErrorStream(true).start()
|
||||||
|
val writer = BufferedWriter(OutputStreamWriter(proc.outputStream))
|
||||||
|
val reader = BufferedReader(InputStreamReader(proc.inputStream))
|
||||||
|
suProcess = proc
|
||||||
|
suWriter = writer
|
||||||
|
suReader = reader
|
||||||
|
val out = execOnPersistentSuLocked("id")
|
||||||
|
if (out != null && out.contains("uid=0")) {
|
||||||
|
applyRootKeepAliveLocked()
|
||||||
|
true
|
||||||
|
} else {
|
||||||
|
closeSuLocked()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
closeSuLocked()
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun execOnPersistentSuLocked(cmd: String): String? {
|
||||||
|
val proc = suProcess ?: return null
|
||||||
|
val writer = suWriter ?: return null
|
||||||
|
val reader = suReader ?: return null
|
||||||
|
if (!proc.isAlive) {
|
||||||
|
closeSuLocked()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
val marker = "__PW_DONE_${UUID.randomUUID().toString().take(8)}__"
|
||||||
|
writer.write("$cmd\necho $marker\n")
|
||||||
|
writer.flush()
|
||||||
|
val sb = StringBuilder()
|
||||||
|
var lines = 0
|
||||||
|
while (lines < 64) {
|
||||||
|
val line = reader.readLine() ?: break
|
||||||
|
if (line.trim() == marker) break
|
||||||
|
if (sb.isNotEmpty()) sb.append('\n')
|
||||||
|
sb.append(line)
|
||||||
|
lines++
|
||||||
|
}
|
||||||
|
sb.toString().trim()
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
closeSuLocked()
|
||||||
|
null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun runRootCommand(cmd: String): String? {
|
||||||
|
if (!isRootAvailable()) return null
|
||||||
|
synchronized(suLock) {
|
||||||
|
return execOnPersistentSuLocked(cmd)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun applyRootKeepAliveLocked() {
|
||||||
|
if (rootKeepAliveApplied) return
|
||||||
|
rootKeepAliveApplied = true
|
||||||
|
val pkg = BuildConfig.APPLICATION_ID
|
||||||
|
val pid = AndroidProcess.myPid()
|
||||||
|
// Whitelist from Doze, allow unrestricted background execution, and raise OOM protection
|
||||||
|
execOnPersistentSuLocked(
|
||||||
|
"dumpsys deviceidle whitelist +$pkg >/dev/null 2>&1; " +
|
||||||
|
"cmd appops set $pkg RUN_IN_BACKGROUND allow >/dev/null 2>&1; " +
|
||||||
|
"cmd appops set $pkg RUN_ANY_IN_BACKGROUND allow >/dev/null 2>&1; " +
|
||||||
|
"echo -900 > /proc/$pid/oom_score_adj 2>/dev/null; true"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sampleCpuUsagePct(): Double? {
|
||||||
|
val line = runCatching {
|
||||||
|
val f = File("/proc/stat")
|
||||||
|
if (f.canRead()) f.bufferedReader().use { it.readLine() } else null
|
||||||
|
}.getOrNull() ?: if (hasRoot) runRootCommand("head -n 1 /proc/stat") else null
|
||||||
|
|
||||||
|
if (line.isNullOrBlank() || !line.startsWith("cpu")) return null
|
||||||
|
val nums = line.trim().split(Regex("\\s+")).drop(1).mapNotNull { it.toLongOrNull() }
|
||||||
|
if (nums.size < 4) return null
|
||||||
|
val idle = nums[3] + (nums.getOrNull(4) ?: 0L)
|
||||||
|
val total = nums.sum()
|
||||||
|
|
||||||
|
val result = if (prevCpuTotal > 0 && total > prevCpuTotal) {
|
||||||
|
val diffTotal = total - prevCpuTotal
|
||||||
|
val diffIdle = (idle - prevCpuIdle).coerceAtLeast(0L)
|
||||||
|
val pct = ((diffTotal - diffIdle).toDouble() / diffTotal.toDouble()) * 100.0
|
||||||
|
(pct.coerceIn(0.0, 100.0) * 10.0).roundToInt() / 10.0
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
prevCpuTotal = total
|
||||||
|
prevCpuIdle = idle
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sampleGpuUsagePct(): Double? {
|
||||||
|
val candidates = listOf(
|
||||||
|
"/sys/class/mpgpu/utilization",
|
||||||
|
"/sys/class/kgsl/kgsl-3d0/gpu_busy_percentage",
|
||||||
|
"/sys/class/misc/mali0/device/utilization"
|
||||||
|
)
|
||||||
|
for (path in candidates) {
|
||||||
|
val raw = runCatching {
|
||||||
|
val f = File(path)
|
||||||
|
if (f.canRead()) f.readText().trim() else null
|
||||||
|
}.getOrNull() ?: if (hasRoot) runRootCommand("cat $path 2>/dev/null") else null
|
||||||
|
if (!raw.isNullOrBlank()) {
|
||||||
|
val num = Regex("[0-9]+(?:\\.[0-9]+)?").find(raw)?.value?.toDoubleOrNull()
|
||||||
|
if (num != null && num in 0.0..100.0) {
|
||||||
|
return (num * 10.0).roundToInt() / 10.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Adreno gpubusy fallback: "<busy> <total>"
|
||||||
|
val adreno = runCatching {
|
||||||
|
val f = File("/sys/class/kgsl/kgsl-3d0/gpubusy")
|
||||||
|
if (f.canRead()) f.readText().trim() else null
|
||||||
|
}.getOrNull() ?: if (hasRoot) runRootCommand("cat /sys/class/kgsl/kgsl-3d0/gpubusy 2>/dev/null") else null
|
||||||
|
if (!adreno.isNullOrBlank()) {
|
||||||
|
val parts = adreno.split(Regex("\\s+")).mapNotNull { it.toDoubleOrNull() }
|
||||||
|
if (parts.size >= 2 && parts[1] > 0) {
|
||||||
|
val pct = ((parts[0] / parts[1]) * 100.0).coerceIn(0.0, 100.0)
|
||||||
|
return (pct * 10.0).roundToInt() / 10.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readStorageMb(): Pair<Long, Long>? {
|
||||||
|
return runCatching {
|
||||||
|
val stat = StatFs(Environment.getDataDirectory().path)
|
||||||
|
val totalMb = stat.totalBytes / (1024L * 1024L)
|
||||||
|
val availMb = stat.availableBytes / (1024L * 1024L)
|
||||||
|
val usedMb = (totalMb - availMb).coerceAtLeast(0L)
|
||||||
|
usedMb to totalMb
|
||||||
|
}.getOrNull()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun closeSuLocked() {
|
||||||
|
runCatching { suWriter?.write("exit\n"); suWriter?.flush() }
|
||||||
|
runCatching { suWriter?.close() }
|
||||||
|
runCatching { suReader?.close() }
|
||||||
|
runCatching { suProcess?.destroy() }
|
||||||
|
suWriter = null
|
||||||
|
suReader = null
|
||||||
|
suProcess = null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun close() {
|
||||||
|
synchronized(suLock) {
|
||||||
|
closeSuLocked()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun collectDisplayProfile(): JSONObject {
|
||||||
|
val dm = activity.resources.displayMetrics
|
||||||
|
val cfg = activity.resources.configuration
|
||||||
|
val wm = activity.windowManager
|
||||||
|
val bounds = wm.currentWindowMetrics.bounds
|
||||||
|
val insets = wm.currentWindowMetrics.windowInsets.getInsetsIgnoringVisibility(
|
||||||
|
WindowInsets.Type.systemBars()
|
||||||
|
)
|
||||||
|
val density = dm.density.coerceAtLeast(1f)
|
||||||
|
val widthPx = bounds.width()
|
||||||
|
val heightPx = bounds.height()
|
||||||
|
val cssW = (widthPx / density).roundToInt()
|
||||||
|
val cssH = (heightPx / density).roundToInt()
|
||||||
|
val safeTopDp = (insets.top / density).roundToInt()
|
||||||
|
val safeBottomDp = (insets.bottom / density).roundToInt()
|
||||||
|
|
||||||
|
val orientation = if (cfg.orientation == Configuration.ORIENTATION_LANDSCAPE) "landscape" else "portrait"
|
||||||
|
val uiModeMgr = activity.getSystemService(Context.UI_MODE_SERVICE) as? UiModeManager
|
||||||
|
val isTvMode = uiModeMgr?.currentModeType == Configuration.UI_MODE_TYPE_TELEVISION
|
||||||
|
val hasTouch = activity.packageManager.hasSystemFeature(PackageManager.FEATURE_TOUCHSCREEN)
|
||||||
|
val deviceType = when {
|
||||||
|
isTvMode || !hasTouch -> "tv"
|
||||||
|
cfg.smallestScreenWidthDp >= 600 -> "tablet"
|
||||||
|
else -> "phone"
|
||||||
|
}
|
||||||
|
val webViewPkg = WebViewCompat.getCurrentWebViewPackage(activity)
|
||||||
|
val webViewVer = webViewPkg?.versionName ?: "unknown"
|
||||||
|
|
||||||
|
return JSONObject().apply {
|
||||||
|
put("device_type", deviceType)
|
||||||
|
put("input_mode", if (deviceType == "tv") "remote" else "touch")
|
||||||
|
put("orientation", orientation)
|
||||||
|
put("width_px", widthPx)
|
||||||
|
put("height_px", heightPx)
|
||||||
|
put("viewport_css_w", cssW)
|
||||||
|
put("viewport_css_h", cssH)
|
||||||
|
put("dpr", density.toDouble())
|
||||||
|
put("safe_area_top_dp", safeTopDp)
|
||||||
|
put("safe_area_bottom_dp", safeBottomDp)
|
||||||
|
put("font_scale", cfg.fontScale.toDouble())
|
||||||
|
put("webview_version", webViewVer)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fun collectHelloPayload(deviceId: String, deviceName: String): JSONObject {
|
||||||
|
return JSONObject().apply {
|
||||||
|
put("device_id", deviceId)
|
||||||
|
put("device_name", deviceName)
|
||||||
|
put("model", "${Build.MANUFACTURER} ${Build.MODEL}")
|
||||||
|
put("android_sdk", Build.VERSION.SDK_INT)
|
||||||
|
put("android_release", Build.VERSION.RELEASE ?: "11")
|
||||||
|
put("app_version", "${BuildConfig.VERSION_NAME} (${BuildConfig.VERSION_CODE})")
|
||||||
|
put("capabilities", detectCapabilities())
|
||||||
|
put("display_profile", collectDisplayProfile())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun readThermalZonesDirect(): JSONObject {
|
||||||
|
val thermalZones = JSONObject()
|
||||||
|
val dir = File("/sys/class/thermal")
|
||||||
|
val zones = dir.listFiles { f -> f.name.startsWith("thermal_zone") } ?: return thermalZones
|
||||||
|
var count = 0
|
||||||
|
for (z in zones) {
|
||||||
|
if (count >= 8) break
|
||||||
|
val typeFile = File(z, "type")
|
||||||
|
val tempFile = File(z, "temp")
|
||||||
|
if (typeFile.canRead() && tempFile.canRead()) {
|
||||||
|
val t = runCatching { typeFile.readText().trim() }.getOrNull()
|
||||||
|
val num = runCatching { tempFile.readText().trim().toDoubleOrNull() }.getOrNull()
|
||||||
|
if (!t.isNullOrBlank() && num != null) {
|
||||||
|
val celsius = if (num > 1000.0) num / 1000.0 else if (num > 150.0) num / 10.0 else num
|
||||||
|
if (celsius in -10.0..130.0) {
|
||||||
|
thermalZones.put(t, (celsius * 10).roundToInt() / 10.0)
|
||||||
|
count++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return thermalZones
|
||||||
|
}
|
||||||
|
|
||||||
|
fun collectTelemetryPayload(): JSONObject {
|
||||||
|
val ctx = activity.applicationContext
|
||||||
|
val batIntent = ctx.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
|
||||||
|
val level = batIntent?.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) ?: -1
|
||||||
|
val scale = batIntent?.getIntExtra(BatteryManager.EXTRA_SCALE, 100) ?: 100
|
||||||
|
val batteryPct = if (level >= 0 && scale > 0) (level * 100) / scale else null
|
||||||
|
val status = batIntent?.getIntExtra(BatteryManager.EXTRA_STATUS, -1) ?: -1
|
||||||
|
val isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL
|
||||||
|
val tempTenth = batIntent?.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, Int.MIN_VALUE) ?: Int.MIN_VALUE
|
||||||
|
val batteryTempC = if (tempTenth != Int.MIN_VALUE) tempTenth / 10.0 else null
|
||||||
|
|
||||||
|
val bm = ctx.getSystemService(Context.BATTERY_SERVICE) as? BatteryManager
|
||||||
|
val currentUa = bm?.getIntProperty(BatteryManager.BATTERY_PROPERTY_CURRENT_NOW)
|
||||||
|
var currentMa = if (currentUa != null && currentUa != Int.MIN_VALUE) currentUa / 1000 else null
|
||||||
|
|
||||||
|
val am = ctx.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
|
||||||
|
val memInfo = ActivityManager.MemoryInfo()
|
||||||
|
am.getMemoryInfo(memInfo)
|
||||||
|
val totalMb = (memInfo.totalMem / (1024 * 1024)).toInt()
|
||||||
|
val usedMb = ((memInfo.totalMem - memInfo.availMem) / (1024 * 1024)).toInt()
|
||||||
|
|
||||||
|
val pm = ctx.getSystemService(Context.POWER_SERVICE) as PowerManager
|
||||||
|
val screenOn = pm.isInteractive
|
||||||
|
|
||||||
|
val wifiMgr = ctx.getSystemService(Context.WIFI_SERVICE) as? WifiManager
|
||||||
|
val rssi = try {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
wifiMgr?.connectionInfo?.rssi
|
||||||
|
} catch (_: Throwable) {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try direct non-root read first; only use single persistent su session if needed
|
||||||
|
val thermalZones = readThermalZonesDirect()
|
||||||
|
if (thermalZones.length() == 0 && hasRoot) {
|
||||||
|
val thermalRaw = runRootCommand(
|
||||||
|
"for z in /sys/class/thermal/thermal_zone*; do " +
|
||||||
|
"t=$(cat \$z/type 2>/dev/null); v=$(cat \$z/temp 2>/dev/null); " +
|
||||||
|
"if [ -n \"\$t\" ] && [ -n \"\$v\" ]; then echo \"\$t=\$v\"; fi; done | head -n 8"
|
||||||
|
)
|
||||||
|
thermalRaw?.lines()?.forEach { line ->
|
||||||
|
val idx = line.indexOf('=')
|
||||||
|
if (idx > 0) {
|
||||||
|
val key = line.substring(0, idx).trim()
|
||||||
|
val num = line.substring(idx + 1).trim().toDoubleOrNull()
|
||||||
|
if (num != null) {
|
||||||
|
val celsius = if (num > 1000.0) num / 1000.0 else if (num > 150.0) num / 10.0 else num
|
||||||
|
if (celsius in -10.0..130.0) {
|
||||||
|
thermalZones.put(key, (celsius * 10).roundToInt() / 10.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val cpuPct = sampleCpuUsagePct()
|
||||||
|
val gpuPct = sampleGpuUsagePct()
|
||||||
|
val storage = readStorageMb()
|
||||||
|
|
||||||
|
return JSONObject().apply {
|
||||||
|
if (batteryPct != null) put("battery_pct", batteryPct)
|
||||||
|
put("is_charging", isCharging)
|
||||||
|
if (batteryTempC != null) put("battery_temp_c", batteryTempC)
|
||||||
|
if (currentMa != null) put("battery_current_ma", currentMa)
|
||||||
|
if (cpuPct != null) put("cpu_usage_pct", cpuPct)
|
||||||
|
if (gpuPct != null) put("gpu_usage_pct", gpuPct)
|
||||||
|
put("mem_used_mb", usedMb)
|
||||||
|
put("mem_total_mb", totalMb)
|
||||||
|
if (storage != null) {
|
||||||
|
put("storage_used_mb", storage.first)
|
||||||
|
put("storage_total_mb", storage.second)
|
||||||
|
}
|
||||||
|
put("thermal_zones", thermalZones)
|
||||||
|
if (rssi != null && rssi > -127) put("wifi_rssi_dbm", rssi)
|
||||||
|
put("screen_on", screenOn)
|
||||||
|
put("display_profile", collectDisplayProfile())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<resources>
|
||||||
|
<style name="Theme.PulseWall" parent="Theme.AppCompat.NoActionBar">
|
||||||
|
<item name="android:windowBackground">#0A0F1D</item>
|
||||||
|
<item name="android:statusBarColor">#0A0F1D</item>
|
||||||
|
<item name="android:navigationBarColor">#0A0F1D</item>
|
||||||
|
<item name="colorPrimary">#38BDF8</item>
|
||||||
|
<item name="colorAccent">#38BDF8</item>
|
||||||
|
</style>
|
||||||
|
</resources>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<paths>
|
||||||
|
<cache-path name="ota_apks" path="ota/" />
|
||||||
|
</paths>
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.application") version "8.5.2" apply false
|
||||||
|
id("org.jetbrains.kotlin.android") version "1.9.24" apply false
|
||||||
|
}
|
||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
export HOME="$ROOT_DIR/.toolchain/home"
|
||||||
|
export JAVA_HOME="$ROOT_DIR/.toolchain/jdk17"
|
||||||
|
export ANDROID_HOME="$ROOT_DIR/.toolchain/android-sdk"
|
||||||
|
export ANDROID_SDK_ROOT="$ANDROID_HOME"
|
||||||
|
export ANDROID_USER_HOME="$HOME/.android"
|
||||||
|
export GRADLE_USER_HOME="$ROOT_DIR/.toolchain/gradle-home"
|
||||||
|
mkdir -p "$ANDROID_USER_HOME"
|
||||||
|
export PATH="$JAVA_HOME/bin:$ROOT_DIR/.toolchain/gradle/gradle-8.7/bin:$ANDROID_HOME/platform-tools:$PATH"
|
||||||
|
|
||||||
|
VERSION_CODE="${PW_VERSION_CODE:-1}"
|
||||||
|
VERSION_NAME="${PW_VERSION_NAME:-0.1.0}"
|
||||||
|
CHANGELOG="${PW_CHANGELOG:-PulseWall 更新包 v${VERSION_NAME} (build ${VERSION_CODE})}"
|
||||||
|
|
||||||
|
cd "$ROOT_DIR/android"
|
||||||
|
gradle assembleDebug --no-daemon -PpwVersionCode="$VERSION_CODE" -PpwVersionName="$VERSION_NAME" "$@"
|
||||||
|
|
||||||
|
APK_SRC="$ROOT_DIR/android/app/build/outputs/apk/debug/app-debug.apk"
|
||||||
|
RELEASE_DIR="$ROOT_DIR/hub/releases"
|
||||||
|
mkdir -p "$RELEASE_DIR"
|
||||||
|
APK_DST="$RELEASE_DIR/pulsewall-latest.apk"
|
||||||
|
cp -f "$APK_SRC" "$APK_DST"
|
||||||
|
|
||||||
|
python3 - "$APK_DST" "$RELEASE_DIR/latest.json" "$VERSION_CODE" "$VERSION_NAME" "$CHANGELOG" <<'PY'
|
||||||
|
import hashlib, json, os, sys, time
|
||||||
|
apk_path, meta_path, vcode, vname, changelog = sys.argv[1:]
|
||||||
|
h = hashlib.sha256()
|
||||||
|
with open(apk_path, "rb") as f:
|
||||||
|
for chunk in iter(lambda: f.read(65536), b""):
|
||||||
|
h.update(chunk)
|
||||||
|
meta = {
|
||||||
|
"version_code": int(vcode),
|
||||||
|
"version_name": vname,
|
||||||
|
"filename": os.path.basename(apk_path),
|
||||||
|
"size_bytes": os.path.getsize(apk_path),
|
||||||
|
"sha256": h.hexdigest(),
|
||||||
|
"changelog": changelog,
|
||||||
|
"updated_at_ms": int(time.time() * 1000),
|
||||||
|
}
|
||||||
|
with open(meta_path, "w", encoding="utf-8") as f:
|
||||||
|
json.dump(meta, f, ensure_ascii=False, indent=2)
|
||||||
|
print("Published OTA release:", json.dumps(meta, ensure_ascii=False))
|
||||||
|
PY
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
org.gradle.jvmargs=-Xmx2560m -Dfile.encoding=UTF-8
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
kotlin.code.style=official
|
||||||
Binary file not shown.
@@ -0,0 +1,18 @@
|
|||||||
|
pluginManagement {
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
gradlePluginPortal()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencyResolutionManagement {
|
||||||
|
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
|
||||||
|
repositories {
|
||||||
|
google()
|
||||||
|
mavenCentral()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProject.name = "PulseWall"
|
||||||
|
include(":app")
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
import fs from 'fs'
|
||||||
|
import path from 'path'
|
||||||
|
import zlib from 'zlib'
|
||||||
|
import { fileURLToPath } from 'url'
|
||||||
|
import * as esbuild from 'esbuild'
|
||||||
|
|
||||||
|
const __dirname = path.dirname(fileURLToPath(import.meta.url))
|
||||||
|
const nm = path.resolve(__dirname, 'node_modules')
|
||||||
|
const outDir = path.resolve(__dirname, '../app/src/main/assets/pulsewall/libs')
|
||||||
|
fs.mkdirSync(outDir, { recursive: true })
|
||||||
|
|
||||||
|
function reportSize(filename) {
|
||||||
|
const full = path.join(outDir, filename)
|
||||||
|
const buf = fs.readFileSync(full)
|
||||||
|
const gz = zlib.gzipSync(buf, { level: 9 })
|
||||||
|
return {
|
||||||
|
file: filename,
|
||||||
|
raw_kb: Number((buf.length / 1024).toFixed(1)),
|
||||||
|
gzip_kb: Number((gz.length / 1024).toFixed(1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function copyDist(srcRel, dstName) {
|
||||||
|
const src = path.join(nm, srcRel)
|
||||||
|
fs.copyFileSync(src, path.join(outDir, dstName))
|
||||||
|
return reportSize(dstName)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function bundleEntry(code, outName, globalName) {
|
||||||
|
await esbuild.build({
|
||||||
|
stdin: {
|
||||||
|
contents: code,
|
||||||
|
resolveDir: __dirname,
|
||||||
|
loader: 'js'
|
||||||
|
},
|
||||||
|
bundle: true,
|
||||||
|
minify: true,
|
||||||
|
format: 'iife',
|
||||||
|
globalName,
|
||||||
|
target: ['chrome83', 'es2020'],
|
||||||
|
outfile: path.join(outDir, outName)
|
||||||
|
})
|
||||||
|
return reportSize(outName)
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateTailwindLiteCss() {
|
||||||
|
const css = `
|
||||||
|
/* PulseWall Prebuilt Tailwind-Compatible Utility Subset (Android 11 WebView safe, zero JS runtime) */
|
||||||
|
.flex{display:flex}.inline-flex{display:inline-flex}.grid{display:grid}.block{display:block}.inline-block{display:inline-block}.hidden{display:none}
|
||||||
|
.flex-col{flex-direction:column}.flex-row{flex-direction:row}.flex-wrap{flex-wrap:wrap}.flex-1{flex:1 1 0%}.shrink-0{flex-shrink:0}
|
||||||
|
.items-center{align-items:center}.items-start{align-items:flex-start}.items-end{align-items:flex-end}.items-stretch{align-items:stretch}
|
||||||
|
.justify-between{justify-content:space-between}.justify-center{justify-content:center}.justify-end{justify-content:flex-end}.justify-start{justify-content:flex-start}
|
||||||
|
.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}
|
||||||
|
.col-span-2{grid-column:span 2/span 2}.col-span-full{grid-column:1/-1}
|
||||||
|
.gap-1{gap:4px}.gap-2{gap:8px}.gap-3{gap:12px}.gap-4{gap:16px}.gap-5{gap:20px}.gap-6{gap:24px}
|
||||||
|
.space-y-2>*+*{margin-top:8px}.space-y-3>*+*{margin-top:12px}.space-y-4>*+*{margin-top:16px}
|
||||||
|
.p-1{padding:4px}.p-2{padding:8px}.p-3{padding:12px}.p-4{padding:16px}.p-5{padding:20px}.p-6{padding:24px}
|
||||||
|
.px-2{padding-left:8px;padding-right:8px}.px-3{padding-left:12px;padding-right:12px}.px-4{padding-left:16px;padding-right:16px}.px-5{padding-left:20px;padding-right:20px}
|
||||||
|
.py-1{padding-top:4px;padding-bottom:4px}.py-2{padding-top:8px;padding-bottom:8px}.py-3{padding-top:12px;padding-bottom:12px}.py-4{padding-top:16px;padding-bottom:16px}
|
||||||
|
.m-0{margin:0}.mt-1{margin-top:4px}.mt-2{margin-top:8px}.mt-3{margin-top:12px}.mt-4{margin-top:16px}.mb-2{margin-bottom:8px}.mb-3{margin-bottom:12px}.mb-4{margin-bottom:16px}.mx-auto{margin-left:auto;margin-right:auto}
|
||||||
|
.w-full{width:100%}.h-full{height:100%}.min-h-screen{min-height:100vh}.max-w-full{max-width:100%}.aspect-video{aspect-ratio:16/9}
|
||||||
|
.relative{position:relative}.absolute{position:absolute}.inset-0{top:0;right:0;bottom:0;left:0}.overflow-hidden{overflow:hidden}.overflow-auto{overflow:auto}
|
||||||
|
.rounded{border-radius:6px}.rounded-lg{border-radius:10px}.rounded-xl{border-radius:14px}.rounded-2xl{border-radius:18px}.rounded-full{border-radius:9999px}
|
||||||
|
.border{border:1px solid rgba(148,163,184,0.22)}.border-slate-700{border-color:#334155}.border-slate-800{border-color:#1e293b}.border-cyan-500{border-color:#06b6d4}.border-teal-400{border-color:#2dd4bf}.border-amber-500{border-color:#f59e0b}.border-red-500{border-color:#ef4444}
|
||||||
|
.text-xs{font-size:12px;line-height:16px}.text-sm{font-size:14px;line-height:20px}.text-base{font-size:16px;line-height:24px}.text-lg{font-size:18px;line-height:26px}.text-xl{font-size:20px;line-height:28px}.text-2xl{font-size:24px;line-height:32px}.text-3xl{font-size:30px;line-height:36px}.text-4xl{font-size:36px;line-height:40px}
|
||||||
|
.font-medium{font-weight:500}.font-semibold{font-weight:600}.font-bold{font-weight:700}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,monospace}
|
||||||
|
.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||||
|
.text-white{color:#fff}.text-slate-200{color:#e2e8f0}.text-slate-300{color:#cbd5e1}.text-slate-400{color:#94a3b8}.text-slate-500{color:#64748b}
|
||||||
|
.text-teal-400{color:#2dd4bf}.text-cyan-400{color:#22d3ee}.text-sky-400{color:#38bdf8}.text-emerald-400{color:#34d399}.text-amber-400{color:#fbbf24}.text-red-400{color:#f87171}.text-rose-400{color:#fb7185}
|
||||||
|
.bg-slate-950{background-color:#020617}.bg-slate-900{background-color:#0f172a}.bg-slate-800{background-color:#1e293b}.bg-slate-700{background-color:#334155}
|
||||||
|
.bg-teal-500{background-color:#14b8a6}.bg-cyan-500{background-color:#06b6d4}.bg-sky-500{background-color:#0ea5e9}.bg-emerald-500{background-color:#10b981}.bg-amber-500{background-color:#f59e0b}.bg-red-600{background-color:#dc2626}
|
||||||
|
.bg-slate-900\\/80{background-color:rgba(15,23,42,0.8)}.bg-slate-800\\/80{background-color:rgba(30,41,59,0.8)}
|
||||||
|
.shadow-lg{box-shadow:0 10px 24px rgba(0,0,0,0.35)}.opacity-60{opacity:0.6}.opacity-80{opacity:0.8}
|
||||||
|
.cursor-pointer{cursor:pointer}.transition{transition:all 0.15s ease}
|
||||||
|
@keyframes pw-pulse{0%,100%{opacity:1}50%{opacity:.45}}.animate-pulse{animation:pw-pulse 1.8s cubic-bezier(.4,0,.6,1) infinite}
|
||||||
|
@keyframes pw-spin{to{transform:rotate(360deg)}}.animate-spin{animation:pw-spin 1s linear infinite}
|
||||||
|
@media(min-width:640px){.sm\\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.sm\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}
|
||||||
|
@media(min-width:900px){.md\\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}}
|
||||||
|
`.trim()
|
||||||
|
fs.writeFileSync(path.join(outDir, 'tailwind-lite.min.css'), css, 'utf8')
|
||||||
|
return reportSize('tailwind-lite.min.css')
|
||||||
|
}
|
||||||
|
|
||||||
|
function generateUltraLightIcons() {
|
||||||
|
// <2KB gzip pure SVG/CSS icon runtime (EagleICON / OpenTiny-style ultra-light offline icons)
|
||||||
|
const js = `(function(g){
|
||||||
|
var P={
|
||||||
|
cpu:"M9 2v2M15 2v2M9 20v2M15 20v2M2 9h2M2 15h2M20 9h2M20 15h2M6 6h12v12H6zM9 9h6v6H9z",
|
||||||
|
thermometer:"M14 14.76V3.5a2.5 2.5 0 0 0-5 0v11.26a4.5 4.5 0 1 0 5 0z",
|
||||||
|
battery:"M2 7h16v10H2zM22 11v2",
|
||||||
|
wifi:"M5 12.55a11 11 0 0 1 14.08 0M1.42 9a16 16 0 0 1 21.16 0M8.53 16.11a6 6 0 0 1 6.95 0M12 20h.01",
|
||||||
|
bell:"M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9M13.73 21a2 2 0 0 1-3.46 0",
|
||||||
|
alert:"M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0zM12 9v4M12 17h.01",
|
||||||
|
check:"M20 6L9 17l-5-5",
|
||||||
|
x:"M18 6L6 18M6 6l12 12",
|
||||||
|
play:"M5 3l14 9-14 9V3z",
|
||||||
|
pause:"M6 4h4v16H6zM14 4h4v16h-4z",
|
||||||
|
tv:"M2 7h20v13H2zM17 2l-5 5-5-5",
|
||||||
|
server:"M2 2h20v8H2zM2 14h20v8H2zM6 6h.01M6 18h.01",
|
||||||
|
activity:"M22 12h-4l-3 9L9 3l-3 9H2",
|
||||||
|
clock:"M12 2a10 10 0 1 0 0 20 10 10 0 0 0 0-20zM12 6v6l4 2",
|
||||||
|
settings:"M12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6zM19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4",
|
||||||
|
refresh:"M23 4v6h-6M1 20v-6h6M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15",
|
||||||
|
home:"M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",
|
||||||
|
sun:"M12 17a5 5 0 1 0 0-10 5 5 0 0 0 0 10zM12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42",
|
||||||
|
cloud:"M18 10h-1.26A8 8 0 1 0 9 20h9a5 5 0 0 0 0-10z",
|
||||||
|
database:"M12 2C6.5 2 2 3.8 2 6v12c0 2.2 4.5 4 10 4s10-1.8 10-4V6c0-2.2-4.5-4-10-4zM2 12c0 2.2 4.5 4 10 4s10-1.8 10-4",
|
||||||
|
terminal:"M4 17l6-6-6-6M12 19h8",
|
||||||
|
volume:"M11 5L6 9H2v6h4l5 4V5zM19.07 4.93a10 10 0 0 1 0 14.14M15.54 8.46a5 5 0 0 1 0 7.07",
|
||||||
|
zap:"M13 2L3 14h9l-1 8 10-12h-9l1-8z",
|
||||||
|
shield:"M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z",
|
||||||
|
chart:"M18 20V10M12 20V4M6 20v-6"
|
||||||
|
};
|
||||||
|
function svg(n,s,c){var d=P[n]||P.activity;s=s||20;return '<svg width="'+s+'" height="'+s+'" viewBox="0 0 24 24" fill="none" stroke="'+(c||"currentColor")+'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" style="display:inline-block;vertical-align:middle"><path d="'+d+'"/></svg>';}
|
||||||
|
function hydrate(root){(root||document).querySelectorAll("[data-pw-icon]").forEach(function(el){el.innerHTML=svg(el.getAttribute("data-pw-icon"),el.getAttribute("data-size")||20,el.getAttribute("data-color"));});}
|
||||||
|
g.PwIcons={names:Object.keys(P),svg:svg,hydrate:hydrate};
|
||||||
|
})(window);`
|
||||||
|
fs.writeFileSync(path.join(outDir, 'pw-icons.min.js'), js, 'utf8')
|
||||||
|
return reportSize('pw-icons.min.js')
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const manifest = {}
|
||||||
|
|
||||||
|
// 1. Plyr (Player UI, zero-dep)
|
||||||
|
manifest.plyr = {
|
||||||
|
global: 'Plyr',
|
||||||
|
category: 'media-player',
|
||||||
|
js: copyDist('plyr/dist/plyr.min.js', 'plyr.min.js'),
|
||||||
|
css: copyDist('plyr/dist/plyr.css', 'plyr.css'),
|
||||||
|
note: '首选轻量无依赖播放器 UI,配合 hls 播放 m3u8 直播/点播'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. hls.js light build
|
||||||
|
manifest.hls = {
|
||||||
|
global: 'Hls',
|
||||||
|
category: 'streaming',
|
||||||
|
js: copyDist('hls.js/dist/hls.light.min.js', 'hls.light.min.js'),
|
||||||
|
note: 'HLS (m3u8) 离线精简版流媒体引擎'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. ECharts (Tree-Shaken Dashboard Build!)
|
||||||
|
manifest.echarts = {
|
||||||
|
global: 'echarts',
|
||||||
|
category: 'charts',
|
||||||
|
heavy: true,
|
||||||
|
js: await bundleEntry(
|
||||||
|
`
|
||||||
|
import * as echarts from 'echarts/core';
|
||||||
|
import { LineChart, BarChart, PieChart, GaugeChart, RadarChart, ScatterChart } from 'echarts/charts';
|
||||||
|
import {
|
||||||
|
TitleComponent, TooltipComponent, GridComponent, LegendComponent,
|
||||||
|
DatasetComponent, TransformComponent, DataZoomComponent, MarkLineComponent, MarkPointComponent
|
||||||
|
} from 'echarts/components';
|
||||||
|
import { CanvasRenderer } from 'echarts/renderers';
|
||||||
|
echarts.use([
|
||||||
|
LineChart, BarChart, PieChart, GaugeChart, RadarChart, ScatterChart,
|
||||||
|
TitleComponent, TooltipComponent, GridComponent, LegendComponent,
|
||||||
|
DatasetComponent, TransformComponent, DataZoomComponent, MarkLineComponent, MarkPointComponent,
|
||||||
|
CanvasRenderer
|
||||||
|
]);
|
||||||
|
export const init = echarts.init;
|
||||||
|
export const use = echarts.use;
|
||||||
|
export const graphic = echarts.graphic;
|
||||||
|
export const registerTheme = echarts.registerTheme;
|
||||||
|
export const getInstanceByDom = echarts.getInstanceByDom;
|
||||||
|
export const dispose = echarts.dispose;
|
||||||
|
export default echarts;
|
||||||
|
`,
|
||||||
|
'echarts.custom.min.js',
|
||||||
|
'echarts'
|
||||||
|
),
|
||||||
|
note: '按需裁剪版 ECharts(含折线/柱状/饼图/仪表盘/雷达/散点 + CanvasRenderer),仅在需要复杂图表时按需加载'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. Konva.js (2D Interactive Canvas)
|
||||||
|
manifest.konva = {
|
||||||
|
global: 'Konva',
|
||||||
|
category: 'canvas-2d',
|
||||||
|
js: copyDist('konva/konva.min.js', 'konva.min.js'),
|
||||||
|
note: '2D 交互画布引擎,适合矢量对象编排与实时动效看板'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. Three.js (3D WebGL - heavy, use sparingly on low-end GPU)
|
||||||
|
manifest.three = {
|
||||||
|
global: 'THREE',
|
||||||
|
category: 'canvas-3d',
|
||||||
|
heavy: true,
|
||||||
|
js: await bundleEntry(
|
||||||
|
`export * from 'three';`,
|
||||||
|
'three.min.js',
|
||||||
|
'THREE'
|
||||||
|
),
|
||||||
|
note: 'Three.js 3D 渲染库,体积较大,机顶盒/低端 GPU 慎用,仅明确需要 3D 时加载'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 6. Rough.js (Hand-drawn sketch style, <9KB)
|
||||||
|
manifest.rough = {
|
||||||
|
global: 'rough',
|
||||||
|
category: 'sketch',
|
||||||
|
js: await bundleEntry(
|
||||||
|
`import rough from 'roughjs/bundled/rough.esm.js'; export default rough; export const canvas = rough.canvas; export const svg = rough.svg; export const generator = rough.generator;`,
|
||||||
|
'rough.min.js',
|
||||||
|
'rough'
|
||||||
|
),
|
||||||
|
note: '手绘风格 Canvas/SVG 绘制库(超轻量 <9KB)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. Tailwind CSS prebuilt utility subset
|
||||||
|
manifest.tailwind = {
|
||||||
|
category: 'css',
|
||||||
|
css: generateTailwindLiteCss(),
|
||||||
|
note: '离线预编译 Tailwind 实用工具类 CSS(零 JS 运行时开销,Android 11 WebView 兼容)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 8. Day.js (~2KB)
|
||||||
|
manifest.dayjs = {
|
||||||
|
global: 'dayjs',
|
||||||
|
category: 'datetime',
|
||||||
|
js: copyDist('dayjs/dayjs.min.js', 'dayjs.min.js'),
|
||||||
|
note: '超轻量日期时间格式化与计算库(~2KB)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 9. lodash-es tree-shaken subset (~3-5KB)
|
||||||
|
manifest.lodash = {
|
||||||
|
global: '_',
|
||||||
|
category: 'utils',
|
||||||
|
js: await bundleEntry(
|
||||||
|
`
|
||||||
|
export {
|
||||||
|
debounce, throttle, cloneDeep, merge, groupBy, sortBy, orderBy,
|
||||||
|
uniq, uniqBy, chunk, clamp, pick, omit, get, set, sumBy, meanBy, keyBy, round, range
|
||||||
|
} from 'lodash-es';
|
||||||
|
`,
|
||||||
|
'lodash-lite.min.js',
|
||||||
|
'_'
|
||||||
|
),
|
||||||
|
note: '按需 Tree-Shaking 的 lodash-es 常用工具函数集(window._)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 10. Zustand vanilla (~1KB)
|
||||||
|
manifest.zustand = {
|
||||||
|
global: 'Zustand',
|
||||||
|
category: 'state',
|
||||||
|
js: await bundleEntry(
|
||||||
|
`export { createStore } from 'zustand/vanilla';`,
|
||||||
|
'zustand.min.js',
|
||||||
|
'Zustand'
|
||||||
|
),
|
||||||
|
note: '极简跨组件状态共享库(window.Zustand.createStore,~1KB)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 11. Anime.js (~6KB)
|
||||||
|
manifest.anime = {
|
||||||
|
global: 'anime',
|
||||||
|
category: 'animation',
|
||||||
|
js: copyDist('animejs/lib/anime.min.js', 'anime.min.js'),
|
||||||
|
note: '轻量动效库(仅在 CSS 动画不够用时按需引入)'
|
||||||
|
}
|
||||||
|
|
||||||
|
// 12. Ultra-light inline SVG icons (<2KB)
|
||||||
|
manifest.icons = {
|
||||||
|
global: 'PwIcons',
|
||||||
|
category: 'icons',
|
||||||
|
js: generateUltraLightIcons(),
|
||||||
|
note: '超轻量离线 SVG 图标运行时(<2KB,支持 PwIcons.svg("cpu", 20) 或 data-pw-icon 属性)'
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.writeFileSync(path.join(outDir, 'manifest.json'), JSON.stringify(manifest, null, 2), 'utf8')
|
||||||
|
console.log('\n=== Bundled Offline Android Assets Summary ===')
|
||||||
|
for (const [k, v] of Object.entries(manifest)) {
|
||||||
|
const jsInfo = v.js ? `JS ${v.js.raw_kb}KB (gz ${v.js.gzip_kb}KB)` : ''
|
||||||
|
const cssInfo = v.css ? `CSS ${v.css.raw_kb}KB (gz ${v.css.gzip_kb}KB)` : ''
|
||||||
|
console.log(`- ${k.padEnd(10)} [global: ${(v.global || '-').padEnd(8)}] ${[jsInfo, cssInfo].filter(Boolean).join(' + ')}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(err)
|
||||||
|
process.exit(1)
|
||||||
|
})
|
||||||
Generated
+620
@@ -0,0 +1,620 @@
|
|||||||
|
{
|
||||||
|
"name": "pulsewall-vendor-builder",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "pulsewall-vendor-builder",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
"animejs": "^3.2.2",
|
||||||
|
"dayjs": "^1.11.13",
|
||||||
|
"echarts": "^5.6.0",
|
||||||
|
"esbuild": "^0.25.0",
|
||||||
|
"hls.js": "^1.5.20",
|
||||||
|
"konva": "^9.3.18",
|
||||||
|
"lodash-es": "^4.17.21",
|
||||||
|
"plyr": "^3.7.8",
|
||||||
|
"roughjs": "^4.6.6",
|
||||||
|
"three": "^0.170.0",
|
||||||
|
"zustand": "^5.0.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/aix-ppc64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"aix"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-6AAmLG7zwD1Z159jCKPvAxZd4y/VTO0VkprYy+3N2FtJ8+BQWFXU+OxARIwA46c5tdD9SsKGZ/1ocqBS/gAKHg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/android-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-5jbb+2hhDHx5phYR2By8GTWEzn6I9UqR11Kwf22iKbNpYrsmRB18aX/9ivc5cabcUiAT/wM+YIZ6SG9QO6a8kg==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"android"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-N3zl+lxHCifgIlcMUP5016ESkeQjLj/959RxxNYIthIg+CQHInujFuXeWbWMgnTo4cp5XVHqFPmpyu9J65C1Yg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/darwin-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-HQ9ka4Kx21qHXwtlTUVbKJOAnmG1ipXhdWTmNXiPzPfWKpXqASVcWdnf2bnL73wgjNrFXAa3yYvBSd9pzfEIpA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"darwin"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-gA0Bx759+7Jve03K1S0vkOu5Lg/85dou3EseOGUes8flVOGxbhDDh/iZaoek11Y8mtyKPGF3vP8XhnkDEAmzeg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/freebsd-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-TGbO26Yw2xsHzxtbVFGEXBFH0FRAP7gtcPE7P5yP7wGy7cXK2oO7RyOhL5NLiqTlBh47XhmIUXuGciXEqYFfBQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"freebsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-lPDGyC1JPDou8kGcywY0YILzWlhhnRjdof3UlcoqYmS9El818LLfJJc3PXXgZHrHCAKs/Z2SeZtDJr5MrkxtOw==",
|
||||||
|
"cpu": [
|
||||||
|
"arm"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-8bwX7a8FghIgrupcxb4aUmYDLp8pX06rGh5HqDT7bB+8Rdells6mHvrFHHW2JAOPZUbnjUpKTLg6ECyzvas2AQ==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ia32": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-0y9KrdVnbMM2/vG8KfU0byhUN+EFCny9+8g202gYqSSVMonbsCfLjUO+rCci7pM0WBEtz+oK/PIwHkzxkyharA==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-loong64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-h///Lr5a9rib/v1GGqXVGzjL4TMvVTv+s1DPoxQdz7l/AYv6LDSxdIwzxkrPW438oUXiDtwM10o9PmwS/6Z0Ng==",
|
||||||
|
"cpu": [
|
||||||
|
"loong64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-mips64el": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-iyRrM1Pzy9GFMDLsXn1iHUm18nhKnNMWscjmp4+hpafcZjrr2WbT//d20xaGljXDBYHqRcl8HnxbX6uaA/eGVw==",
|
||||||
|
"cpu": [
|
||||||
|
"mips64el"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-ppc64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-9meM/lRXxMi5PSUqEXRCtVjEZBGwB7P/D4yT8UG/mwIdze2aV4Vo6U5gD3+RsoHXKkHCfSxZKzmDssVlRj1QQA==",
|
||||||
|
"cpu": [
|
||||||
|
"ppc64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-riscv64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-Zr7KR4hgKUpWAwb1f3o5ygT04MzqVrGEGXGLnj15YQDJErYu/BGg+wmFlIDOdJp0PmB0lLvxFIOXZgFRrdjR0w==",
|
||||||
|
"cpu": [
|
||||||
|
"riscv64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-s390x": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-MsKncOcgTNvdtiISc/jZs/Zf8d0cl/t3gYWX8J9ubBnVOwlk65UIEEvgBORTiljloIWnBzLs4qhzPkJcitIzIg==",
|
||||||
|
"cpu": [
|
||||||
|
"s390x"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/linux-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-uqZMTLr/zR/ed4jIGnwSLkaHmPjOjJvnm6TVVitAa08SLS9Z0VM8wIRx7gWbJB5/J54YuIMInDquWyYvQLZkgw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"linux"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-xXwcTq4GhRM7J9A8Gv5boanHhRa/Q9KLVmcyXHCTaM4wKfIpWkdXiMog/KsnxzJ0A1+nD+zoecuzqPmCRyBGjg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/netbsd-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-Ld5pTlzPy3YwGec4OuHh1aCVCRvOXdH8DgRjfDy/oumVovmuSzWfnSJg+VtakB9Cm0gxNO9BzWkj6mtO1FMXkQ==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"netbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-fF96T6KsBo/pkQI950FARU9apGNTSlZGsv1jZBAlcLL1MLjLNIWPBkj5NlSz8aAzYKg+eNqknrUJ24QBybeR5A==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openbsd-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-MZyXUkZHjQxUvzK7rN8DJ3SRmrVrke8ZyRusHlP+kuwqTcfWLyqMOE3sScPPyeIXN/mDJIfGXvcMqCgYKekoQw==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openbsd"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/openharmony-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-rm0YWsqUSRrjncSXGA7Zv78Nbnw4XL6/dzr20cyrQf7ZmRcsovpcRBdhD43Nuk3y7XIoW2OxMVvwuRvk9XdASg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"openharmony"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/sunos-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-3wGSCDyuTHQUzt0nV7bocDy72r2lI33QL3gkDNGkod22EsYl04sMf0qLb8luNKTOmgF/eDEDP5BFNwoBKH441w==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"sunos"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-arm64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-rMmLrur64A7+DKlnSuwqUdRKyd3UE7oPJZmnljqEptesKM8wx9J8gx5u0+9Pq0fQQW8vqeKebwNXdfOyP+8Bsg==",
|
||||||
|
"cpu": [
|
||||||
|
"arm64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-ia32": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-HkqnmmBoCbCwxUKKNPBixiWDGCpQGVsrQfJoVGYLPT41XWF8lHuE5N6WhVia2n4o5QK5M4tYr21827fNhi4byQ==",
|
||||||
|
"cpu": [
|
||||||
|
"ia32"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@esbuild/win32-x64": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA==",
|
||||||
|
"cpu": [
|
||||||
|
"x64"
|
||||||
|
],
|
||||||
|
"optional": true,
|
||||||
|
"os": [
|
||||||
|
"win32"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/animejs": {
|
||||||
|
"version": "3.2.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/animejs/-/animejs-3.2.2.tgz",
|
||||||
|
"integrity": "sha512-Ao95qWLpDPXXM+WrmwcKbl6uNlC5tjnowlaRYtuVDHHoygjtIPfDUoK9NthrlZsQSKjZXlmji2TrBUAVbiH0LQ=="
|
||||||
|
},
|
||||||
|
"node_modules/custom-event-polyfill": {
|
||||||
|
"version": "1.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/custom-event-polyfill/-/custom-event-polyfill-1.0.7.tgz",
|
||||||
|
"integrity": "sha512-TDDkd5DkaZxZFM8p+1I3yAlvM3rSr1wbrOliG4yJiwinMZN8z/iGL7BTlDkrJcYTmgUSb4ywVCc3ZaUtOtC76w=="
|
||||||
|
},
|
||||||
|
"node_modules/dayjs": {
|
||||||
|
"version": "1.11.23",
|
||||||
|
"resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.23.tgz",
|
||||||
|
"integrity": "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="
|
||||||
|
},
|
||||||
|
"node_modules/echarts": {
|
||||||
|
"version": "5.6.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/echarts/-/echarts-5.6.0.tgz",
|
||||||
|
"integrity": "sha512-oTbVTsXfKuEhxftHqL5xprgLoc0k7uScAwtryCgWF6hPYFLRwOUHiFmHGCBKP5NPFNkDVopOieyUqYGH8Fa3kA==",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.3.0",
|
||||||
|
"zrender": "5.6.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/esbuild": {
|
||||||
|
"version": "0.25.12",
|
||||||
|
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.12.tgz",
|
||||||
|
"integrity": "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"bin": {
|
||||||
|
"esbuild": "bin/esbuild"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@esbuild/aix-ppc64": "0.25.12",
|
||||||
|
"@esbuild/android-arm": "0.25.12",
|
||||||
|
"@esbuild/android-arm64": "0.25.12",
|
||||||
|
"@esbuild/android-x64": "0.25.12",
|
||||||
|
"@esbuild/darwin-arm64": "0.25.12",
|
||||||
|
"@esbuild/darwin-x64": "0.25.12",
|
||||||
|
"@esbuild/freebsd-arm64": "0.25.12",
|
||||||
|
"@esbuild/freebsd-x64": "0.25.12",
|
||||||
|
"@esbuild/linux-arm": "0.25.12",
|
||||||
|
"@esbuild/linux-arm64": "0.25.12",
|
||||||
|
"@esbuild/linux-ia32": "0.25.12",
|
||||||
|
"@esbuild/linux-loong64": "0.25.12",
|
||||||
|
"@esbuild/linux-mips64el": "0.25.12",
|
||||||
|
"@esbuild/linux-ppc64": "0.25.12",
|
||||||
|
"@esbuild/linux-riscv64": "0.25.12",
|
||||||
|
"@esbuild/linux-s390x": "0.25.12",
|
||||||
|
"@esbuild/linux-x64": "0.25.12",
|
||||||
|
"@esbuild/netbsd-arm64": "0.25.12",
|
||||||
|
"@esbuild/netbsd-x64": "0.25.12",
|
||||||
|
"@esbuild/openbsd-arm64": "0.25.12",
|
||||||
|
"@esbuild/openbsd-x64": "0.25.12",
|
||||||
|
"@esbuild/openharmony-arm64": "0.25.12",
|
||||||
|
"@esbuild/sunos-x64": "0.25.12",
|
||||||
|
"@esbuild/win32-arm64": "0.25.12",
|
||||||
|
"@esbuild/win32-ia32": "0.25.12",
|
||||||
|
"@esbuild/win32-x64": "0.25.12"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/hachure-fill": {
|
||||||
|
"version": "0.5.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/hachure-fill/-/hachure-fill-0.5.2.tgz",
|
||||||
|
"integrity": "sha512-3GKBOn+m2LX9iq+JC1064cSFprJY4jL1jCXTcpnfER5HYE2l/4EfWSGzkPa/ZDBmYI0ZOEj5VHV/eKnPGkHuOg=="
|
||||||
|
},
|
||||||
|
"node_modules/hls.js": {
|
||||||
|
"version": "1.7.4",
|
||||||
|
"resolved": "https://registry.npmjs.org/hls.js/-/hls.js-1.7.4.tgz",
|
||||||
|
"integrity": "sha512-3GlxGdPvT2YHvQYOt+yOzT/DEior/qJVNIylHA77kgeoBTdQQqi70GwefNEUmHQeNGyjC8U62+bruqW/Tpm+tg=="
|
||||||
|
},
|
||||||
|
"node_modules/konva": {
|
||||||
|
"version": "9.3.22",
|
||||||
|
"resolved": "https://registry.npmjs.org/konva/-/konva-9.3.22.tgz",
|
||||||
|
"integrity": "sha512-yQI5d1bmELlD/fowuyfOp9ff+oamg26WOCkyqUyc+nczD/lhRa3EvD2MZOoc4c1293TAubW9n34fSQLgSeEgSw==",
|
||||||
|
"funding": [
|
||||||
|
{
|
||||||
|
"type": "patreon",
|
||||||
|
"url": "https://www.patreon.com/lavrton"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/konva"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"type": "github",
|
||||||
|
"url": "https://github.com/sponsors/lavrton"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"node_modules/loadjs": {
|
||||||
|
"version": "4.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/loadjs/-/loadjs-4.3.0.tgz",
|
||||||
|
"integrity": "sha512-vNX4ZZLJBeDEOBvdr2v/F+0aN5oMuPu7JTqrMwp+DtgK+AryOlpy6Xtm2/HpNr+azEa828oQjOtWsB6iDtSfSQ=="
|
||||||
|
},
|
||||||
|
"node_modules/lodash-es": {
|
||||||
|
"version": "4.18.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/lodash-es/-/lodash-es-4.18.1.tgz",
|
||||||
|
"integrity": "sha512-J8xewKD/Gk22OZbhpOVSwcs60zhd95ESDwezOFuA3/099925PdHJ7OFHNTGtajL3AlZkykD32HykiMo+BIBI8A=="
|
||||||
|
},
|
||||||
|
"node_modules/path-data-parser": {
|
||||||
|
"version": "0.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/path-data-parser/-/path-data-parser-0.1.0.tgz",
|
||||||
|
"integrity": "sha512-NOnmBpt5Y2RWbuv0LMzsayp3lVylAHLPUTut412ZA3l+C4uw4ZVkQbjShYCQ8TCpUMdPapr4YjUqLYD6v68j+w=="
|
||||||
|
},
|
||||||
|
"node_modules/plyr": {
|
||||||
|
"version": "3.8.5",
|
||||||
|
"resolved": "https://registry.npmjs.org/plyr/-/plyr-3.8.5.tgz",
|
||||||
|
"integrity": "sha512-SqGU1s76fq4lI8ABYhi1uxwrcLGYqmyiMazFAUIOQKKwt6S7FfflEMljLaM3SV8HUUb1KdZ04FY/SNFRpPZHUw==",
|
||||||
|
"deprecated": "Plyr is deprecated and receives security updates only. Use Video.js 10 for new projects. Migration guide: https://videojs.org/docs/framework/html/guides/migrate-from-plyr",
|
||||||
|
"hasInstallScript": true,
|
||||||
|
"dependencies": {
|
||||||
|
"custom-event-polyfill": "^1.0.7",
|
||||||
|
"loadjs": "^4.3.0",
|
||||||
|
"rangetouch": "^2.0.1",
|
||||||
|
"url-polyfill": "^1.1.14"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": "^22.18.0 || >=24.11.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/points-on-curve": {
|
||||||
|
"version": "0.2.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/points-on-curve/-/points-on-curve-0.2.0.tgz",
|
||||||
|
"integrity": "sha512-0mYKnYYe9ZcqMCWhUjItv/oHjvgEsfKvnUTg8sAtnHr3GVy7rGkXCb6d5cSyqrWqL4k81b9CPg3urd+T7aop3A=="
|
||||||
|
},
|
||||||
|
"node_modules/points-on-path": {
|
||||||
|
"version": "0.2.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/points-on-path/-/points-on-path-0.2.1.tgz",
|
||||||
|
"integrity": "sha512-25ClnWWuw7JbWZcgqY/gJ4FQWadKxGWk+3kR/7kD0tCaDtPPMj7oHu2ToLaVhfpnHrZzYby2w6tUA0eOIuUg8g==",
|
||||||
|
"dependencies": {
|
||||||
|
"path-data-parser": "0.1.0",
|
||||||
|
"points-on-curve": "0.2.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/rangetouch": {
|
||||||
|
"version": "2.0.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/rangetouch/-/rangetouch-2.0.1.tgz",
|
||||||
|
"integrity": "sha512-sln+pNSc8NGaHoLzwNBssFSf/rSYkqeBXzX1AtJlkJiUaVSJSbRAWJk+4omsXkN+EJalzkZhWQ3th1m0FpR5xA=="
|
||||||
|
},
|
||||||
|
"node_modules/roughjs": {
|
||||||
|
"version": "4.6.6",
|
||||||
|
"resolved": "https://registry.npmjs.org/roughjs/-/roughjs-4.6.6.tgz",
|
||||||
|
"integrity": "sha512-ZUz/69+SYpFN/g/lUlo2FXcIjRkSu3nDarreVdGGndHEBJ6cXPdKguS8JGxwj5HA5xIbVKSmLgr5b3AWxtRfvQ==",
|
||||||
|
"dependencies": {
|
||||||
|
"hachure-fill": "^0.5.2",
|
||||||
|
"path-data-parser": "^0.1.0",
|
||||||
|
"points-on-curve": "^0.2.0",
|
||||||
|
"points-on-path": "^0.2.1"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/three": {
|
||||||
|
"version": "0.170.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/three/-/three-0.170.0.tgz",
|
||||||
|
"integrity": "sha512-FQK+LEpYc0fBD+J8g6oSEyyNzjp+Q7Ks1C568WWaoMRLW+TkNNWmenWeGgJjV105Gd+p/2ql1ZcjYvNiPZBhuQ=="
|
||||||
|
},
|
||||||
|
"node_modules/tslib": {
|
||||||
|
"version": "2.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.3.0.tgz",
|
||||||
|
"integrity": "sha512-N82ooyxVNm6h1riLCoyS9e3fuJ3AMG2zIZs2Gd1ATcSFjSA23Q0fzjjZeh0jbJvWVDZ0cJT8yaNNaaXHzueNjg=="
|
||||||
|
},
|
||||||
|
"node_modules/url-polyfill": {
|
||||||
|
"version": "1.1.14",
|
||||||
|
"resolved": "https://registry.npmjs.org/url-polyfill/-/url-polyfill-1.1.14.tgz",
|
||||||
|
"integrity": "sha512-p4f3TTAG6ADVF3mwbXw7hGw+QJyw5CnNGvYh5fCuQQZIiuKUswqcznyV3pGDP9j0TSmC4UvRKm8kl1QsX1diiQ=="
|
||||||
|
},
|
||||||
|
"node_modules/zrender": {
|
||||||
|
"version": "5.6.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/zrender/-/zrender-5.6.1.tgz",
|
||||||
|
"integrity": "sha512-OFXkDJKcrlx5su2XbzJvj/34Q3m6PvyCZkVPHGYpcCJ52ek4U/ymZyfuV1nKE23AyBJ51E/6Yr0mhZ7xGTO4ag==",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.3.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/zustand": {
|
||||||
|
"version": "5.1.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/zustand/-/zustand-5.1.0.tgz",
|
||||||
|
"integrity": "sha512-ciJZlP48M1PTQbVQq81CGVFxHTLpZNrFjKqwjtCU34AWuXTZT/jrF3p9+fI84Cf1eSCMLapxqBy/SNTfwOBuqA==",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12.20.0"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@types/react": ">=18.0.0",
|
||||||
|
"immer": ">=9.0.6",
|
||||||
|
"react": ">=18.0.0",
|
||||||
|
"use-sync-external-store": ">=1.2.0"
|
||||||
|
},
|
||||||
|
"peerDependenciesMeta": {
|
||||||
|
"@types/react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"immer": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"react": {
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
|
"use-sync-external-store": {
|
||||||
|
"optional": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
{
|
||||||
|
"name": "pulsewall-vendor-builder",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"dependencies": {
|
||||||
|
"animejs": "^3.2.2",
|
||||||
|
"dayjs": "^1.11.13",
|
||||||
|
"echarts": "^5.6.0",
|
||||||
|
"esbuild": "^0.25.0",
|
||||||
|
"hls.js": "^1.5.20",
|
||||||
|
"konva": "^9.3.18",
|
||||||
|
"lodash-es": "^4.17.21",
|
||||||
|
"plyr": "^3.7.8",
|
||||||
|
"roughjs": "^4.6.6",
|
||||||
|
"three": "^0.170.0",
|
||||||
|
"zustand": "^5.0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
"""PulseWall Hub package."""
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,330 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import struct
|
||||||
|
from typing import Iterable
|
||||||
|
|
||||||
|
|
||||||
|
def _mp4_box(box_type: bytes, payload: bytes) -> bytes:
|
||||||
|
return struct.pack(">I", 8 + len(payload)) + box_type + payload
|
||||||
|
|
||||||
|
|
||||||
|
def _mp4_full_box(box_type: bytes, version: int, flags: int, payload: bytes) -> bytes:
|
||||||
|
vf = ((version & 0xFF) << 24) | (flags & 0xFFFFFF)
|
||||||
|
return _mp4_box(box_type, struct.pack(">I", vf) + payload)
|
||||||
|
|
||||||
|
|
||||||
|
_IDENTITY_MATRIX = struct.pack(
|
||||||
|
">9I",
|
||||||
|
0x00010000, 0, 0,
|
||||||
|
0, 0x00010000, 0,
|
||||||
|
0, 0, 0x40000000,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _find_start_codes(buf: bytes | bytearray) -> list[tuple[int, int]]:
|
||||||
|
"""Returns list of (start_code_offset, nal_payload_offset) for every Annex-B start code in buf."""
|
||||||
|
res: list[tuple[int, int]] = []
|
||||||
|
n = len(buf)
|
||||||
|
i = 0
|
||||||
|
while i < n - 3:
|
||||||
|
pos = buf.find(b"\x00\x00\x01", i)
|
||||||
|
if pos < 0:
|
||||||
|
break
|
||||||
|
if pos > 0 and buf[pos - 1] == 0:
|
||||||
|
sc_start = pos - 1
|
||||||
|
else:
|
||||||
|
sc_start = pos
|
||||||
|
nal_start = pos + 3
|
||||||
|
if res and sc_start < res[-1][1]:
|
||||||
|
sc_start = pos
|
||||||
|
res.append((sc_start, nal_start))
|
||||||
|
i = nal_start
|
||||||
|
return res
|
||||||
|
|
||||||
|
|
||||||
|
class AnnexBAccessUnitFramer:
|
||||||
|
"""Zero-hold Annex-B H.264 Access Unit framer.
|
||||||
|
|
||||||
|
Unlike FFmpeg's av_parser_parse2 (which permanently traps the newest frame
|
||||||
|
until the NEXT frame's start code arrives), this framer emits each Access Unit
|
||||||
|
immediately on the next frame boundary AND supports `flush_idle()` after a
|
||||||
|
brief read timeout (~45ms) so the final frame of a burst or initial static
|
||||||
|
screen IDR is delivered immediately.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._buf = bytearray()
|
||||||
|
self._cur_nals: list[bytes] = []
|
||||||
|
self._cur_has_vcl = False
|
||||||
|
self._cur_is_idr = False
|
||||||
|
|
||||||
|
def reset(self) -> None:
|
||||||
|
self._buf.clear()
|
||||||
|
self._cur_nals.clear()
|
||||||
|
self._cur_has_vcl = False
|
||||||
|
self._cur_is_idr = False
|
||||||
|
|
||||||
|
def _emit_current(self) -> tuple[list[bytes], bool] | None:
|
||||||
|
if not self._cur_has_vcl or not self._cur_nals:
|
||||||
|
return None
|
||||||
|
out = (list(self._cur_nals), self._cur_is_idr)
|
||||||
|
self._cur_nals.clear()
|
||||||
|
self._cur_has_vcl = False
|
||||||
|
self._cur_is_idr = False
|
||||||
|
return out
|
||||||
|
|
||||||
|
def _ingest_nal(self, nal: bytes, ready: list[tuple[list[bytes], bool]]) -> None:
|
||||||
|
if not nal:
|
||||||
|
return
|
||||||
|
ntype = nal[0] & 0x1F
|
||||||
|
if ntype == 9: # AUD starts a new access unit
|
||||||
|
emitted = self._emit_current()
|
||||||
|
if emitted:
|
||||||
|
ready.append(emitted)
|
||||||
|
return
|
||||||
|
|
||||||
|
# If we already have a VCL slice in the current AU, check if this NAL begins the next AU
|
||||||
|
if self._cur_has_vcl:
|
||||||
|
if ntype in (6, 7, 8):
|
||||||
|
emitted = self._emit_current()
|
||||||
|
if emitted:
|
||||||
|
ready.append(emitted)
|
||||||
|
elif ntype in (1, 5):
|
||||||
|
# first_mb_in_slice == 0 in Exp-Golomb iff MSB of byte 1 is 1
|
||||||
|
is_new_pic = len(nal) > 1 and (nal[1] & 0x80) != 0
|
||||||
|
if is_new_pic:
|
||||||
|
emitted = self._emit_current()
|
||||||
|
if emitted:
|
||||||
|
ready.append(emitted)
|
||||||
|
|
||||||
|
self._cur_nals.append(nal)
|
||||||
|
if ntype == 5:
|
||||||
|
self._cur_has_vcl = True
|
||||||
|
self._cur_is_idr = True
|
||||||
|
elif ntype == 1:
|
||||||
|
self._cur_has_vcl = True
|
||||||
|
|
||||||
|
def feed(self, chunk: bytes) -> list[tuple[list[bytes], bool]]:
|
||||||
|
"""Feeds incoming raw Annex-B bytes and returns all immediately complete Access Units."""
|
||||||
|
if not chunk:
|
||||||
|
return []
|
||||||
|
self._buf.extend(chunk)
|
||||||
|
# Guard against corrupted runaway buffer
|
||||||
|
if len(self._buf) > 4 * 1024 * 1024:
|
||||||
|
self.reset()
|
||||||
|
return []
|
||||||
|
|
||||||
|
codes = _find_start_codes(self._buf)
|
||||||
|
if len(codes) < 2:
|
||||||
|
return []
|
||||||
|
|
||||||
|
ready: list[tuple[list[bytes], bool]] = []
|
||||||
|
# Every NAL between code[k] and code[k+1] is guaranteed complete
|
||||||
|
for k in range(len(codes) - 1):
|
||||||
|
_, nal_start = codes[k]
|
||||||
|
next_sc, _ = codes[k + 1]
|
||||||
|
if next_sc > nal_start:
|
||||||
|
nal = bytes(self._buf[nal_start:next_sc])
|
||||||
|
self._ingest_nal(nal, ready)
|
||||||
|
|
||||||
|
# Keep only from the last start code onward
|
||||||
|
last_sc, _ = codes[-1]
|
||||||
|
del self._buf[:last_sc]
|
||||||
|
return ready
|
||||||
|
|
||||||
|
def flush_idle(self) -> list[tuple[list[bytes], bool]]:
|
||||||
|
"""Flushes the trailing NAL/AU once the input pipe goes idle (e.g. 45ms timeout)."""
|
||||||
|
ready: list[tuple[list[bytes], bool]] = []
|
||||||
|
if self._buf:
|
||||||
|
codes = _find_start_codes(self._buf)
|
||||||
|
if codes:
|
||||||
|
_, nal_start = codes[-1]
|
||||||
|
# Only flush if we have a real VCL NAL in progress or already buffered
|
||||||
|
if nal_start < len(self._buf):
|
||||||
|
trailing = bytes(self._buf[nal_start:])
|
||||||
|
ntype = trailing[0] & 0x1F
|
||||||
|
# Don't flush if trailing is only SPS/PPS without VCL yet
|
||||||
|
if ntype in (1, 5) or self._cur_has_vcl:
|
||||||
|
self._buf.clear()
|
||||||
|
self._ingest_nal(trailing, ready)
|
||||||
|
emitted = self._emit_current()
|
||||||
|
if emitted:
|
||||||
|
ready.append(emitted)
|
||||||
|
return ready
|
||||||
|
|
||||||
|
|
||||||
|
class ZeroLatencyFmp4Muxer:
|
||||||
|
"""Pure-Python ISO BMFF fMP4 muxer for H.264 with ZERO frame buffering.
|
||||||
|
|
||||||
|
Emits `ftyp+moov` init segment once SPS+PPS are observed, and emits a standalone
|
||||||
|
`moof+mdat` fragment for every single Access Unit in <0.1ms with monotonic
|
||||||
|
sequence_number and decode_time across seamless source restarts.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def __init__(self, timescale: int = 90000, frame_duration: int = 3600) -> None:
|
||||||
|
self.timescale = timescale
|
||||||
|
self.frame_duration = frame_duration
|
||||||
|
self.sps: bytes | None = None
|
||||||
|
self.pps: bytes | None = None
|
||||||
|
self.width: int = 960
|
||||||
|
self.height: int = 540
|
||||||
|
self.mime: str = 'video/mp4; codecs="avc1.42c029"'
|
||||||
|
self.init_segment: bytes | None = None
|
||||||
|
self._seq_num: int = 0
|
||||||
|
self._decode_time: int = 0
|
||||||
|
|
||||||
|
def update_dimensions(self, width: int, height: int) -> None:
|
||||||
|
if width != self.width or height != self.height:
|
||||||
|
self.width = width
|
||||||
|
self.height = height
|
||||||
|
self.init_segment = None
|
||||||
|
|
||||||
|
def _build_init_segment(self, sps: bytes, pps: bytes) -> bytes:
|
||||||
|
w, h = self.width, self.height
|
||||||
|
ts = self.timescale
|
||||||
|
|
||||||
|
ftyp = _mp4_box(b"ftyp", b"isom" + struct.pack(">I", 512) + b"isomiso2avc1mp41")
|
||||||
|
|
||||||
|
mvhd_payload = (
|
||||||
|
struct.pack(">IIII", 0, 0, ts, 0)
|
||||||
|
+ struct.pack(">IH", 0x00010000, 0x0100)
|
||||||
|
+ b"\x00" * 10
|
||||||
|
+ _IDENTITY_MATRIX
|
||||||
|
+ b"\x00" * 24
|
||||||
|
+ struct.pack(">I", 2)
|
||||||
|
)
|
||||||
|
mvhd = _mp4_full_box(b"mvhd", 0, 0, mvhd_payload)
|
||||||
|
|
||||||
|
tkhd_payload = (
|
||||||
|
struct.pack(">IIIII", 0, 0, 1, 0, 0)
|
||||||
|
+ b"\x00" * 8
|
||||||
|
+ struct.pack(">HHHH", 0, 0, 0, 0)
|
||||||
|
+ _IDENTITY_MATRIX
|
||||||
|
+ struct.pack(">II", w << 16, h << 16)
|
||||||
|
)
|
||||||
|
tkhd = _mp4_full_box(b"tkhd", 0, 3, tkhd_payload)
|
||||||
|
|
||||||
|
mdhd = _mp4_full_box(b"mdhd", 0, 0, struct.pack(">IIIIHH", 0, 0, ts, 0, 0x55C4, 0))
|
||||||
|
hdlr = _mp4_full_box(b"hdlr", 0, 0, struct.pack(">I", 0) + b"vide" + b"\x00" * 12 + b"VideoHandler\x00")
|
||||||
|
vmhd = _mp4_full_box(b"vmhd", 0, 1, struct.pack(">HHHH", 0, 0, 0, 0))
|
||||||
|
url_box = _mp4_full_box(b"url ", 0, 1, b"")
|
||||||
|
dref = _mp4_full_box(b"dref", 0, 0, struct.pack(">I", 1) + url_box)
|
||||||
|
dinf = _mp4_box(b"dinf", dref)
|
||||||
|
|
||||||
|
profile = sps[1] if len(sps) > 1 else 0x42
|
||||||
|
compat = sps[2] if len(sps) > 2 else 0xC0
|
||||||
|
level = sps[3] if len(sps) > 3 else 0x29
|
||||||
|
self.mime = f'video/mp4; codecs="avc1.{profile:02x}{compat:02x}{level:02x}"'
|
||||||
|
|
||||||
|
avcc_payload = (
|
||||||
|
bytes([1, profile, compat, level, 0xFF, 0xE1])
|
||||||
|
+ struct.pack(">H", len(sps))
|
||||||
|
+ sps
|
||||||
|
+ bytes([1])
|
||||||
|
+ struct.pack(">H", len(pps))
|
||||||
|
+ pps
|
||||||
|
)
|
||||||
|
avcc = _mp4_box(b"avcC", avcc_payload)
|
||||||
|
|
||||||
|
avc1_payload = (
|
||||||
|
b"\x00" * 6
|
||||||
|
+ struct.pack(">H", 1)
|
||||||
|
+ b"\x00" * 16
|
||||||
|
+ struct.pack(">HH", w, h)
|
||||||
|
+ struct.pack(">II", 0x00480000, 0x00480000)
|
||||||
|
+ struct.pack(">I", 0)
|
||||||
|
+ struct.pack(">H", 1)
|
||||||
|
+ b"\x00" * 32
|
||||||
|
+ struct.pack(">HH", 0x0018, 0xFFFF)
|
||||||
|
+ avcc
|
||||||
|
)
|
||||||
|
avc1 = _mp4_box(b"avc1", avc1_payload)
|
||||||
|
stsd = _mp4_full_box(b"stsd", 0, 0, struct.pack(">I", 1) + avc1)
|
||||||
|
stts = _mp4_full_box(b"stts", 0, 0, struct.pack(">I", 0))
|
||||||
|
stsc = _mp4_full_box(b"stsc", 0, 0, struct.pack(">I", 0))
|
||||||
|
stsz = _mp4_full_box(b"stsz", 0, 0, struct.pack(">II", 0, 0))
|
||||||
|
stco = _mp4_full_box(b"stco", 0, 0, struct.pack(">I", 0))
|
||||||
|
stbl = _mp4_box(b"stbl", stsd + stts + stsc + stsz + stco)
|
||||||
|
minf = _mp4_box(b"minf", vmhd + dinf + stbl)
|
||||||
|
mdia = _mp4_box(b"mdia", mdhd + hdlr + minf)
|
||||||
|
trak = _mp4_box(b"trak", tkhd + mdia)
|
||||||
|
|
||||||
|
trex = _mp4_full_box(
|
||||||
|
b"trex",
|
||||||
|
0,
|
||||||
|
0,
|
||||||
|
struct.pack(">IIIII", 1, 1, self.frame_duration, 0, 0x01010000),
|
||||||
|
)
|
||||||
|
mvex = _mp4_box(b"mvex", trex)
|
||||||
|
moov = _mp4_box(b"moov", mvhd + trak + mvex)
|
||||||
|
return ftyp + moov
|
||||||
|
|
||||||
|
def mux_access_unit(
|
||||||
|
self,
|
||||||
|
nals: Iterable[bytes],
|
||||||
|
is_idr: bool,
|
||||||
|
) -> tuple[bytes | None, bytes | None]:
|
||||||
|
"""Returns (new_init_segment_or_None, media_fragment_or_None).
|
||||||
|
|
||||||
|
`new_init_segment` is returned ONLY when SPS/PPS first appear or change,
|
||||||
|
so seamless restarts at identical resolution never tear down browser MSE!
|
||||||
|
"""
|
||||||
|
nal_list = [n for n in nals if n]
|
||||||
|
if not nal_list:
|
||||||
|
return None, None
|
||||||
|
|
||||||
|
sps_changed = False
|
||||||
|
avcc_parts: list[bytes] = []
|
||||||
|
for nal in nal_list:
|
||||||
|
ntype = nal[0] & 0x1F
|
||||||
|
if ntype == 7:
|
||||||
|
if self.sps != nal:
|
||||||
|
self.sps = nal
|
||||||
|
sps_changed = True
|
||||||
|
elif ntype == 8:
|
||||||
|
if self.pps != nal:
|
||||||
|
self.pps = nal
|
||||||
|
sps_changed = True
|
||||||
|
if ntype != 9:
|
||||||
|
avcc_parts.append(struct.pack(">I", len(nal)) + nal)
|
||||||
|
|
||||||
|
new_init: bytes | None = None
|
||||||
|
if self.sps and self.pps and (self.init_segment is None or sps_changed):
|
||||||
|
self.init_segment = self._build_init_segment(self.sps, self.pps)
|
||||||
|
new_init = self.init_segment
|
||||||
|
|
||||||
|
if self.init_segment is None or not avcc_parts:
|
||||||
|
return new_init, None
|
||||||
|
|
||||||
|
mdat_payload = b"".join(avcc_parts)
|
||||||
|
self._seq_num += 1
|
||||||
|
decode_time = self._decode_time
|
||||||
|
self._decode_time += self.frame_duration
|
||||||
|
|
||||||
|
sample_flags = 0x02000000 if is_idr else 0x01010000
|
||||||
|
mfhd = _mp4_full_box(b"mfhd", 0, 0, struct.pack(">I", self._seq_num))
|
||||||
|
tfhd = _mp4_full_box(b"tfhd", 0, 0x020000, struct.pack(">I", 1))
|
||||||
|
tfdt = _mp4_full_box(b"tfdt", 1, 0, struct.pack(">Q", decode_time))
|
||||||
|
|
||||||
|
def _make_moof(data_offset: int) -> bytes:
|
||||||
|
# flags 0x000701: data-offset | sample-duration | sample-size | sample-flags
|
||||||
|
trun = _mp4_full_box(
|
||||||
|
b"trun",
|
||||||
|
0,
|
||||||
|
0x000701,
|
||||||
|
struct.pack(
|
||||||
|
">IiIII",
|
||||||
|
1,
|
||||||
|
data_offset,
|
||||||
|
self.frame_duration,
|
||||||
|
len(mdat_payload),
|
||||||
|
sample_flags,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
traf = _mp4_box(b"traf", tfhd + tfdt + trun)
|
||||||
|
return _mp4_box(b"moof", mfhd + traf)
|
||||||
|
|
||||||
|
probe_moof = _make_moof(0)
|
||||||
|
moof = _make_moof(len(probe_moof) + 8)
|
||||||
|
mdat = _mp4_box(b"mdat", mdat_payload)
|
||||||
|
return new_init, moof + mdat
|
||||||
@@ -0,0 +1,327 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from typing import Any, Callable
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import HTTPException
|
||||||
|
from mcp.server.mcpserver import MCPServer
|
||||||
|
|
||||||
|
from app.storage.db import PulseWallDB
|
||||||
|
|
||||||
|
|
||||||
|
def _serialize_tool_result(res: Any) -> tuple[str, bool]:
|
||||||
|
is_err = bool(getattr(res, "is_error", False))
|
||||||
|
structured = getattr(res, "structured_content", None)
|
||||||
|
if structured is not None:
|
||||||
|
return json.dumps(structured, ensure_ascii=False), is_err
|
||||||
|
content = getattr(res, "content", None)
|
||||||
|
if isinstance(content, list) and content:
|
||||||
|
parts = []
|
||||||
|
for item in content:
|
||||||
|
txt = getattr(item, "text", None)
|
||||||
|
parts.append(txt if txt is not None else str(item))
|
||||||
|
return "\n".join(parts), is_err
|
||||||
|
return json.dumps(res, ensure_ascii=False, default=str), is_err
|
||||||
|
|
||||||
|
|
||||||
|
class HubMcpChatAgent:
|
||||||
|
"""OpenAI-compatible tool-calling chat agent wired directly to PulseWall's live MCPServer."""
|
||||||
|
|
||||||
|
def __init__(
|
||||||
|
self,
|
||||||
|
db: PulseWallDB,
|
||||||
|
mcp_server: MCPServer,
|
||||||
|
transport: httpx.AsyncBaseTransport | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.mcp_server = mcp_server
|
||||||
|
self._transport = transport
|
||||||
|
|
||||||
|
async def get_openai_tools(self) -> list[dict[str, Any]]:
|
||||||
|
mcp_tools = await self.mcp_server.list_tools()
|
||||||
|
openai_tools: list[dict[str, Any]] = []
|
||||||
|
for t in mcp_tools:
|
||||||
|
schema = getattr(t, "input_schema", None) or {"type": "object", "properties": {}}
|
||||||
|
openai_tools.append(
|
||||||
|
{
|
||||||
|
"type": "function",
|
||||||
|
"function": {
|
||||||
|
"name": t.name,
|
||||||
|
"description": (t.description or "").strip(),
|
||||||
|
"parameters": schema,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
return openai_tools
|
||||||
|
|
||||||
|
async def chat(
|
||||||
|
self,
|
||||||
|
user_message: str,
|
||||||
|
history: list[dict[str, Any]] | None = None,
|
||||||
|
max_steps: int | None = None,
|
||||||
|
on_tool_progress: Callable[[list[dict[str, Any]]], None] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
cfg = self.db.get_config().hub_chat_ai
|
||||||
|
if not cfg.base_url.strip() or not cfg.api_key.strip() or not cfg.model.strip():
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": "请先在上方填写并保存「中心桥专用 AI 配置」(Base URL、API Key、Model)。",
|
||||||
|
"tool_trace": [],
|
||||||
|
}
|
||||||
|
|
||||||
|
effective_max_steps = max(1, min(100, int(max_steps if max_steps is not None else getattr(cfg, "max_tool_steps", 30))))
|
||||||
|
|
||||||
|
tools = await self.get_openai_tools()
|
||||||
|
messages: list[dict[str, Any]] = [{"role": "system", "content": cfg.system_prompt}]
|
||||||
|
for item in history or []:
|
||||||
|
role = item.get("role")
|
||||||
|
if role in ("user", "assistant") and item.get("content") is not None:
|
||||||
|
messages.append({"role": role, "content": str(item["content"])})
|
||||||
|
messages.append({"role": "user", "content": user_message})
|
||||||
|
|
||||||
|
endpoint = cfg.base_url.rstrip("/") + "/chat/completions"
|
||||||
|
headers = {
|
||||||
|
"Authorization": f"Bearer {cfg.api_key}",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
tool_trace: list[dict[str, Any]] = []
|
||||||
|
|
||||||
|
client_kwargs: dict[str, Any] = {"timeout": float(cfg.timeout_sec)}
|
||||||
|
if self._transport is not None:
|
||||||
|
client_kwargs["transport"] = self._transport
|
||||||
|
|
||||||
|
async with httpx.AsyncClient(**client_kwargs) as client:
|
||||||
|
for _step in range(effective_max_steps):
|
||||||
|
req_body: dict[str, Any] = {
|
||||||
|
"model": cfg.model,
|
||||||
|
"messages": messages,
|
||||||
|
"tools": tools,
|
||||||
|
"tool_choice": "auto",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
resp = await client.post(endpoint, headers=headers, json=req_body)
|
||||||
|
except Exception as exc:
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": f"请求中心桥 AI 接口失败: {exc}",
|
||||||
|
"tool_trace": tool_trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
if resp.status_code >= 400:
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": f"AI 接口返回 HTTP {resp.status_code}: {resp.text[:400]}",
|
||||||
|
"tool_trace": tool_trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
try:
|
||||||
|
data = resp.json()
|
||||||
|
choice_msg = data["choices"][0]["message"]
|
||||||
|
except Exception as exc:
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": f"解析 AI 响应失败: {exc} · 原始响应: {resp.text[:300]}",
|
||||||
|
"tool_trace": tool_trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
tool_calls = choice_msg.get("tool_calls") or []
|
||||||
|
assistant_content = choice_msg.get("content") or ""
|
||||||
|
|
||||||
|
if not tool_calls:
|
||||||
|
self.db.add_audit(
|
||||||
|
"hub_ai_chat",
|
||||||
|
"hub",
|
||||||
|
f"AI chat completed ({len(tool_trace)} MCP tool calls)",
|
||||||
|
{"user_message": user_message[:200], "tools_used": [t["name"] for t in tool_trace]},
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"reply": assistant_content,
|
||||||
|
"tool_trace": tool_trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
# Append assistant tool-call turn
|
||||||
|
messages.append(
|
||||||
|
{
|
||||||
|
"role": "assistant",
|
||||||
|
"content": assistant_content,
|
||||||
|
"tool_calls": tool_calls,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
# Execute each requested MCP tool call against live MCPServer
|
||||||
|
for tc in tool_calls:
|
||||||
|
tc_id = tc.get("id") or f"call_{len(tool_trace)}"
|
||||||
|
fn = tc.get("function") or {}
|
||||||
|
fn_name = str(fn.get("name") or "")
|
||||||
|
raw_args = fn.get("arguments") or "{}"
|
||||||
|
try:
|
||||||
|
parsed_args = json.loads(raw_args) if isinstance(raw_args, str) else dict(raw_args)
|
||||||
|
except Exception:
|
||||||
|
parsed_args = {}
|
||||||
|
|
||||||
|
try:
|
||||||
|
mcp_res = await self.mcp_server.call_tool(fn_name, parsed_args)
|
||||||
|
result_text, is_err = _serialize_tool_result(mcp_res)
|
||||||
|
except Exception as exc:
|
||||||
|
result_text = json.dumps({"ok": False, "error": str(exc)}, ensure_ascii=False)
|
||||||
|
is_err = True
|
||||||
|
|
||||||
|
tool_trace.append(
|
||||||
|
{
|
||||||
|
"name": fn_name,
|
||||||
|
"arguments": parsed_args,
|
||||||
|
"result": result_text,
|
||||||
|
"is_error": is_err,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
if on_tool_progress is not None:
|
||||||
|
try:
|
||||||
|
on_tool_progress(list(tool_trace))
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
messages.append(
|
||||||
|
{
|
||||||
|
"role": "tool",
|
||||||
|
"tool_call_id": tc_id,
|
||||||
|
"name": fn_name,
|
||||||
|
"content": result_text,
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"reply": f"已达到单轮最大 MCP 工具调用次数({effective_max_steps} 步),可在「中心桥专用 AI 配置」或「全局设置」中调大上限,或继续追问。",
|
||||||
|
"tool_trace": tool_trace,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
class ChatSessionRunner:
|
||||||
|
"""Runs AI chat turns as detached Hub background tasks so closing the browser never aborts an active run."""
|
||||||
|
|
||||||
|
def __init__(self, db: PulseWallDB, agent: HubMcpChatAgent) -> None:
|
||||||
|
self.db = db
|
||||||
|
self.agent = agent
|
||||||
|
self._tasks: dict[str, asyncio.Task[None]] = {}
|
||||||
|
|
||||||
|
def is_running(self, session_id: str) -> bool:
|
||||||
|
t = self._tasks.get(session_id)
|
||||||
|
return t is not None and not t.done()
|
||||||
|
|
||||||
|
def start_message_run(self, session_id: str, user_text: str) -> dict[str, Any]:
|
||||||
|
sess = self.db.get_chat_session(session_id)
|
||||||
|
if not sess:
|
||||||
|
raise HTTPException(status_code=404, detail="会话不存在")
|
||||||
|
if self.is_running(session_id) or sess.get("status") == "running":
|
||||||
|
raise HTTPException(status_code=409, detail="该会话有 AI 回复正在后台执行中,请等待完成或切换到其他会话。")
|
||||||
|
|
||||||
|
# Build prior conversation context from persisted SQLite messages before appending new turn
|
||||||
|
existing_msgs = self.db.list_chat_messages(session_id)
|
||||||
|
history = [
|
||||||
|
{"role": m["role"], "content": m["content"]}
|
||||||
|
for m in existing_msgs
|
||||||
|
if m["role"] in ("user", "assistant") and m["status"] == "done" and m["content"]
|
||||||
|
]
|
||||||
|
|
||||||
|
# Auto-name untitled session using first user message
|
||||||
|
if sess["title"] in ("新会话", "未命名会话", "") and len(existing_msgs) == 0:
|
||||||
|
auto_title = user_text.strip().replace("\n", " ")[:24]
|
||||||
|
if len(user_text.strip()) > 24:
|
||||||
|
auto_title += "…"
|
||||||
|
self.db.rename_chat_session(session_id, auto_title or "新会话")
|
||||||
|
|
||||||
|
run_id = f"run_{uuid.uuid4().hex[:10]}"
|
||||||
|
user_msg = self.db.add_chat_message(session_id, "user", user_text, status="done", run_id=run_id)
|
||||||
|
assistant_msg = self.db.add_chat_message(session_id, "assistant", "", tool_trace=[], status="running", run_id=run_id)
|
||||||
|
self.db.set_chat_session_status(session_id, "running", active_run_id=run_id)
|
||||||
|
|
||||||
|
task = asyncio.create_task(
|
||||||
|
self._execute_run(
|
||||||
|
session_id=session_id,
|
||||||
|
run_id=run_id,
|
||||||
|
assistant_msg_id=int(assistant_msg["id"]),
|
||||||
|
user_text=user_text,
|
||||||
|
history=history,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
self._tasks[session_id] = task
|
||||||
|
task.add_done_callback(lambda _t, sid=session_id: self._cleanup_task(sid, _t))
|
||||||
|
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"run_id": run_id,
|
||||||
|
"session": self.db.get_chat_session(session_id),
|
||||||
|
"user_message": user_msg,
|
||||||
|
"assistant_message": assistant_msg,
|
||||||
|
}
|
||||||
|
|
||||||
|
def _cleanup_task(self, session_id: str, task: asyncio.Task[None]) -> None:
|
||||||
|
if self._tasks.get(session_id) is task:
|
||||||
|
del self._tasks[session_id]
|
||||||
|
|
||||||
|
async def _execute_run(
|
||||||
|
self,
|
||||||
|
session_id: str,
|
||||||
|
run_id: str,
|
||||||
|
assistant_msg_id: int,
|
||||||
|
user_text: str,
|
||||||
|
history: list[dict[str, Any]],
|
||||||
|
) -> None:
|
||||||
|
def on_progress(trace: list[dict[str, Any]]) -> None:
|
||||||
|
self.db.update_chat_message(assistant_msg_id, tool_trace=trace, status="running")
|
||||||
|
|
||||||
|
try:
|
||||||
|
res = await self.agent.chat(
|
||||||
|
user_message=user_text,
|
||||||
|
history=history,
|
||||||
|
on_tool_progress=on_progress,
|
||||||
|
)
|
||||||
|
if res.get("ok"):
|
||||||
|
self.db.update_chat_message(
|
||||||
|
assistant_msg_id,
|
||||||
|
role="assistant",
|
||||||
|
content=str(res.get("reply") or "操作已完成。"),
|
||||||
|
tool_trace=res.get("tool_trace") or [],
|
||||||
|
status="done",
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
self.db.update_chat_message(
|
||||||
|
assistant_msg_id,
|
||||||
|
role="error",
|
||||||
|
content=str(res.get("error") or "调用失败"),
|
||||||
|
tool_trace=res.get("tool_trace") or [],
|
||||||
|
status="error",
|
||||||
|
)
|
||||||
|
except asyncio.CancelledError:
|
||||||
|
self.db.update_chat_message(
|
||||||
|
assistant_msg_id,
|
||||||
|
role="error",
|
||||||
|
content="后台任务已取消。",
|
||||||
|
status="error",
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
except Exception as exc:
|
||||||
|
self.db.update_chat_message(
|
||||||
|
assistant_msg_id,
|
||||||
|
role="error",
|
||||||
|
content=f"后台执行异常: {exc}",
|
||||||
|
status="error",
|
||||||
|
)
|
||||||
|
finally:
|
||||||
|
self.db.set_chat_session_status(session_id, "idle", active_run_id="")
|
||||||
|
|
||||||
|
def cancel_session_run(self, session_id: str) -> bool:
|
||||||
|
t = self._tasks.get(session_id)
|
||||||
|
if t and not t.done():
|
||||||
|
t.cancel()
|
||||||
|
return True
|
||||||
|
return False
|
||||||
|
|
||||||
|
def cancel_all(self) -> None:
|
||||||
|
for t in list(self._tasks.values()):
|
||||||
|
if not t.done():
|
||||||
|
t.cancel()
|
||||||
|
self._tasks.clear()
|
||||||
@@ -0,0 +1,649 @@
|
|||||||
|
ADMIN_HTML = r"""<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>PulseWall Hub · 控制中心</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #090e1c; --card: #121a2e; --card-2: #17223b; --border: #243250;
|
||||||
|
--text: #e7eef9; --muted: #93a4c3; --accent: #38bdf8;
|
||||||
|
--ok: #22c55e; --warn: #f59e0b; --danger: #ef4444;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; background: var(--bg); color: var(--text); }
|
||||||
|
header { padding: 14px 24px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; background: #0d1426; position: sticky; top: 0; z-index: 20; }
|
||||||
|
header h1 { margin: 0; font-size: 19px; display: flex; align-items: center; gap: 8px; }
|
||||||
|
.tabs { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.tab-btn { background: transparent; color: var(--muted); border: 1px solid var(--border); border-radius: 10px; padding: 8px 16px; font-weight: 600; cursor: pointer; font-size: 13px; margin: 0; transition: all .15s; }
|
||||||
|
.tab-btn:hover { color: var(--text); border-color: var(--accent); }
|
||||||
|
.tab-btn.active { background: var(--accent); color: #041220; border-color: var(--accent); }
|
||||||
|
.tab-panel { display: none; max-width: 1360px; margin: 18px auto 40px; padding: 0 20px; }
|
||||||
|
.tab-panel.active { display: block; }
|
||||||
|
|
||||||
|
.badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; background: #1e293b; color: var(--accent); margin-right: 4px; font-weight: 600; }
|
||||||
|
.badge.on { background: rgba(34,197,94,0.18); color: var(--ok); }
|
||||||
|
.badge.off { background: rgba(239,68,68,0.18); color: var(--danger); }
|
||||||
|
.badge.custom { background: rgba(245,158,11,0.2); color: var(--warn); }
|
||||||
|
|
||||||
|
.grid-devices { display: grid; grid-template-columns: 340px 1fr; gap: 18px; align-items: start; }
|
||||||
|
.grid-2 { display: grid; grid-template-columns: 1.15fr 1fr; gap: 18px; align-items: start; }
|
||||||
|
@media (max-width: 960px) { .grid-devices, .grid-2 { grid-template-columns: 1fr; } }
|
||||||
|
|
||||||
|
.card { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 16px; margin-bottom: 16px; }
|
||||||
|
.card h2 { margin: 0 0 12px; font-size: 15px; color: var(--accent); display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||||
|
label { display: block; font-size: 12px; color: var(--muted); margin: 8px 0 4px; }
|
||||||
|
input, select, textarea { width: 100%; background: #0b1222; color: var(--text); border: 1px solid var(--border); border-radius: 8px; padding: 8px 10px; font-size: 13px; font-family: inherit; }
|
||||||
|
textarea { resize: vertical; }
|
||||||
|
button { background: var(--accent); color: #04101d; border: none; border-radius: 8px; padding: 8px 14px; font-weight: 600; cursor: pointer; font-size: 13px; margin-top: 8px; }
|
||||||
|
button:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||||
|
button.danger { background: var(--danger); color: #fff; }
|
||||||
|
button.secondary { background: #243352; color: var(--text); }
|
||||||
|
button.small { padding: 5px 10px; font-size: 12px; margin-top: 0; }
|
||||||
|
.row { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; }
|
||||||
|
.mono { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 12px; color: var(--muted); }
|
||||||
|
|
||||||
|
.dev-card { border: 1px solid var(--border); border-radius: 12px; padding: 12px; margin-bottom: 10px; background: #0e1628; cursor: pointer; transition: border-color .15s, background .15s; }
|
||||||
|
.dev-card:hover { border-color: rgba(56,189,248,0.6); }
|
||||||
|
.dev-card.selected { border-color: var(--accent); background: #14223d; box-shadow: 0 0 0 1px rgba(56,189,248,0.35); }
|
||||||
|
|
||||||
|
.kv-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 10px; margin-bottom: 12px; }
|
||||||
|
.kv-box { background: #0c1425; border: 1px solid var(--border); border-radius: 10px; padding: 10px 12px; }
|
||||||
|
.kv-box .k { font-size: 11px; color: var(--muted); }
|
||||||
|
.kv-box .v { font-size: 14px; font-weight: 700; margin-top: 3px; word-break: break-all; }
|
||||||
|
|
||||||
|
.log-list { max-height: 320px; overflow-y: auto; font-size: 12px; }
|
||||||
|
.log-row { padding: 7px 0; border-bottom: 1px solid rgba(255,255,255,0.06); }
|
||||||
|
|
||||||
|
/* AI Chat Console */
|
||||||
|
.chat-wrap { display: flex; flex-direction: column; height: 540px; }
|
||||||
|
.chat-messages { flex: 1; overflow-y: auto; padding: 12px; background: #0b1222; border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; gap: 12px; }
|
||||||
|
.msg { max-width: 88%; padding: 10px 14px; border-radius: 12px; font-size: 13.5px; line-height: 1.55; white-space: pre-wrap; word-break: break-word; }
|
||||||
|
.msg.user { align-self: flex-end; background: #0369a1; color: #f8fafc; border-bottom-right-radius: 4px; }
|
||||||
|
.msg.assistant { align-self: flex-start; background: #162138; border: 1px solid var(--border); color: var(--text); border-bottom-left-radius: 4px; }
|
||||||
|
.msg.error { align-self: flex-start; background: rgba(239,68,68,0.16); border: 1px solid var(--danger); color: #fecaca; }
|
||||||
|
.tool-trace { margin-top: 8px; border-top: 1px dashed rgba(148,163,184,0.25); padding-top: 8px; }
|
||||||
|
.tool-trace details { background: #0b1222; border: 1px solid var(--border); border-radius: 8px; padding: 6px 10px; margin-bottom: 6px; font-size: 12px; }
|
||||||
|
.tool-trace summary { cursor: pointer; color: var(--accent); font-weight: 600; }
|
||||||
|
.tool-trace pre { margin: 6px 0 0; white-space: pre-wrap; word-break: break-all; color: #cbd5e1; max-height: 180px; overflow-y: auto; font-size: 11.5px; }
|
||||||
|
.chip { background: #1a2742; color: #bae6fd; border: 1px solid #2b3f66; border-radius: 999px; padding: 5px 12px; font-size: 12px; cursor: pointer; margin: 0; }
|
||||||
|
.chip:hover { border-color: var(--accent); background: #213459; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<h1>⚡ PulseWall Hub <span class="badge">MCP: /mcp/</span></h1>
|
||||||
|
<nav class="tabs">
|
||||||
|
<button class="tab-btn active" data-tab="devices" onclick="switchTab('devices')">📱 设备列表</button>
|
||||||
|
<button class="tab-btn" data-tab="chat" onclick="switchTab('chat')">🤖 AI 会话测试</button>
|
||||||
|
<button class="tab-btn" data-tab="global" onclick="switchTab('global')">⚙️ 全局配置 & 日志</button>
|
||||||
|
</nav>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- ==================== TAB 1: 设备列表 ==================== -->
|
||||||
|
<section id="tab-devices" class="tab-panel active">
|
||||||
|
<div class="grid-devices">
|
||||||
|
<div class="card" style="margin-bottom:0;">
|
||||||
|
<h2><span>📱 已接入设备</span> <button class="secondary small" onclick="refreshLivePanels()">刷新</button></h2>
|
||||||
|
<div id="device_list_sidebar" class="mono">加载中...</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div id="device_detail_pane">
|
||||||
|
<div class="card">
|
||||||
|
<div class="mono">请在左侧选择一台设备查看详情、独立 AI 配置与联调操作。</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ==================== TAB 2: AI 会话测试 ==================== -->
|
||||||
|
<section id="tab-chat" class="tab-panel">
|
||||||
|
<div class="card">
|
||||||
|
<h2>
|
||||||
|
<span>🧠 中心桥专用 AI 配置(OpenAI 兼容 · 专用于下方 MCP 对话测试)</span>
|
||||||
|
<span id="chat_cfg_dirty" class="badge off" style="display:none;">有未保存修改</span>
|
||||||
|
</h2>
|
||||||
|
<div class="row">
|
||||||
|
<div style="flex:1.4;min-width:220px;"><label>OpenAI Base URL</label><input id="chat_ai_base_url" placeholder="https://api.openai.com/v1" /></div>
|
||||||
|
<div style="flex:1.2;min-width:200px;"><label>API Key</label><input id="chat_ai_api_key" type="password" placeholder="sk-..." /></div>
|
||||||
|
<div style="flex:1;min-width:160px;"><label>Model(需支持 Tool Calling)</label><input id="chat_ai_model" placeholder="gpt-4o-mini / deepseek-chat / ..." /></div>
|
||||||
|
</div>
|
||||||
|
<label>System Prompt(控制中心桥 AI 调用 MCP 的行为规范)</label>
|
||||||
|
<textarea id="chat_ai_system" rows="2"></textarea>
|
||||||
|
<div class="row">
|
||||||
|
<button onclick="saveHubChatConfig()">💾 保存中心桥专用 AI 配置</button>
|
||||||
|
<button class="secondary" onclick="loadGlobalAndChatConfig(true)">重新读取已存配置</button>
|
||||||
|
<span id="chat_cfg_msg" class="mono"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>
|
||||||
|
<span>💬 AI 对话测试台(自动挂载全部 PulseWall MCP 工具)</span>
|
||||||
|
<button class="secondary small" onclick="clearChat()">清空会话</button>
|
||||||
|
</h2>
|
||||||
|
<div class="row" style="margin-bottom:10px;">
|
||||||
|
<button class="chip" onclick="quickAsk('请列出当前所有在线设备,并详细汇报每台设备的型号、分辨率、WebView版本和实时温度/电量状态。')">📋 巡检全部设备状态</button>
|
||||||
|
<button class="chip" onclick="quickAsk('请先查看当前在线设备的分辨率和形态,然后为它设计并渲染一个酷炫的暗黑大屏监控仪表盘页面,展示设备状态和一个可以回调中心桥的测试按钮。')">🖥️ 让 AI 自适应画页面</button>
|
||||||
|
<button class="chip" onclick="quickAsk('模拟生产数据库主节点宕机(连接超时 30s),请给当前在线设备触发一条全屏红色紧急警报,附带「确认收到」「自动切换备库」「静音30分钟」三个预设按钮。')">🚨 演练 AI 全屏红屏告警</button>
|
||||||
|
<button class="chip" onclick="quickAsk('查询一下待处理的反向事件,看看用户刚才在设备上点击了什么按钮或有没有端侧修复提问。')">📬 查询用户交互回复</button>
|
||||||
|
<button class="chip" onclick="quickAsk('请把当前在线设备恢复到内置默认首页。')">🏠 恢复默认首页</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chat-wrap">
|
||||||
|
<div id="chat_messages" class="chat-messages">
|
||||||
|
<div class="msg assistant">你好!我是中心桥内置的 PulseWall MCP 调试助手。你可以直接用自然语言让我查询设备信息、画适配分辨率的动态页面、触发分层警报,或检测双向交互回执。</div>
|
||||||
|
</div>
|
||||||
|
<div class="row" style="margin-top:10px;align-items:stretch;">
|
||||||
|
<textarea id="chat_input" rows="2" style="flex:1;" placeholder="输入测试指令,例如:帮我查一下机顶盒状态,然后给它发一条普通提醒... (Ctrl+Enter 发送)"></textarea>
|
||||||
|
<button id="chat_send_btn" style="margin-top:0;min-width:110px;" onclick="sendChat()">发送</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- ==================== TAB 3: 全局配置 & 日志 ==================== -->
|
||||||
|
<section id="tab-global" class="tab-panel">
|
||||||
|
<div class="grid-2">
|
||||||
|
<div class="card">
|
||||||
|
<h2>
|
||||||
|
<span>🌐 全局默认「端侧修复 AI」配置(未单独配置的设备默认继承此项)</span>
|
||||||
|
<span id="global_cfg_dirty" class="badge off" style="display:none;">有未保存修改</span>
|
||||||
|
</h2>
|
||||||
|
<label><input type="checkbox" id="g_ai_enabled" style="width:auto;margin-right:6px;">默认启用端侧自动修复哨兵</label>
|
||||||
|
<label>OpenAI Base URL</label>
|
||||||
|
<input id="g_ai_base_url" placeholder="https://api.openai.com/v1" />
|
||||||
|
<label>API Key</label>
|
||||||
|
<input id="g_ai_api_key" type="password" placeholder="sk-..." />
|
||||||
|
<label>Model</label>
|
||||||
|
<input id="g_ai_model" placeholder="gpt-4o-mini / deepseek-chat / ..." />
|
||||||
|
<div class="row">
|
||||||
|
<div style="flex:1"><label>最大重试次数</label><input id="g_ai_retries" type="number" value="3" /></div>
|
||||||
|
<div style="flex:1"><label>运行报错冷却(秒)</label><input id="g_ai_cooldown" type="number" value="30" /></div>
|
||||||
|
</div>
|
||||||
|
<label style="margin-top:14px;"><input type="checkbox" id="g_lan_debug" style="width:auto;margin-right:6px;">启用全局「仅限局域网」ADB 开发者调试 API</label>
|
||||||
|
<div class="row">
|
||||||
|
<button onclick="saveGlobalConfig()">💾 保存全局配置并同步在线设备</button>
|
||||||
|
<button class="secondary" onclick="loadGlobalAndChatConfig(true)">重新读取</button>
|
||||||
|
</div>
|
||||||
|
<div id="global_cfg_msg" class="mono" style="margin-top:8px;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>🚀 App 自更新分发 (OTA) & 待处理反向事件</h2>
|
||||||
|
<div id="ota_info" class="mono" style="margin-bottom:8px;">检测中...</div>
|
||||||
|
<div class="row" style="margin-bottom:14px;">
|
||||||
|
<button onclick="pushOta(null)">🚀 全量推送 OTA 更新到所有在线设备</button>
|
||||||
|
<a id="ota_dl_link" href="/api/ota/download/pulsewall-latest.apk" style="color:var(--accent);font-size:13px;margin-top:8px;display:none;">下载最新 APK</a>
|
||||||
|
</div>
|
||||||
|
<div id="ota_msg" class="mono" style="margin-bottom:12px;"></div>
|
||||||
|
<h2 style="margin-top:8px;">📬 待处理反向事件(用户操作 & 修复 AI 数据追问)</h2>
|
||||||
|
<div id="events_list" class="log-list">暂无</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>📜 交互与审计日志</h2>
|
||||||
|
<div id="audits_list" class="log-list">加载中...</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
let globalConfig = null;
|
||||||
|
let devicesCache = [];
|
||||||
|
let selectedDeviceId = null;
|
||||||
|
|
||||||
|
let globalCfgDirty = false;
|
||||||
|
let chatCfgDirty = false;
|
||||||
|
let deviceFormDirty = false;
|
||||||
|
let currentRenderedDeviceId = null;
|
||||||
|
|
||||||
|
const chatHistory = [];
|
||||||
|
|
||||||
|
async function api(path, opts = {}) {
|
||||||
|
const res = await fetch(path, { headers: { 'Content-Type': 'application/json' }, ...opts });
|
||||||
|
return res.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
function escapeHtml(s) {
|
||||||
|
return String(s ?? '').replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"');
|
||||||
|
}
|
||||||
|
|
||||||
|
function switchTab(name) {
|
||||||
|
document.querySelectorAll('.tab-btn').forEach(b => b.classList.toggle('active', b.dataset.tab === name));
|
||||||
|
document.querySelectorAll('.tab-panel').forEach(p => p.classList.toggle('active', p.id === 'tab-' + name));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Dirty tracking for Global & Hub Chat AI forms ----
|
||||||
|
['g_ai_enabled','g_ai_base_url','g_ai_api_key','g_ai_model','g_ai_retries','g_ai_cooldown','g_lan_debug'].forEach(id => {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
el.addEventListener('input', () => { globalCfgDirty = true; document.getElementById('global_cfg_dirty').style.display='inline-block'; });
|
||||||
|
el.addEventListener('change', () => { globalCfgDirty = true; document.getElementById('global_cfg_dirty').style.display='inline-block'; });
|
||||||
|
});
|
||||||
|
['chat_ai_base_url','chat_ai_api_key','chat_ai_model','chat_ai_system'].forEach(id => {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
el.addEventListener('input', () => { chatCfgDirty = true; document.getElementById('chat_cfg_dirty').style.display='inline-block'; });
|
||||||
|
});
|
||||||
|
|
||||||
|
async function loadGlobalAndChatConfig(force = false) {
|
||||||
|
const cfg = await api('/api/admin/config');
|
||||||
|
globalConfig = cfg;
|
||||||
|
if (force || !globalCfgDirty) {
|
||||||
|
const r = cfg.repair_ai || {};
|
||||||
|
document.getElementById('g_ai_enabled').checked = !!r.enabled;
|
||||||
|
document.getElementById('g_ai_base_url').value = r.base_url || '';
|
||||||
|
document.getElementById('g_ai_api_key').value = r.api_key || '';
|
||||||
|
document.getElementById('g_ai_model').value = r.model || '';
|
||||||
|
document.getElementById('g_ai_retries').value = r.max_retries ?? 3;
|
||||||
|
document.getElementById('g_ai_cooldown').value = r.runtime_cooldown_sec ?? 30;
|
||||||
|
document.getElementById('g_lan_debug').checked = !!cfg.lan_debug_enabled;
|
||||||
|
globalCfgDirty = false;
|
||||||
|
document.getElementById('global_cfg_dirty').style.display = 'none';
|
||||||
|
}
|
||||||
|
if (force || !chatCfgDirty) {
|
||||||
|
const c = cfg.hub_chat_ai || {};
|
||||||
|
document.getElementById('chat_ai_base_url').value = c.base_url || '';
|
||||||
|
document.getElementById('chat_ai_api_key').value = c.api_key || '';
|
||||||
|
document.getElementById('chat_ai_model').value = c.model || '';
|
||||||
|
document.getElementById('chat_ai_system').value = c.system_prompt || '';
|
||||||
|
chatCfgDirty = false;
|
||||||
|
document.getElementById('chat_cfg_dirty').style.display = 'none';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveGlobalConfig() {
|
||||||
|
const body = {
|
||||||
|
repair_ai: {
|
||||||
|
enabled: document.getElementById('g_ai_enabled').checked,
|
||||||
|
base_url: document.getElementById('g_ai_base_url').value.trim(),
|
||||||
|
api_key: document.getElementById('g_ai_api_key').value.trim(),
|
||||||
|
model: document.getElementById('g_ai_model').value.trim(),
|
||||||
|
max_retries: parseInt(document.getElementById('g_ai_retries').value || '3', 10),
|
||||||
|
runtime_cooldown_sec: parseInt(document.getElementById('g_ai_cooldown').value || '30', 10),
|
||||||
|
timeout_sec: (globalConfig && globalConfig.repair_ai && globalConfig.repair_ai.timeout_sec) || 30
|
||||||
|
},
|
||||||
|
hub_chat_ai: (globalConfig && globalConfig.hub_chat_ai) || undefined,
|
||||||
|
lan_debug_enabled: document.getElementById('g_lan_debug').checked,
|
||||||
|
telemetry_interval_sec: (globalConfig && globalConfig.telemetry_interval_sec) || 10,
|
||||||
|
theme: (globalConfig && globalConfig.theme) || 'dark-glass',
|
||||||
|
auth_token: (globalConfig && globalConfig.auth_token) || ''
|
||||||
|
};
|
||||||
|
const r = await api('/api/admin/config', { method: 'PUT', body: JSON.stringify(body) });
|
||||||
|
globalConfig = { ...(globalConfig || {}), ...body };
|
||||||
|
globalCfgDirty = false;
|
||||||
|
document.getElementById('global_cfg_dirty').style.display = 'none';
|
||||||
|
document.getElementById('global_cfg_msg').textContent = `✅ 全局配置已持久化保存,已同步 ${r.pushed_devices} 台在线设备(使用独立配置的设备不受覆盖)`;
|
||||||
|
refreshLivePanels();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveHubChatConfig() {
|
||||||
|
const body = {
|
||||||
|
base_url: document.getElementById('chat_ai_base_url').value.trim(),
|
||||||
|
api_key: document.getElementById('chat_ai_api_key').value.trim(),
|
||||||
|
model: document.getElementById('chat_ai_model').value.trim(),
|
||||||
|
system_prompt: document.getElementById('chat_ai_system').value.trim(),
|
||||||
|
timeout_sec: 60
|
||||||
|
};
|
||||||
|
const r = await api('/api/admin/chat-ai-config', { method: 'PUT', body: JSON.stringify(body) });
|
||||||
|
if (globalConfig) globalConfig.hub_chat_ai = r.hub_chat_ai;
|
||||||
|
chatCfgDirty = false;
|
||||||
|
document.getElementById('chat_cfg_dirty').style.display = 'none';
|
||||||
|
document.getElementById('chat_cfg_msg').textContent = '✅ 中心桥专用 AI 配置已保存';
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Tab 1: Device List & Per-Device Settings ----
|
||||||
|
function selectDevice(deviceId) {
|
||||||
|
if (selectedDeviceId === deviceId) return;
|
||||||
|
selectedDeviceId = deviceId;
|
||||||
|
deviceFormDirty = false;
|
||||||
|
currentRenderedDeviceId = null;
|
||||||
|
renderDeviceSidebar();
|
||||||
|
renderDeviceDetail(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderDeviceSidebar() {
|
||||||
|
const box = document.getElementById('device_list_sidebar');
|
||||||
|
if (!devicesCache.length) {
|
||||||
|
box.innerHTML = '<div class="mono">尚无设备接入。<br/>启动 App 连接 ws://<HubIP>:8765 即可自动出现。</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!selectedDeviceId || !devicesCache.some(d => d.device_id === selectedDeviceId)) {
|
||||||
|
selectedDeviceId = devicesCache[0].device_id;
|
||||||
|
}
|
||||||
|
box.innerHTML = devicesCache.map(d => {
|
||||||
|
const p = d.display_profile || {};
|
||||||
|
const hasCustom = !!d.repair_ai_override;
|
||||||
|
return `<div class="dev-card ${d.device_id === selectedDeviceId ? 'selected' : ''}" onclick="selectDevice('${escapeHtml(d.device_id)}')">
|
||||||
|
<div class="row" style="justify-content:space-between;">
|
||||||
|
<strong>${escapeHtml(d.device_name)}</strong>
|
||||||
|
<span class="badge ${d.online ? 'on' : 'off'}">${d.online ? 'ONLINE' : 'OFFLINE'}</span>
|
||||||
|
</div>
|
||||||
|
<div class="mono" style="margin:5px 0;">${escapeHtml(d.device_id)} · ${escapeHtml(p.device_type || 'android')} · ${p.viewport_css_w || '?'}×${p.viewport_css_h || '?'}</div>
|
||||||
|
<div>
|
||||||
|
<span class="badge ${hasCustom ? 'custom' : ''}">${hasCustom ? '独立 AI: ' + escapeHtml(d.repair_ai_override.model || '-') : '继承全局 AI'}</span>
|
||||||
|
${(d.capabilities || []).map(c => `<span class="badge">${escapeHtml(c)}</span>`).join('')}
|
||||||
|
</div>
|
||||||
|
</div>`;
|
||||||
|
}).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renderDeviceDetail(forceRebuild = false) {
|
||||||
|
const pane = document.getElementById('device_detail_pane');
|
||||||
|
const d = devicesCache.find(x => x.device_id === selectedDeviceId);
|
||||||
|
if (!d) {
|
||||||
|
pane.innerHTML = '<div class="card"><div class="mono">尚无在线或历史设备。</div></div>';
|
||||||
|
currentRenderedDeviceId = null;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If already rendered for this device and user is editing form, ONLY update live telemetry values without destroying form inputs!
|
||||||
|
if (!forceRebuild && currentRenderedDeviceId === d.device_id) {
|
||||||
|
updateLiveDeviceTelemetryDom(d);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
currentRenderedDeviceId = d.device_id;
|
||||||
|
const hasCustom = !!d.repair_ai_override;
|
||||||
|
const baseAi = d.repair_ai_override || (globalConfig && globalConfig.repair_ai) || {
|
||||||
|
enabled: false, base_url: 'https://api.openai.com/v1', api_key: '', model: 'gpt-4o-mini', max_retries: 3, runtime_cooldown_sec: 30
|
||||||
|
};
|
||||||
|
|
||||||
|
pane.innerHTML = `
|
||||||
|
<div class="card">
|
||||||
|
<h2>
|
||||||
|
<span>📺 ${escapeHtml(d.device_name)} <span class="mono">(${escapeHtml(d.device_id)})</span></span>
|
||||||
|
<span id="det_online_badge" class="badge ${d.online ? 'on' : 'off'}">${d.online ? 'ONLINE' : 'OFFLINE'}</span>
|
||||||
|
</h2>
|
||||||
|
<div class="kv-grid" id="det_kv_grid"></div>
|
||||||
|
<div class="row">
|
||||||
|
<button onclick="deviceQuickAction('feed')">推送普通消息 (叮)</button>
|
||||||
|
<button class="danger" onclick="deviceQuickAction('alarm')">🚨 触发全屏红屏警报</button>
|
||||||
|
<button class="secondary" onclick="deviceQuickAction('render')">下发测试动态页</button>
|
||||||
|
<button class="secondary" onclick="deviceQuickAction('home')">🏠 恢复默认首页</button>
|
||||||
|
<button class="secondary" onclick="pushOta('${escapeHtml(d.device_id)}')">🚀 单独推 OTA</button>
|
||||||
|
</div>
|
||||||
|
<div id="det_action_msg" class="mono" style="margin-top:8px;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>
|
||||||
|
<span>🤖 本设备专属「端侧修复 AI」配置</span>
|
||||||
|
<span id="dev_ai_dirty" class="badge off" style="display:none;">有未保存修改</span>
|
||||||
|
</h2>
|
||||||
|
<div class="row" style="margin-bottom:10px;">
|
||||||
|
<label style="margin:0;display:flex;align-items:center;gap:6px;cursor:pointer;">
|
||||||
|
<input type="radio" name="dev_ai_mode" value="inherit" style="width:auto;" ${!hasCustom ? 'checked' : ''} onchange="toggleDevAiMode()" />
|
||||||
|
继承全局默认 AI 配置
|
||||||
|
</label>
|
||||||
|
<label style="margin:0;display:flex;align-items:center;gap:6px;cursor:pointer;margin-left:14px;">
|
||||||
|
<input type="radio" name="dev_ai_mode" value="custom" style="width:auto;" ${hasCustom ? 'checked' : ''} onchange="toggleDevAiMode()" />
|
||||||
|
使用本设备独立 AI 配置
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div id="dev_ai_fields" style="${!hasCustom ? 'opacity:0.55;' : ''}">
|
||||||
|
<label><input type="checkbox" id="d_ai_enabled" style="width:auto;margin-right:6px;" ${baseAi.enabled ? 'checked' : ''}>启用端侧自动修复哨兵</label>
|
||||||
|
<div class="row">
|
||||||
|
<div style="flex:1.4;min-width:200px;"><label>OpenAI Base URL</label><input id="d_ai_base_url" value="${escapeHtml(baseAi.base_url || '')}" /></div>
|
||||||
|
<div style="flex:1;min-width:160px;"><label>Model</label><input id="d_ai_model" value="${escapeHtml(baseAi.model || '')}" /></div>
|
||||||
|
</div>
|
||||||
|
<label>API Key</label>
|
||||||
|
<input id="d_ai_api_key" type="password" value="${escapeHtml(baseAi.api_key || '')}" placeholder="sk-..." />
|
||||||
|
<div class="row">
|
||||||
|
<div style="flex:1"><label>最大重试次数</label><input id="d_ai_retries" type="number" value="${baseAi.max_retries ?? 3}" /></div>
|
||||||
|
<div style="flex:1"><label>运行报错冷却(秒)</label><input id="d_ai_cooldown" type="number" value="${baseAi.runtime_cooldown_sec ?? 30}" /></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button onclick="saveDeviceAiConfig('${escapeHtml(d.device_id)}')">💾 保存该设备 AI 配置并立即同步</button>
|
||||||
|
<div id="dev_ai_msg" class="mono" style="margin-top:8px;"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="card">
|
||||||
|
<h2>🛠️ 局域网开发者调试 (LAN ADB) & 页面快照回滚</h2>
|
||||||
|
<div class="row" style="margin-bottom:12px;">
|
||||||
|
<input id="det_adb_target" value="${escapeHtml(d.adb_target || '')}" placeholder="局域网 ADB 地址如 192.168.1.50:5555" style="flex:1;" />
|
||||||
|
<button class="secondary" style="margin-top:0;" onclick="toggleLanDebug('${escapeHtml(d.device_id)}', ${!d.lan_debug_allowed})">
|
||||||
|
${d.lan_debug_allowed ? '关闭该设备 LAN ADB' : '授权该设备 LAN ADB'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div id="det_snapshots" class="log-list">加载快照...</div>
|
||||||
|
</div>
|
||||||
|
`;
|
||||||
|
|
||||||
|
['d_ai_enabled','d_ai_base_url','d_ai_api_key','d_ai_model','d_ai_retries','d_ai_cooldown'].forEach(id => {
|
||||||
|
const el = document.getElementById(id);
|
||||||
|
if (!el) return;
|
||||||
|
el.addEventListener('input', () => { deviceFormDirty = true; document.getElementById('dev_ai_dirty').style.display='inline-block'; });
|
||||||
|
el.addEventListener('change', () => { deviceFormDirty = true; document.getElementById('dev_ai_dirty').style.display='inline-block'; });
|
||||||
|
});
|
||||||
|
toggleDevAiMode(false);
|
||||||
|
updateLiveDeviceTelemetryDom(d);
|
||||||
|
loadDeviceSnapshots(d.device_id);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateLiveDeviceTelemetryDom(d) {
|
||||||
|
const badge = document.getElementById('det_online_badge');
|
||||||
|
if (badge) {
|
||||||
|
badge.className = 'badge ' + (d.online ? 'on' : 'off');
|
||||||
|
badge.textContent = d.online ? 'ONLINE' : 'OFFLINE';
|
||||||
|
}
|
||||||
|
const kv = document.getElementById('det_kv_grid');
|
||||||
|
if (kv) {
|
||||||
|
const p = d.display_profile || {};
|
||||||
|
const t = d.telemetry || {};
|
||||||
|
const thermals = t.thermal_zones ? Object.entries(t.thermal_zones).slice(0,3).map(([k,v]) => `${k}:${v}°C`).join(' ') : '';
|
||||||
|
kv.innerHTML = `
|
||||||
|
<div class="kv-box"><div class="k">型号 / 系统</div><div class="v">${escapeHtml(d.model || '-')} · Android ${escapeHtml(d.android_release)}</div></div>
|
||||||
|
<div class="kv-box"><div class="k">App / WebView</div><div class="v">${escapeHtml(d.app_version || '-')} / ${escapeHtml(p.webview_version || '-')}</div></div>
|
||||||
|
<div class="kv-box"><div class="k">视口 / 形态</div><div class="v">${p.viewport_css_w || '?'}×${p.viewport_css_h || '?'} (${escapeHtml(p.device_type || '-')} · ${escapeHtml(p.orientation || '-')})</div></div>
|
||||||
|
<div class="kv-box"><div class="k">电源 / 内存</div><div class="v">${t.battery_pct ?? '外接'}% · ${t.battery_temp_c ?? '?'}°C · ${t.mem_used_mb ?? '?'}/${t.mem_total_mb ?? '?'}MB</div></div>
|
||||||
|
<div class="kv-box"><div class="k">设备能力</div><div class="v">${(d.capabilities || []).join(', ')}</div></div>
|
||||||
|
<div class="kv-box"><div class="k">热区温度</div><div class="v">${escapeHtml(thermals || '--')}</div></div>
|
||||||
|
`;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleDevAiMode(markDirty = true) {
|
||||||
|
const radio = document.querySelector('input[name="dev_ai_mode"]:checked');
|
||||||
|
const isCustom = radio && radio.value === 'custom';
|
||||||
|
const box = document.getElementById('dev_ai_fields');
|
||||||
|
if (box) {
|
||||||
|
box.style.opacity = isCustom ? '1' : '0.5';
|
||||||
|
box.querySelectorAll('input').forEach(inp => inp.disabled = !isCustom);
|
||||||
|
}
|
||||||
|
if (markDirty) {
|
||||||
|
deviceFormDirty = true;
|
||||||
|
const b = document.getElementById('dev_ai_dirty');
|
||||||
|
if (b) b.style.display = 'inline-block';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveDeviceAiConfig(deviceId) {
|
||||||
|
const isCustom = document.querySelector('input[name="dev_ai_mode"]:checked')?.value === 'custom';
|
||||||
|
const payload = {
|
||||||
|
use_custom: isCustom,
|
||||||
|
repair_ai: isCustom ? {
|
||||||
|
enabled: document.getElementById('d_ai_enabled').checked,
|
||||||
|
base_url: document.getElementById('d_ai_base_url').value.trim(),
|
||||||
|
api_key: document.getElementById('d_ai_api_key').value.trim(),
|
||||||
|
model: document.getElementById('d_ai_model').value.trim(),
|
||||||
|
max_retries: parseInt(document.getElementById('d_ai_retries').value || '3', 10),
|
||||||
|
runtime_cooldown_sec: parseInt(document.getElementById('d_ai_cooldown').value || '30', 10),
|
||||||
|
timeout_sec: 30
|
||||||
|
} : null
|
||||||
|
};
|
||||||
|
const r = await api(`/api/admin/devices/${encodeURIComponent(deviceId)}/repair-ai`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(payload)
|
||||||
|
});
|
||||||
|
deviceFormDirty = false;
|
||||||
|
document.getElementById('dev_ai_dirty').style.display = 'none';
|
||||||
|
document.getElementById('dev_ai_msg').textContent = r.pushed_online
|
||||||
|
? '✅ 已持久化保存并立即热同步至该设备'
|
||||||
|
: '✅ 已持久化保存(设备当前离线,下次上线将自动推送此配置)';
|
||||||
|
await refreshLivePanels();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadDeviceSnapshots(deviceId) {
|
||||||
|
const el = document.getElementById('det_snapshots');
|
||||||
|
if (!el) return;
|
||||||
|
const r = await api(`/api/admin/snapshots/${encodeURIComponent(deviceId)}`);
|
||||||
|
if (!r.snapshots || !r.snapshots.length) {
|
||||||
|
el.innerHTML = '<div class="mono">该设备暂无动态页面快照</div>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = r.snapshots.map(s => `
|
||||||
|
<div class="log-row row" style="justify-content:space-between;">
|
||||||
|
<div><span class="badge">${escapeHtml(s.status)}</span> <strong>${escapeHtml(s.title || s.snapshot_id)}</strong> <span class="mono">${new Date(s.created_at_ms).toLocaleTimeString()}</span></div>
|
||||||
|
<button class="secondary small" onclick="rollbackSnapshot('${escapeHtml(deviceId)}','${escapeHtml(s.snapshot_id)}')">回滚此页</button>
|
||||||
|
</div>
|
||||||
|
`).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rollbackSnapshot(deviceId, snapshotId) {
|
||||||
|
const r = await api(`/api/admin/devices/${encodeURIComponent(deviceId)}/rollback`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ snapshot_id: snapshotId })
|
||||||
|
});
|
||||||
|
document.getElementById('det_action_msg').textContent = r.ok ? `已下发回滚至 ${snapshotId}` : JSON.stringify(r);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deviceQuickAction(kind) {
|
||||||
|
if (!selectedDeviceId) return;
|
||||||
|
const r = await api(`/api/admin/test/${kind}`, { method: 'POST', body: JSON.stringify({ device_id: selectedDeviceId }) });
|
||||||
|
document.getElementById('det_action_msg').textContent = JSON.stringify(r);
|
||||||
|
if (kind === 'render') loadDeviceSnapshots(selectedDeviceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleLanDebug(deviceId, allow) {
|
||||||
|
const adbTarget = (document.getElementById('det_adb_target')?.value || '').trim();
|
||||||
|
await api(`/api/admin/devices/${encodeURIComponent(deviceId)}/lan-debug`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ allowed: allow, adb_target: adbTarget })
|
||||||
|
});
|
||||||
|
await refreshLivePanels();
|
||||||
|
renderDeviceDetail(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pushOta(deviceId) {
|
||||||
|
const url = deviceId ? `/api/admin/ota/push?device_id=${encodeURIComponent(deviceId)}` : '/api/admin/ota/push';
|
||||||
|
const r = await api(url, { method: 'POST' });
|
||||||
|
const text = `🚀 已推送 OTA 更新通知给 ${r.pushed_devices} 台在线设备`;
|
||||||
|
const m1 = document.getElementById('ota_msg');
|
||||||
|
const m2 = document.getElementById('det_action_msg');
|
||||||
|
if (m1) m1.textContent = text;
|
||||||
|
if (deviceId && m2) m2.textContent = text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Tab 2: AI Chat Console ----
|
||||||
|
function appendChatBubble(role, text, toolTrace = []) {
|
||||||
|
const wrap = document.getElementById('chat_messages');
|
||||||
|
const div = document.createElement('div');
|
||||||
|
div.className = 'msg ' + role;
|
||||||
|
div.textContent = text || '(空回复)';
|
||||||
|
|
||||||
|
if (toolTrace && toolTrace.length) {
|
||||||
|
const traceDiv = document.createElement('div');
|
||||||
|
traceDiv.className = 'tool-trace';
|
||||||
|
traceDiv.innerHTML = toolTrace.map((t, idx) => `
|
||||||
|
<details>
|
||||||
|
<summary>🔧 MCP 工具 #${idx + 1}: ${escapeHtml(t.name)} ${t.is_error ? '❌' : '✅'}</summary>
|
||||||
|
<pre>入参: ${escapeHtml(JSON.stringify(t.arguments, null, 2))}\n\n返回: ${escapeHtml(t.result)}</pre>
|
||||||
|
</details>
|
||||||
|
`).join('');
|
||||||
|
div.appendChild(traceDiv);
|
||||||
|
}
|
||||||
|
wrap.appendChild(div);
|
||||||
|
wrap.scrollTop = wrap.scrollHeight;
|
||||||
|
}
|
||||||
|
|
||||||
|
function quickAsk(prompt) {
|
||||||
|
document.getElementById('chat_input').value = prompt;
|
||||||
|
sendChat();
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearChat() {
|
||||||
|
chatHistory.length = 0;
|
||||||
|
document.getElementById('chat_messages').innerHTML =
|
||||||
|
'<div class="msg assistant">会话已清空。输入新指令即可开始新一轮 MCP 联调测试。</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendChat() {
|
||||||
|
const input = document.getElementById('chat_input');
|
||||||
|
const btn = document.getElementById('chat_send_btn');
|
||||||
|
const msg = input.value.trim();
|
||||||
|
if (!msg || btn.disabled) return;
|
||||||
|
|
||||||
|
input.value = '';
|
||||||
|
appendChatBubble('user', msg);
|
||||||
|
btn.disabled = true;
|
||||||
|
btn.textContent = '思考 & 调用 MCP 中...';
|
||||||
|
|
||||||
|
try {
|
||||||
|
const r = await api('/api/admin/chat', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ message: msg, history: chatHistory })
|
||||||
|
});
|
||||||
|
if (r.ok) {
|
||||||
|
chatHistory.push({ role: 'user', content: msg });
|
||||||
|
chatHistory.push({ role: 'assistant', content: r.reply || '' });
|
||||||
|
appendChatBubble('assistant', r.reply || '操作已完成。', r.tool_trace || []);
|
||||||
|
refreshLivePanels();
|
||||||
|
} else {
|
||||||
|
appendChatBubble('error', '❌ ' + (r.error || '调用失败'), r.tool_trace || []);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
appendChatBubble('error', '❌ 网络或服务异常: ' + e.message);
|
||||||
|
} finally {
|
||||||
|
btn.disabled = false;
|
||||||
|
btn.textContent = '发送';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('chat_input').addEventListener('keydown', e => {
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
sendChat();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---- Live Polling (NEVER overwrites forms being edited) ----
|
||||||
|
async function refreshLivePanels() {
|
||||||
|
const [devs, evts, audits, ota] = await Promise.all([
|
||||||
|
api('/api/admin/devices'),
|
||||||
|
api('/api/admin/events'),
|
||||||
|
api('/api/admin/audits'),
|
||||||
|
api('/api/ota/latest')
|
||||||
|
]);
|
||||||
|
devicesCache = devs.devices || [];
|
||||||
|
renderDeviceSidebar();
|
||||||
|
renderDeviceDetail(false);
|
||||||
|
|
||||||
|
const otaEl = document.getElementById('ota_info');
|
||||||
|
const otaLink = document.getElementById('ota_dl_link');
|
||||||
|
if (ota && ota.available) {
|
||||||
|
otaEl.textContent = `最新包: v${ota.version_name} (build ${ota.version_code}) · ${(ota.size_bytes/1048576).toFixed(2)} MB · SHA256: ${ota.sha256.slice(0,12)}...`;
|
||||||
|
otaLink.href = ota.download_path;
|
||||||
|
otaLink.style.display = 'inline-block';
|
||||||
|
} else {
|
||||||
|
otaEl.textContent = '尚未发布 APK(运行 ./android/build_apk.sh 自动发布)';
|
||||||
|
otaLink.style.display = 'none';
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('events_list').innerHTML = evts.events.length
|
||||||
|
? evts.events.map(e => `<div class="log-row"><span class="badge">${escapeHtml(e.event_type)}</span> <strong>${escapeHtml(e.device_id)}</strong> <span class="mono">${escapeHtml(JSON.stringify(e.payload))}</span></div>`).join('')
|
||||||
|
: '<div class="mono">暂无待处理事件</div>';
|
||||||
|
|
||||||
|
document.getElementById('audits_list').innerHTML = audits.audits.map(a =>
|
||||||
|
`<div class="log-row"><span class="badge">${escapeHtml(a.category)}</span> <strong>${escapeHtml(a.device_id || 'hub')}</strong> ${escapeHtml(a.summary)} <span class="mono">${new Date(a.created_at_ms).toLocaleTimeString()}</span></div>`
|
||||||
|
).join('') || '<div class="mono">暂无日志</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
(async function init() {
|
||||||
|
await loadGlobalAndChatConfig(true);
|
||||||
|
await refreshLivePanels();
|
||||||
|
setInterval(refreshLivePanels, 5000);
|
||||||
|
})();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
"""
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
|
||||||
|
DISCOVER_MAGIC = b"PULSEWALL_DISCOVER"
|
||||||
|
|
||||||
|
|
||||||
|
class _DiscoveryProtocol(asyncio.DatagramProtocol):
|
||||||
|
def __init__(self, hub_port: int, hub_name: str = "PulseWall Hub") -> None:
|
||||||
|
self.hub_port = hub_port
|
||||||
|
self.hub_name = hub_name
|
||||||
|
self.transport: asyncio.DatagramTransport | None = None
|
||||||
|
|
||||||
|
def connection_made(self, transport: asyncio.BaseTransport) -> None:
|
||||||
|
self.transport = transport # type: ignore[assignment]
|
||||||
|
|
||||||
|
def datagram_received(self, data: bytes, addr: tuple[str, int]) -> None:
|
||||||
|
if not data.startswith(DISCOVER_MAGIC) or self.transport is None:
|
||||||
|
return
|
||||||
|
reply: dict[str, Any] = {
|
||||||
|
"type": "PULSEWALL_HUB_HERE",
|
||||||
|
"hub_name": self.hub_name,
|
||||||
|
"port": self.hub_port,
|
||||||
|
"ws_path": "/ws/device",
|
||||||
|
"ota_path": "/api/ota/latest",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
self.transport.sendto(json.dumps(reply, ensure_ascii=False).encode("utf-8"), addr)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class LanDiscoveryResponder:
|
||||||
|
"""Listens on LAN UDP port (default 8766) so TV boxes / phones find Hub without typing IPs."""
|
||||||
|
|
||||||
|
def __init__(self, hub_port: int | None = None, udp_port: int | None = None) -> None:
|
||||||
|
self.hub_port = hub_port or int(os.environ.get("PULSEWALL_PORT", "8765"))
|
||||||
|
self.udp_port = udp_port if udp_port is not None else int(os.environ.get("PULSEWALL_DISCOVERY_PORT", "8766"))
|
||||||
|
self._transport: asyncio.DatagramTransport | None = None
|
||||||
|
|
||||||
|
async def start(self) -> None:
|
||||||
|
if self.udp_port <= 0:
|
||||||
|
return
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
try:
|
||||||
|
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||||
|
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||||
|
sock.bind(("0.0.0.0", self.udp_port))
|
||||||
|
self._transport, _ = await loop.create_datagram_endpoint(
|
||||||
|
lambda: _DiscoveryProtocol(self.hub_port),
|
||||||
|
sock=sock,
|
||||||
|
)
|
||||||
|
except OSError:
|
||||||
|
# Non-fatal if port busy in parallel test runs
|
||||||
|
self._transport = None
|
||||||
|
|
||||||
|
def stop(self) -> None:
|
||||||
|
if self._transport is not None:
|
||||||
|
self._transport.close()
|
||||||
|
self._transport = None
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
import httpx
|
||||||
|
from fastapi import WebSocket
|
||||||
|
|
||||||
|
from app.storage.db import PulseWallDB, now_ms
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceBridgeManager:
|
||||||
|
"""Manages active Android WebSocket sessions, pending render futures, and reverse event fan-out."""
|
||||||
|
|
||||||
|
def __init__(self, db: PulseWallDB) -> None:
|
||||||
|
self.db = db
|
||||||
|
self._connections: dict[str, WebSocket] = {}
|
||||||
|
self._pending_renders: dict[str, asyncio.Future[dict[str, Any]]] = {}
|
||||||
|
self._sse_subscribers: set[asyncio.Queue[dict[str, Any]]] = set()
|
||||||
|
|
||||||
|
def is_connected(self, device_id: str) -> bool:
|
||||||
|
return device_id in self._connections
|
||||||
|
|
||||||
|
def connected_device_ids(self) -> list[str]:
|
||||||
|
return list(self._connections.keys())
|
||||||
|
|
||||||
|
async def register(self, device_id: str, ws: WebSocket) -> None:
|
||||||
|
old = self._connections.get(device_id)
|
||||||
|
if old and old is not ws:
|
||||||
|
try:
|
||||||
|
await old.close(code=1001, reason="Replaced by new connection")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
self._connections[device_id] = ws
|
||||||
|
self.db.set_device_online(device_id, True)
|
||||||
|
self.db.add_audit("ws", device_id, "Device connected")
|
||||||
|
await self.push_config(device_id)
|
||||||
|
|
||||||
|
def unregister(self, device_id: str, ws: WebSocket) -> None:
|
||||||
|
if self._connections.get(device_id) is ws:
|
||||||
|
del self._connections[device_id]
|
||||||
|
self.db.set_device_online(device_id, False)
|
||||||
|
self.db.add_audit("ws", device_id, "Device disconnected")
|
||||||
|
|
||||||
|
async def close_all(self) -> None:
|
||||||
|
items = list(self._connections.items())
|
||||||
|
self._connections.clear()
|
||||||
|
for dev_id, ws in items:
|
||||||
|
self.db.set_device_online(dev_id, False)
|
||||||
|
try:
|
||||||
|
await ws.close(code=1001, reason="Hub shutting down")
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
|
||||||
|
async def send_frame(self, device_id: str, msg_type: str, payload: dict[str, Any]) -> bool:
|
||||||
|
ws = self._connections.get(device_id)
|
||||||
|
if not ws:
|
||||||
|
return False
|
||||||
|
frame = {
|
||||||
|
"type": msg_type,
|
||||||
|
"msg_id": str(uuid.uuid4()),
|
||||||
|
"ts": now_ms(),
|
||||||
|
"payload": payload,
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
await ws.send_text(json.dumps(frame, ensure_ascii=False))
|
||||||
|
return True
|
||||||
|
except Exception:
|
||||||
|
self.unregister(device_id, ws)
|
||||||
|
return False
|
||||||
|
|
||||||
|
async def push_config(self, device_id: str | None = None) -> int:
|
||||||
|
cfg = self.db.get_config()
|
||||||
|
targets = [device_id] if device_id else list(self._connections.keys())
|
||||||
|
sent = 0
|
||||||
|
for tid in targets:
|
||||||
|
effective_ai = self.db.get_effective_repair_ai(tid)
|
||||||
|
payload = {
|
||||||
|
"repair_ai": effective_ai.model_dump(),
|
||||||
|
"telemetry_interval_sec": cfg.telemetry_interval_sec,
|
||||||
|
"theme": cfg.theme,
|
||||||
|
}
|
||||||
|
if await self.send_frame(tid, "config.push", payload):
|
||||||
|
sent += 1
|
||||||
|
return sent
|
||||||
|
|
||||||
|
async def handle_incoming(self, device_id: str, raw_text: str) -> None:
|
||||||
|
try:
|
||||||
|
frame = json.loads(raw_text)
|
||||||
|
except json.JSONDecodeError:
|
||||||
|
return
|
||||||
|
msg_type = frame.get("type", "")
|
||||||
|
payload = frame.get("payload") or {}
|
||||||
|
|
||||||
|
if msg_type == "device.hello":
|
||||||
|
self.db.upsert_device_hello(device_id, payload)
|
||||||
|
await self.push_config(device_id)
|
||||||
|
await self._emit_event(device_id, "device_online", {"device_id": device_id, "model": payload.get("model", "")}, persist=False)
|
||||||
|
|
||||||
|
elif msg_type == "device.telemetry":
|
||||||
|
self.db.update_device_telemetry(device_id, payload)
|
||||||
|
|
||||||
|
elif msg_type == "render.result":
|
||||||
|
task_id = str(payload.get("task_id", ""))
|
||||||
|
snapshot_id = str(payload.get("snapshot_id", ""))
|
||||||
|
status = str(payload.get("status", "failed_rolled_back"))
|
||||||
|
final_html = payload.get("final_html")
|
||||||
|
fix_summary = str(payload.get("local_fix_summary", ""))
|
||||||
|
if snapshot_id:
|
||||||
|
self.db.update_snapshot_result(snapshot_id, status, final_html=final_html, local_fix_summary=fix_summary)
|
||||||
|
|
||||||
|
self.db.add_audit(
|
||||||
|
"render_result",
|
||||||
|
device_id,
|
||||||
|
f"Render {status} (task={task_id}, trigger={payload.get('trigger', 'initial_render')})",
|
||||||
|
{
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"status": status,
|
||||||
|
"attempts": payload.get("attempts", 0),
|
||||||
|
"local_fix_summary": fix_summary,
|
||||||
|
"errors": payload.get("errors", []),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# Resolve synchronous MCP waiter if present
|
||||||
|
fut = self._pending_renders.pop(task_id, None)
|
||||||
|
if fut and not fut.done():
|
||||||
|
fut.set_result(payload)
|
||||||
|
|
||||||
|
# If end-side Repair AI needs upstream data clarification, ALWAYS emit a reverse event too
|
||||||
|
if status == "needs_clarification" or payload.get("clarification_questions"):
|
||||||
|
await self._emit_event(device_id, "repair_data_clarification", payload, persist=True)
|
||||||
|
|
||||||
|
elif msg_type == "interaction.reply":
|
||||||
|
self.db.add_audit(
|
||||||
|
"interaction",
|
||||||
|
device_id,
|
||||||
|
f"User replied: {payload.get('selected_label') or payload.get('custom_text')}",
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
await self._emit_event(device_id, "user_interaction_reply", payload, persist=True)
|
||||||
|
|
||||||
|
elif msg_type == "console.error_report":
|
||||||
|
self.db.add_audit(
|
||||||
|
"console_error",
|
||||||
|
device_id,
|
||||||
|
f"Runtime console error: {payload.get('message', '')[:120]}",
|
||||||
|
payload,
|
||||||
|
)
|
||||||
|
await self._emit_event(device_id, "console_error", payload, persist=True)
|
||||||
|
|
||||||
|
async def send_render_and_wait(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
html: str,
|
||||||
|
mode: str = "full",
|
||||||
|
title: str = "",
|
||||||
|
data_context: dict[str, Any] | None = None,
|
||||||
|
wait_validation_sec: int = 15,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
task_id = f"task_{uuid.uuid4().hex[:10]}"
|
||||||
|
snapshot_id = self.db.create_snapshot(
|
||||||
|
device_id=device_id,
|
||||||
|
task_id=task_id,
|
||||||
|
html=html,
|
||||||
|
mode=mode,
|
||||||
|
title=title,
|
||||||
|
data_context=data_context,
|
||||||
|
status="pending",
|
||||||
|
)
|
||||||
|
if not self.is_connected(device_id):
|
||||||
|
self.db.update_snapshot_result(snapshot_id, "queued_offline")
|
||||||
|
return {
|
||||||
|
"status": "queued_offline",
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"message": f"Device '{device_id}' is currently offline. Snapshot saved.",
|
||||||
|
}
|
||||||
|
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
fut: asyncio.Future[dict[str, Any]] = loop.create_future()
|
||||||
|
self._pending_renders[task_id] = fut
|
||||||
|
|
||||||
|
sent = await self.send_frame(
|
||||||
|
device_id,
|
||||||
|
"render.apply",
|
||||||
|
{
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"mode": mode,
|
||||||
|
"title": title,
|
||||||
|
"html": html,
|
||||||
|
"data_context": data_context or {},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
if not sent:
|
||||||
|
self._pending_renders.pop(task_id, None)
|
||||||
|
self.db.update_snapshot_result(snapshot_id, "queued_offline")
|
||||||
|
return {
|
||||||
|
"status": "queued_offline",
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"message": f"Failed to send frame to '{device_id}'.",
|
||||||
|
}
|
||||||
|
|
||||||
|
self.db.add_audit("render_push", device_id, f"Dispatched render task {task_id} ({mode})", {"snapshot_id": snapshot_id})
|
||||||
|
|
||||||
|
if wait_validation_sec <= 0:
|
||||||
|
return {"status": "dispatched", "task_id": task_id, "snapshot_id": snapshot_id}
|
||||||
|
|
||||||
|
try:
|
||||||
|
result = await asyncio.wait_for(fut, timeout=float(wait_validation_sec))
|
||||||
|
result.setdefault("task_id", task_id)
|
||||||
|
result.setdefault("snapshot_id", snapshot_id)
|
||||||
|
return result
|
||||||
|
except asyncio.TimeoutError:
|
||||||
|
self._pending_renders.pop(task_id, None)
|
||||||
|
return {
|
||||||
|
"status": "validation_timeout",
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"message": f"Device did not finish validation/repair within {wait_validation_sec}s; check pending events later.",
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- SSE / Webhook Event Bus ----
|
||||||
|
def subscribe_sse(self) -> asyncio.Queue[dict[str, Any]]:
|
||||||
|
q: asyncio.Queue[dict[str, Any]] = asyncio.Queue(maxsize=100)
|
||||||
|
self._sse_subscribers.add(q)
|
||||||
|
return q
|
||||||
|
|
||||||
|
def unsubscribe_sse(self, q: asyncio.Queue[dict[str, Any]]) -> None:
|
||||||
|
self._sse_subscribers.discard(q)
|
||||||
|
|
||||||
|
async def _emit_event(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
event_type: str,
|
||||||
|
payload: dict[str, Any],
|
||||||
|
persist: bool = True,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
if persist:
|
||||||
|
event = self.db.create_event(device_id, event_type, payload)
|
||||||
|
else:
|
||||||
|
event = {
|
||||||
|
"event_id": f"evt_{uuid.uuid4().hex[:10]}",
|
||||||
|
"device_id": device_id,
|
||||||
|
"event_type": event_type,
|
||||||
|
"payload": payload,
|
||||||
|
"acked": False,
|
||||||
|
"created_at_ms": now_ms(),
|
||||||
|
}
|
||||||
|
|
||||||
|
for q in list(self._sse_subscribers):
|
||||||
|
try:
|
||||||
|
q.put_nowait(event)
|
||||||
|
except asyncio.QueueFull:
|
||||||
|
pass
|
||||||
|
|
||||||
|
if persist:
|
||||||
|
webhooks = self.db.list_webhooks()
|
||||||
|
if webhooks:
|
||||||
|
asyncio.create_task(self._dispatch_webhooks(webhooks, event))
|
||||||
|
return event
|
||||||
|
|
||||||
|
async def _dispatch_webhooks(self, webhooks: list[dict[str, Any]], event: dict[str, Any]) -> None:
|
||||||
|
async with httpx.AsyncClient(timeout=8.0) as client:
|
||||||
|
for wh in webhooks:
|
||||||
|
headers = {"Content-Type": "application/json"}
|
||||||
|
if wh.get("secret"):
|
||||||
|
headers["X-PulseWall-Secret"] = wh["secret"]
|
||||||
|
try:
|
||||||
|
await client.post(wh["url"], json=event, headers=headers)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
+656
@@ -0,0 +1,656 @@
|
|||||||
|
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 = """
|
||||||
|
<div class="pw-stack">
|
||||||
|
<div class="pw-card pw-hero">
|
||||||
|
<div class="pw-row pw-between">
|
||||||
|
<span class="pw-pill pw-ok">LIVE · AI CANVAS</span>
|
||||||
|
<span class="pw-muted" id="clock">--:--:--</span>
|
||||||
|
</div>
|
||||||
|
<h1 style="margin:8px 0 4px;font-size:22px;">PulseWall 动态画布已就绪</h1>
|
||||||
|
<p class="pw-muted" style="margin:0;">当前页面由中心桥下发并通过了端侧校验与自适应渲染。</p>
|
||||||
|
</div>
|
||||||
|
<div class="pw-grid-2">
|
||||||
|
<div class="pw-card">
|
||||||
|
<div class="pw-muted">系统状态</div>
|
||||||
|
<div class="pw-metric pw-ok-text">HEALTHY</div>
|
||||||
|
</div>
|
||||||
|
<div class="pw-card">
|
||||||
|
<div class="pw-muted">快速回报</div>
|
||||||
|
<button class="pw-btn pw-btn-primary" onclick="window.PulseWall.sendAction('canvas_ping','画布测试正常',null)">点我回传中心桥</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<script>
|
||||||
|
function tick(){ var el=document.getElementById('clock'); if(el) el.textContent=new Date().toLocaleTimeString(); }
|
||||||
|
tick(); setInterval(tick, 1000);
|
||||||
|
</script>
|
||||||
|
"""
|
||||||
|
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()
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import contextvars
|
||||||
|
import json
|
||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from mcp.server.mcpserver import MCPServer
|
||||||
|
|
||||||
|
from app.adb_lan.controller import LanAdbController
|
||||||
|
from app.bridge.manager import DeviceBridgeManager
|
||||||
|
from app.storage.db import PulseWallDB, now_ms
|
||||||
|
|
||||||
|
# Populated by ASGI middleware on /mcp to verify whether the caller is on private LAN.
|
||||||
|
mcp_request_is_lan: contextvars.ContextVar[bool] = contextvars.ContextVar("mcp_request_is_lan", default=False)
|
||||||
|
|
||||||
|
|
||||||
|
UI_FRAMEWORK_GUIDE = {
|
||||||
|
"local_assets_base": "https://appassets.androidplatform.net/assets/pulsewall/",
|
||||||
|
"preloaded_globals": [
|
||||||
|
"Vue (Vue 3 runtime)",
|
||||||
|
"dayjs (Day.js datetime ~2KB)",
|
||||||
|
"PwIcons (ultra-light offline SVG icons: PwIcons.svg('cpu', 20) or <span data-pw-icon='cpu'></span>)",
|
||||||
|
"pulsewall-tokens.css + tailwind-lite.min.css (zero-runtime Tailwind utility classes & dark-glass tokens)",
|
||||||
|
"window.PulseWall JSBridge: loadLib(nameOrArray), sendAction(id, label, customText), getDeviceProfile(), getTelemetry(), getDataContext()",
|
||||||
|
],
|
||||||
|
"lazy_local_libraries": {
|
||||||
|
"usage": "Call `await window.PulseWall.loadLib(['plyr', 'hls'])` (or `<script src='./libs/...'>`). All files load offline from APK in <5ms — NEVER use external CDN URLs when a local library exists!",
|
||||||
|
"libs": {
|
||||||
|
"plyr": {"global": "Plyr", "files": "./libs/plyr.min.js + ./libs/plyr.css", "use_for": "Lightweight zero-dep media player UI (preferred)"},
|
||||||
|
"hls": {"global": "Hls", "files": "./libs/hls.light.min.js", "use_for": "HLS (.m3u8) live/VOD streaming engine (light build)"},
|
||||||
|
"echarts": {"global": "echarts", "files": "./libs/echarts.custom.min.js", "heavy": True, "use_for": "Tree-shaken ECharts (Line/Bar/Pie/Gauge/Radar/Scatter + CanvasRenderer). Load ONLY when rich charts are needed."},
|
||||||
|
"konva": {"global": "Konva", "files": "./libs/konva.min.js", "use_for": "2D interactive canvas & object manipulation"},
|
||||||
|
"three": {"global": "THREE", "files": "./libs/three.min.js", "heavy": True, "use_for": "3D WebGL scenes. Heavy — avoid on low-end TV boxes unless explicitly requested."},
|
||||||
|
"rough": {"global": "rough", "files": "./libs/rough.min.js", "use_for": "Hand-drawn sketchy Canvas/SVG visuals (<9KB)"},
|
||||||
|
"lodash": {"global": "_", "files": "./libs/lodash-lite.min.js", "use_for": "Tree-shaken lodash-es (debounce, throttle, cloneDeep, merge, groupBy, sortBy, orderBy, uniq, chunk, clamp, pick, omit, get, set, sumBy, meanBy, keyBy, round, range)"},
|
||||||
|
"zustand": {"global": "Zustand", "files": "./libs/zustand.min.js", "use_for": "Minimal shared state store (`Zustand.createStore`, ~1KB)"},
|
||||||
|
"anime": {"global": "anime", "files": "./libs/anime.min.js", "use_for": "Lightweight JS animation (~6KB, use only when CSS transitions aren't enough)"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"compatibility_rules": [
|
||||||
|
"Always respect device viewport_css_w / viewport_css_h, device_type (tv/phone/tablet), and safe_area_top_dp / safe_area_bottom_dp.",
|
||||||
|
"Prefer lightweight core libs (Vue + tailwind-lite + dayjs + PwIcons + rough/konva); only lazy-load heavy libs (echarts, three) when genuinely needed.",
|
||||||
|
"Avoid fixed pixel widths exceeding viewport_css_w; prefer flexbox/grid and relative units.",
|
||||||
|
"Target Android 11 WebView compatibility (Chrome 83+ / ES2020): avoid bleeding-edge CSS like :has() or container queries unless guarded.",
|
||||||
|
"Never overwrite native alert layer; render page content inside the canvas container only.",
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def build_mcp_server(
|
||||||
|
db: PulseWallDB,
|
||||||
|
bridge: DeviceBridgeManager,
|
||||||
|
adb_controller: LanAdbController,
|
||||||
|
) -> MCPServer:
|
||||||
|
mcp = MCPServer(
|
||||||
|
name="PulseWall Hub",
|
||||||
|
instructions=(
|
||||||
|
"PulseWall controls connected Android information-wall devices. "
|
||||||
|
"Always inspect get_device_status(device_id) before calling render_page so styles match the exact "
|
||||||
|
"phone/tablet viewport and Android 11 WebView version. For important alerts requiring user action, "
|
||||||
|
"provide 2-4 high-probability preset buttons before optional free-text input."
|
||||||
|
),
|
||||||
|
version="0.1.0",
|
||||||
|
)
|
||||||
|
|
||||||
|
# ---- Resources ----
|
||||||
|
@mcp.resource("pulsewall://devices")
|
||||||
|
def res_devices() -> str:
|
||||||
|
return json.dumps(db.list_devices(), ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
@mcp.resource("pulsewall://device/{device_id}/profile")
|
||||||
|
def res_device_profile(device_id: str) -> str:
|
||||||
|
dev = db.get_device(device_id)
|
||||||
|
if not dev:
|
||||||
|
return json.dumps({"error": f"Device '{device_id}' not found"}, ensure_ascii=False)
|
||||||
|
return json.dumps(
|
||||||
|
{
|
||||||
|
"device": dev,
|
||||||
|
"ui_framework_guide": UI_FRAMEWORK_GUIDE,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
indent=2,
|
||||||
|
)
|
||||||
|
|
||||||
|
@mcp.resource("pulsewall://device/{device_id}/layout")
|
||||||
|
def res_device_layout(device_id: str) -> str:
|
||||||
|
snaps = db.list_snapshots(device_id=device_id, limit=5)
|
||||||
|
return json.dumps({"device_id": device_id, "recent_snapshots": snaps}, ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
@mcp.resource("pulsewall://events/pending")
|
||||||
|
def res_pending_events() -> str:
|
||||||
|
return json.dumps(db.list_pending_events(limit=30), ensure_ascii=False, indent=2)
|
||||||
|
|
||||||
|
# ---- Tools ----
|
||||||
|
@mcp.tool()
|
||||||
|
def list_devices() -> dict[str, Any]:
|
||||||
|
"""List all registered Android devices with online state, capabilities, and display summary."""
|
||||||
|
devices = db.list_devices()
|
||||||
|
return {"count": len(devices), "devices": devices}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_device_status(device_id: str) -> dict[str, Any]:
|
||||||
|
"""Get real-time hardware telemetry, DisplayProfile (viewport/DPI/safe-area/webview_version), and UI style hints for a device."""
|
||||||
|
dev = db.get_device(device_id)
|
||||||
|
if not dev:
|
||||||
|
return {"ok": False, "error": f"Device '{device_id}' not found."}
|
||||||
|
return {
|
||||||
|
"ok": True,
|
||||||
|
"device": dev,
|
||||||
|
"ui_framework_guide": UI_FRAMEWORK_GUIDE,
|
||||||
|
}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def push_feed_item(
|
||||||
|
device_id: str,
|
||||||
|
title: str,
|
||||||
|
body: str,
|
||||||
|
level: str = "info",
|
||||||
|
source: str = "ai",
|
||||||
|
sound: str = "ding",
|
||||||
|
html_snippet: str | None = None,
|
||||||
|
tags: list[str] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Push a passive live-feed item to the device (no user confirmation required)."""
|
||||||
|
item_id = f"feed_{uuid.uuid4().hex[:10]}"
|
||||||
|
payload = {
|
||||||
|
"item_id": item_id,
|
||||||
|
"title": title,
|
||||||
|
"body": body,
|
||||||
|
"level": level,
|
||||||
|
"source": source,
|
||||||
|
"sound": sound,
|
||||||
|
"html_snippet": html_snippet,
|
||||||
|
"tags": tags or [],
|
||||||
|
"ts": now_ms(),
|
||||||
|
}
|
||||||
|
sent = await bridge.send_frame(device_id, "feed.push", payload)
|
||||||
|
db.add_audit("feed", device_id, f"[{level}] {title}", payload)
|
||||||
|
return {"ok": sent, "item_id": item_id, "delivered": sent}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def trigger_alert(
|
||||||
|
device_id: str,
|
||||||
|
title: str,
|
||||||
|
message: str,
|
||||||
|
level: str = "warning",
|
||||||
|
presentation: str = "modal",
|
||||||
|
sound: str = "warning",
|
||||||
|
vibrate: bool = True,
|
||||||
|
wake_screen: bool = False,
|
||||||
|
tts_text: str | None = None,
|
||||||
|
details_code: str | None = None,
|
||||||
|
custom_html: str | None = None,
|
||||||
|
interaction: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Trigger a native alert overlay (toast | modal | fullscreen_alarm) with optional Preset-First interactive buttons."""
|
||||||
|
alert_id = f"alert_{uuid.uuid4().hex[:10]}"
|
||||||
|
if interaction and "interaction_id" not in interaction:
|
||||||
|
interaction = {**interaction, "interaction_id": f"int_{uuid.uuid4().hex[:10]}"}
|
||||||
|
payload = {
|
||||||
|
"alert_id": alert_id,
|
||||||
|
"title": title,
|
||||||
|
"message": message,
|
||||||
|
"level": level,
|
||||||
|
"presentation": presentation,
|
||||||
|
"sound": sound,
|
||||||
|
"vibrate": vibrate,
|
||||||
|
"wake_screen": wake_screen or (presentation == "fullscreen_alarm"),
|
||||||
|
"tts_text": tts_text,
|
||||||
|
"details_code": details_code,
|
||||||
|
"custom_html": custom_html,
|
||||||
|
"interaction": interaction,
|
||||||
|
}
|
||||||
|
sent = await bridge.send_frame(device_id, "alert.trigger", payload)
|
||||||
|
db.add_audit("alert", device_id, f"[{level}/{presentation}] {title}", payload)
|
||||||
|
return {
|
||||||
|
"ok": sent,
|
||||||
|
"alert_id": alert_id,
|
||||||
|
"interaction_id": (interaction or {}).get("interaction_id"),
|
||||||
|
"delivered": sent,
|
||||||
|
}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def dismiss_alert(device_id: str, alert_id: str | None = None) -> dict[str, Any]:
|
||||||
|
"""Dismiss an active alert (or all alerts if alert_id is omitted) on the device."""
|
||||||
|
sent = await bridge.send_frame(device_id, "alert.dismiss", {"alert_id": alert_id})
|
||||||
|
return {"ok": sent, "alert_id": alert_id}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def render_page(
|
||||||
|
device_id: str,
|
||||||
|
html: str,
|
||||||
|
mode: str = "full",
|
||||||
|
title: str = "",
|
||||||
|
data_context: dict[str, Any] | None = None,
|
||||||
|
wait_validation_sec: int = 15,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Render dynamic HTML/Vue layout on device with pre-render sandbox validation and end-side Repair AI self-healing."""
|
||||||
|
return await bridge.send_render_and_wait(
|
||||||
|
device_id=device_id,
|
||||||
|
html=html,
|
||||||
|
mode=mode,
|
||||||
|
title=title,
|
||||||
|
data_context=data_context,
|
||||||
|
wait_validation_sec=wait_validation_sec,
|
||||||
|
)
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def rollback_page(device_id: str, snapshot_id: str | None = None) -> dict[str, Any]:
|
||||||
|
"""Roll back the device WebView to a previous healthy snapshot, or pass snapshot_id='home' to restore built-in Home screen."""
|
||||||
|
if snapshot_id == "home":
|
||||||
|
sent = await bridge.send_frame(device_id, "render.home", {})
|
||||||
|
db.add_audit("rollback", device_id, "Restored built-in Home screen")
|
||||||
|
return {"ok": sent, "snapshot_id": "home"}
|
||||||
|
snap = db.get_snapshot(snapshot_id) if snapshot_id else db.get_previous_healthy_snapshot(device_id)
|
||||||
|
if not snap:
|
||||||
|
return {"ok": False, "error": "No healthy snapshot available for rollback."}
|
||||||
|
sent = await bridge.send_frame(
|
||||||
|
device_id,
|
||||||
|
"render.rollback",
|
||||||
|
{"snapshot_id": snap["snapshot_id"], "html": snap["html"], "title": snap.get("title", "")},
|
||||||
|
)
|
||||||
|
db.add_audit("rollback", device_id, f"Rolled back to {snap['snapshot_id']}")
|
||||||
|
return {"ok": sent, "snapshot_id": snap["snapshot_id"]}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def reply_clarification(
|
||||||
|
device_id: str,
|
||||||
|
task_id: str,
|
||||||
|
answers: dict[str, Any],
|
||||||
|
updated_data: dict[str, Any] | None = None,
|
||||||
|
updated_html: str | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Reply to a data clarification question raised by the device's end-side Repair AI."""
|
||||||
|
payload = {
|
||||||
|
"task_id": task_id,
|
||||||
|
"answers": answers,
|
||||||
|
"updated_data": updated_data or {},
|
||||||
|
"updated_html": updated_html,
|
||||||
|
}
|
||||||
|
sent = await bridge.send_frame(device_id, "clarification.answer", payload)
|
||||||
|
db.add_audit("clarification_answer", device_id, f"Upstream answered clarification for {task_id}", payload)
|
||||||
|
return {"ok": sent, "task_id": task_id}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def get_pending_events(device_id: str | None = None, limit: int = 20) -> dict[str, Any]:
|
||||||
|
"""Poll pending reverse events (user interaction replies & end-side AI data clarification questions)."""
|
||||||
|
events = db.list_pending_events(device_id=device_id, limit=limit)
|
||||||
|
return {"count": len(events), "events": events}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
def ack_events(event_ids: list[str]) -> dict[str, Any]:
|
||||||
|
"""Acknowledge reverse events after processing them."""
|
||||||
|
acked = db.ack_events(event_ids)
|
||||||
|
return {"ok": True, "acked_count": acked}
|
||||||
|
|
||||||
|
@mcp.tool()
|
||||||
|
async def lan_adb_action(
|
||||||
|
device_id: str,
|
||||||
|
action: str,
|
||||||
|
params: dict[str, Any] | None = None,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""Execute a LAN-ONLY developer debug / ADB action on an authorized device (tap, swipe, text, keyevent, screencap, launch_app, screen_wake, screen_sleep, status, dumpsys_summary)."""
|
||||||
|
if not mcp_request_is_lan.get():
|
||||||
|
return {
|
||||||
|
"ok": False,
|
||||||
|
"error": "Forbidden: lan_adb_action is strictly restricted to private LAN MCP callers.",
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
return await adb_controller.execute_action(device_id, action, params)
|
||||||
|
except Exception as exc:
|
||||||
|
detail = getattr(exc, "detail", str(exc))
|
||||||
|
return {"ok": False, "error": detail}
|
||||||
|
|
||||||
|
return mcp
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
from typing import Any, Literal
|
||||||
|
from pydantic import BaseModel, Field
|
||||||
|
|
||||||
|
|
||||||
|
class DisplayProfile(BaseModel):
|
||||||
|
device_type: Literal["phone", "tablet", "tv", "unknown"] = "phone"
|
||||||
|
orientation: Literal["portrait", "landscape"] = "portrait"
|
||||||
|
width_px: int = 1080
|
||||||
|
height_px: int = 2340
|
||||||
|
viewport_css_w: int = 392
|
||||||
|
viewport_css_h: int = 850
|
||||||
|
dpr: float = 2.75
|
||||||
|
safe_area_top_dp: int = 28
|
||||||
|
safe_area_bottom_dp: int = 16
|
||||||
|
font_scale: float = 1.0
|
||||||
|
webview_version: str = "unknown"
|
||||||
|
|
||||||
|
|
||||||
|
class DeviceTelemetry(BaseModel):
|
||||||
|
battery_pct: int | None = None
|
||||||
|
is_charging: bool | None = None
|
||||||
|
battery_temp_c: float | None = None
|
||||||
|
battery_current_ma: int | None = None
|
||||||
|
cpu_usage_pct: float | None = None
|
||||||
|
gpu_usage_pct: float | None = None
|
||||||
|
mem_used_mb: int | None = None
|
||||||
|
mem_total_mb: int | None = None
|
||||||
|
storage_used_mb: int | None = None
|
||||||
|
storage_total_mb: int | None = None
|
||||||
|
thermal_zones: dict[str, float] = Field(default_factory=dict)
|
||||||
|
wifi_rssi_dbm: int | None = None
|
||||||
|
screen_on: bool | None = None
|
||||||
|
extra: dict[str, Any] = Field(default_factory=dict)
|
||||||
|
|
||||||
|
|
||||||
|
class RepairAIConfig(BaseModel):
|
||||||
|
enabled: bool = False
|
||||||
|
base_url: str = "https://api.openai.com/v1"
|
||||||
|
api_key: str = ""
|
||||||
|
model: str = "gpt-4o-mini"
|
||||||
|
timeout_sec: int = 30
|
||||||
|
max_retries: int = 3
|
||||||
|
runtime_cooldown_sec: int = 30
|
||||||
|
|
||||||
|
|
||||||
|
class HubChatAIConfig(BaseModel):
|
||||||
|
base_url: str = "https://api.openai.com/v1"
|
||||||
|
api_key: str = ""
|
||||||
|
model: str = "gpt-4o-mini"
|
||||||
|
timeout_sec: int = 60
|
||||||
|
max_tool_steps: int = Field(default=30, ge=1, le=100)
|
||||||
|
system_prompt: str = (
|
||||||
|
"你是 PulseWall 中心桥控制助手,可以通过工具查询连接的 Android 手机/平板/机顶盒设备状态与屏幕参数,"
|
||||||
|
"推送动态信息、触发分层告警(含全屏红屏警报与预设交互按钮)、动态生成并渲染适配该设备分辨率与 WebView 版本的 HTML/Vue 页面,"
|
||||||
|
"以及查询用户的反向操作回复。渲染页面前务必先调用 get_device_status 获取目标设备的 viewport_css_w/h、device_type 和本地内置库清单。"
|
||||||
|
"App 本地已离线内置 Vue3、tailwind-lite、dayjs、PwIcons,以及可按需 `await window.PulseWall.loadLib([...])` 零延迟加载的 "
|
||||||
|
"plyr、hls、echarts(裁剪版)、konva、three、rough、lodash、zustand、anime,优先使用本地库避免外网 CDN 依赖,非必要不加载重库(three/echarts);"
|
||||||
|
"在 Android 机顶盒/平板大屏上尽量减少高频 60fps 全屏 Canvas 重绘与大面积 backdrop-filter 模糊,以保持低 CPU/低发热。"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
class HubConfig(BaseModel):
|
||||||
|
repair_ai: RepairAIConfig = Field(default_factory=RepairAIConfig)
|
||||||
|
hub_chat_ai: HubChatAIConfig = Field(default_factory=HubChatAIConfig)
|
||||||
|
telemetry_interval_sec: int = Field(default=3, ge=1, le=120)
|
||||||
|
theme: str = "dark-glass"
|
||||||
|
lan_debug_enabled: bool = False
|
||||||
|
auth_token: str = ""
|
||||||
|
|
||||||
|
|
||||||
|
class PresetOption(BaseModel):
|
||||||
|
id: str
|
||||||
|
label: str
|
||||||
|
style: Literal["primary", "secondary", "danger", "success"] = "primary"
|
||||||
|
|
||||||
|
|
||||||
|
class InteractionSpec(BaseModel):
|
||||||
|
interaction_id: str
|
||||||
|
mode: Literal["ack_required", "action_required"] = "ack_required"
|
||||||
|
presets: list[PresetOption] = Field(
|
||||||
|
default_factory=lambda: [PresetOption(id="ack", label="确认收到", style="primary")]
|
||||||
|
)
|
||||||
|
allow_custom_input: bool = True
|
||||||
|
custom_input_placeholder: str = "其他说明或指令..."
|
||||||
|
|
||||||
|
|
||||||
|
class AlertPayload(BaseModel):
|
||||||
|
alert_id: str
|
||||||
|
title: str
|
||||||
|
message: str
|
||||||
|
level: Literal["info", "notice", "warning", "error", "critical"] = "warning"
|
||||||
|
presentation: Literal["toast", "modal", "fullscreen_alarm"] = "modal"
|
||||||
|
sound: Literal["none", "ding", "warning", "siren", "tts"] = "warning"
|
||||||
|
vibrate: bool = True
|
||||||
|
wake_screen: bool = False
|
||||||
|
tts_text: str | None = None
|
||||||
|
details_code: str | None = None
|
||||||
|
custom_html: str | None = None
|
||||||
|
interaction: InteractionSpec | None = None
|
||||||
|
|
||||||
|
|
||||||
|
class FeedItemPayload(BaseModel):
|
||||||
|
item_id: str
|
||||||
|
title: str
|
||||||
|
body: str
|
||||||
|
level: Literal["info", "notice", "warning", "error", "critical"] = "info"
|
||||||
|
source: str = "ai"
|
||||||
|
sound: Literal["none", "ding", "warning"] = "ding"
|
||||||
|
html_snippet: str | None = None
|
||||||
|
tags: list[str] = Field(default_factory=list)
|
||||||
|
ts: int
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import asyncio
|
||||||
|
import contextlib
|
||||||
|
import os
|
||||||
|
import signal
|
||||||
|
from collections.abc import Generator
|
||||||
|
|
||||||
|
import uvicorn
|
||||||
|
|
||||||
|
from app.main import app
|
||||||
|
|
||||||
|
|
||||||
|
class GracefulHubServer(uvicorn.Server):
|
||||||
|
"""Triggers immediate cleanup of long-lived WS/MJPEG/SSE connections on first Ctrl+C without Python 3.13 tracebacks."""
|
||||||
|
|
||||||
|
def handle_exit(self, sig: int, frame) -> None: # type: ignore[override]
|
||||||
|
shutdown_ev = getattr(app.state, "shutdown_event", None)
|
||||||
|
adb_ctrl = getattr(app.state, "adb_controller", None)
|
||||||
|
bridge = getattr(app.state, "bridge", None)
|
||||||
|
if shutdown_ev is not None:
|
||||||
|
shutdown_ev.set()
|
||||||
|
if adb_ctrl is not None:
|
||||||
|
adb_ctrl.stop_all_streams()
|
||||||
|
try:
|
||||||
|
loop = asyncio.get_running_loop()
|
||||||
|
if bridge is not None:
|
||||||
|
loop.create_task(bridge.close_all())
|
||||||
|
except RuntimeError:
|
||||||
|
pass
|
||||||
|
super().handle_exit(sig, frame)
|
||||||
|
|
||||||
|
@contextlib.contextmanager
|
||||||
|
def capture_signals(self) -> Generator[None, None, None]:
|
||||||
|
# Override Uvicorn's capture_signals so it does NOT re-raise SIGINT after clean shutdown
|
||||||
|
# (which causes spurious CancelledError/KeyboardInterrupt tracebacks on Python 3.13 + uvloop).
|
||||||
|
original_handlers = {
|
||||||
|
sig: signal.signal(sig, self.handle_exit)
|
||||||
|
for sig in (signal.SIGINT, signal.SIGTERM)
|
||||||
|
}
|
||||||
|
try:
|
||||||
|
yield
|
||||||
|
finally:
|
||||||
|
for sig, handler in original_handlers.items():
|
||||||
|
signal.signal(sig, handler)
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
port = int(os.environ.get("PULSEWALL_PORT", "8765"))
|
||||||
|
config = uvicorn.Config(
|
||||||
|
app=app,
|
||||||
|
host="0.0.0.0",
|
||||||
|
port=port,
|
||||||
|
timeout_graceful_shutdown=2,
|
||||||
|
)
|
||||||
|
server = GracefulHubServer(config)
|
||||||
|
try:
|
||||||
|
server.run()
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,987 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sqlite3
|
||||||
|
import threading
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from app.models import HubConfig, RepairAIConfig
|
||||||
|
|
||||||
|
|
||||||
|
def now_ms() -> int:
|
||||||
|
return int(time.time() * 1000)
|
||||||
|
|
||||||
|
|
||||||
|
class PulseWallDB:
|
||||||
|
def __init__(self, db_path: str | Path = "pulsewall_hub.db") -> None:
|
||||||
|
self.db_path = Path(db_path)
|
||||||
|
self.db_path.parent.mkdir(parents=True, exist_ok=True)
|
||||||
|
self._lock = threading.RLock()
|
||||||
|
self._telemetry_writes = 0
|
||||||
|
self._init_schema()
|
||||||
|
|
||||||
|
def _connect(self) -> sqlite3.Connection:
|
||||||
|
conn = sqlite3.connect(str(self.db_path), check_same_thread=False)
|
||||||
|
conn.row_factory = sqlite3.Row
|
||||||
|
return conn
|
||||||
|
|
||||||
|
def _init_schema(self) -> None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.executescript(
|
||||||
|
"""
|
||||||
|
CREATE TABLE IF NOT EXISTS devices (
|
||||||
|
device_id TEXT PRIMARY KEY,
|
||||||
|
device_name TEXT NOT NULL,
|
||||||
|
model TEXT DEFAULT '',
|
||||||
|
android_sdk INTEGER DEFAULT 30,
|
||||||
|
android_release TEXT DEFAULT '11',
|
||||||
|
app_version TEXT DEFAULT '0.1.0',
|
||||||
|
capabilities_json TEXT DEFAULT '["basic"]',
|
||||||
|
display_profile_json TEXT DEFAULT '{}',
|
||||||
|
telemetry_json TEXT DEFAULT '{}',
|
||||||
|
online INTEGER DEFAULT 0,
|
||||||
|
lan_debug_allowed INTEGER DEFAULT 0,
|
||||||
|
adb_target TEXT DEFAULT '',
|
||||||
|
repair_ai_override_json TEXT DEFAULT '',
|
||||||
|
last_seen_ms INTEGER DEFAULT 0
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS hub_config (
|
||||||
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
||||||
|
config_json TEXT NOT NULL,
|
||||||
|
updated_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS snapshots (
|
||||||
|
snapshot_id TEXT PRIMARY KEY,
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
task_id TEXT NOT NULL,
|
||||||
|
title TEXT DEFAULT '',
|
||||||
|
mode TEXT DEFAULT 'full',
|
||||||
|
html TEXT NOT NULL,
|
||||||
|
data_context_json TEXT DEFAULT '{}',
|
||||||
|
status TEXT DEFAULT 'pending',
|
||||||
|
local_fix_summary TEXT DEFAULT '',
|
||||||
|
created_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS events (
|
||||||
|
event_id TEXT PRIMARY KEY,
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
event_type TEXT NOT NULL,
|
||||||
|
payload_json TEXT NOT NULL,
|
||||||
|
acked INTEGER DEFAULT 0,
|
||||||
|
created_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS audit_logs (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
category TEXT NOT NULL,
|
||||||
|
device_id TEXT DEFAULT '',
|
||||||
|
summary TEXT NOT NULL,
|
||||||
|
detail_json TEXT DEFAULT '{}',
|
||||||
|
created_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS webhooks (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
url TEXT NOT NULL,
|
||||||
|
secret TEXT DEFAULT '',
|
||||||
|
enabled INTEGER DEFAULT 1,
|
||||||
|
created_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_sessions (
|
||||||
|
session_id TEXT PRIMARY KEY,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
status TEXT NOT NULL DEFAULT 'idle',
|
||||||
|
active_run_id TEXT DEFAULT '',
|
||||||
|
created_at_ms INTEGER NOT NULL,
|
||||||
|
updated_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS chat_messages (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
session_id TEXT NOT NULL,
|
||||||
|
run_id TEXT DEFAULT '',
|
||||||
|
role TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL DEFAULT '',
|
||||||
|
tool_trace_json TEXT DEFAULT '[]',
|
||||||
|
status TEXT NOT NULL DEFAULT 'done',
|
||||||
|
created_at_ms INTEGER NOT NULL,
|
||||||
|
updated_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS prompt_groups (
|
||||||
|
group_id TEXT PRIMARY KEY,
|
||||||
|
name TEXT NOT NULL,
|
||||||
|
sort_order INTEGER DEFAULT 0,
|
||||||
|
created_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS quick_prompts (
|
||||||
|
prompt_id TEXT PRIMARY KEY,
|
||||||
|
group_id TEXT NOT NULL,
|
||||||
|
title TEXT NOT NULL,
|
||||||
|
content TEXT NOT NULL,
|
||||||
|
sort_order INTEGER DEFAULT 0,
|
||||||
|
created_at_ms INTEGER NOT NULL,
|
||||||
|
updated_at_ms INTEGER NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS device_telemetry_history (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
device_id TEXT NOT NULL,
|
||||||
|
ts_ms INTEGER NOT NULL,
|
||||||
|
cpu_usage_pct REAL,
|
||||||
|
gpu_usage_pct REAL,
|
||||||
|
mem_used_mb INTEGER,
|
||||||
|
mem_total_mb INTEGER,
|
||||||
|
storage_used_mb INTEGER,
|
||||||
|
storage_total_mb INTEGER,
|
||||||
|
battery_pct INTEGER,
|
||||||
|
battery_temp_c REAL,
|
||||||
|
max_thermal_c REAL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_telemetry_dev_ts
|
||||||
|
ON device_telemetry_history(device_id, ts_ms);
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
cur = conn.execute("SELECT config_json FROM hub_config WHERE id = 1")
|
||||||
|
if cur.fetchone() is None:
|
||||||
|
default_cfg = HubConfig().model_dump_json()
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO hub_config (id, config_json, updated_at_ms) VALUES (1, ?, ?)",
|
||||||
|
(default_cfg, now_ms()),
|
||||||
|
)
|
||||||
|
# Idempotent schema migration for existing DBs
|
||||||
|
cols = {r["name"] for r in conn.execute("PRAGMA table_info(devices)").fetchall()}
|
||||||
|
if "repair_ai_override_json" not in cols:
|
||||||
|
conn.execute("ALTER TABLE devices ADD COLUMN repair_ai_override_json TEXT DEFAULT ''")
|
||||||
|
if "ui_prefs_json" not in cols:
|
||||||
|
conn.execute("ALTER TABLE devices ADD COLUMN ui_prefs_json TEXT DEFAULT ''")
|
||||||
|
t_cols = {r["name"] for r in conn.execute("PRAGMA table_info(device_telemetry_history)").fetchall()}
|
||||||
|
if "gpu_usage_pct" not in t_cols:
|
||||||
|
conn.execute("ALTER TABLE device_telemetry_history ADD COLUMN gpu_usage_pct REAL")
|
||||||
|
|
||||||
|
# Recover any stale 'running' sessions left behind by an unclean process restart
|
||||||
|
ts = now_ms()
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE chat_sessions SET status = 'idle', active_run_id = '', updated_at_ms = ? WHERE status = 'running'",
|
||||||
|
(ts,),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE chat_messages
|
||||||
|
SET status = 'error',
|
||||||
|
role = 'error',
|
||||||
|
content = CASE WHEN content = '' THEN '中心桥服务重启,上次后台回复已中断。' ELSE content || '\n\n(中心桥重启导致中断)' END,
|
||||||
|
updated_at_ms = ?
|
||||||
|
WHERE status = 'running'
|
||||||
|
""",
|
||||||
|
(ts,),
|
||||||
|
)
|
||||||
|
|
||||||
|
# Seed default prompt groups & quick prompts only on first initialization
|
||||||
|
g_cnt = conn.execute("SELECT COUNT(1) AS c FROM prompt_groups").fetchone()["c"]
|
||||||
|
if g_cnt == 0:
|
||||||
|
self._seed_default_prompts_locked(conn, ts)
|
||||||
|
|
||||||
|
# Prune telemetry older than 7 days on startup
|
||||||
|
cutoff_7d = ts - 7 * 86400 * 1000
|
||||||
|
conn.execute("DELETE FROM device_telemetry_history WHERE ts_ms < ?", (cutoff_7d,))
|
||||||
|
|
||||||
|
# ---- Config ----
|
||||||
|
def get_config(self) -> HubConfig:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT config_json FROM hub_config WHERE id = 1").fetchone()
|
||||||
|
if not row:
|
||||||
|
return HubConfig()
|
||||||
|
return HubConfig.model_validate_json(row["config_json"])
|
||||||
|
|
||||||
|
def save_config(self, cfg: HubConfig) -> HubConfig:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE hub_config SET config_json = ?, updated_at_ms = ? WHERE id = 1",
|
||||||
|
(cfg.model_dump_json(), now_ms()),
|
||||||
|
)
|
||||||
|
self.add_audit("config", "", "Hub config updated", {"model": cfg.repair_ai.model, "lan_debug": cfg.lan_debug_enabled})
|
||||||
|
return cfg
|
||||||
|
|
||||||
|
# ---- Devices ----
|
||||||
|
def upsert_device_hello(self, device_id: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
existing = conn.execute(
|
||||||
|
"SELECT lan_debug_allowed, adb_target, telemetry_json FROM devices WHERE device_id = ?",
|
||||||
|
(device_id,),
|
||||||
|
).fetchone()
|
||||||
|
lan_allowed = existing["lan_debug_allowed"] if existing else 0
|
||||||
|
adb_target = existing["adb_target"] if existing else ""
|
||||||
|
telemetry_json = existing["telemetry_json"] if existing else "{}"
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO devices (
|
||||||
|
device_id, device_name, model, android_sdk, android_release,
|
||||||
|
app_version, capabilities_json, display_profile_json, telemetry_json,
|
||||||
|
online, lan_debug_allowed, adb_target, last_seen_ms
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 1, ?, ?, ?)
|
||||||
|
ON CONFLICT(device_id) DO UPDATE SET
|
||||||
|
device_name = excluded.device_name,
|
||||||
|
model = excluded.model,
|
||||||
|
android_sdk = excluded.android_sdk,
|
||||||
|
android_release = excluded.android_release,
|
||||||
|
app_version = excluded.app_version,
|
||||||
|
capabilities_json = excluded.capabilities_json,
|
||||||
|
display_profile_json = excluded.display_profile_json,
|
||||||
|
online = 1,
|
||||||
|
last_seen_ms = excluded.last_seen_ms
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
device_id,
|
||||||
|
payload.get("device_name") or device_id,
|
||||||
|
payload.get("model", ""),
|
||||||
|
int(payload.get("android_sdk", 30)),
|
||||||
|
str(payload.get("android_release", "11")),
|
||||||
|
str(payload.get("app_version", "0.1.0")),
|
||||||
|
json.dumps(payload.get("capabilities", ["basic"]), ensure_ascii=False),
|
||||||
|
json.dumps(payload.get("display_profile", {}), ensure_ascii=False),
|
||||||
|
telemetry_json,
|
||||||
|
lan_allowed,
|
||||||
|
adb_target,
|
||||||
|
ts,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return self.get_device(device_id) or {}
|
||||||
|
|
||||||
|
def update_device_telemetry(self, device_id: str, payload: dict[str, Any]) -> None:
|
||||||
|
ts = now_ms()
|
||||||
|
display_profile = payload.get("display_profile")
|
||||||
|
telemetry_clean = {k: v for k, v in payload.items() if k != "display_profile"}
|
||||||
|
|
||||||
|
thermals = telemetry_clean.get("thermal_zones") or {}
|
||||||
|
thermal_vals = [float(v) for v in thermals.values() if isinstance(v, (int, float))]
|
||||||
|
max_thermal = round(max(thermal_vals), 1) if thermal_vals else None
|
||||||
|
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if display_profile:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE devices
|
||||||
|
SET telemetry_json = ?, display_profile_json = ?, online = 1, last_seen_ms = ?
|
||||||
|
WHERE device_id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
json.dumps(telemetry_clean, ensure_ascii=False),
|
||||||
|
json.dumps(display_profile, ensure_ascii=False),
|
||||||
|
ts,
|
||||||
|
device_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE devices
|
||||||
|
SET telemetry_json = ?, online = 1, last_seen_ms = ?
|
||||||
|
WHERE device_id = ?
|
||||||
|
""",
|
||||||
|
(json.dumps(telemetry_clean, ensure_ascii=False), ts, device_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO device_telemetry_history (
|
||||||
|
device_id, ts_ms, cpu_usage_pct, gpu_usage_pct, mem_used_mb, mem_total_mb,
|
||||||
|
storage_used_mb, storage_total_mb, battery_pct, battery_temp_c, max_thermal_c
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
device_id,
|
||||||
|
ts,
|
||||||
|
telemetry_clean.get("cpu_usage_pct"),
|
||||||
|
telemetry_clean.get("gpu_usage_pct"),
|
||||||
|
telemetry_clean.get("mem_used_mb"),
|
||||||
|
telemetry_clean.get("mem_total_mb"),
|
||||||
|
telemetry_clean.get("storage_used_mb"),
|
||||||
|
telemetry_clean.get("storage_total_mb"),
|
||||||
|
telemetry_clean.get("battery_pct"),
|
||||||
|
telemetry_clean.get("battery_temp_c"),
|
||||||
|
max_thermal,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
self._telemetry_writes += 1
|
||||||
|
if self._telemetry_writes % 100 == 0:
|
||||||
|
cutoff_7d = ts - 7 * 86400 * 1000
|
||||||
|
conn.execute("DELETE FROM device_telemetry_history WHERE ts_ms < ?", (cutoff_7d,))
|
||||||
|
|
||||||
|
def query_telemetry_history(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
range_key: str = "1h",
|
||||||
|
max_points: int = 240,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
range_map = {
|
||||||
|
"15m": 15 * 60 * 1000,
|
||||||
|
"1h": 60 * 60 * 1000,
|
||||||
|
"6h": 6 * 3600 * 1000,
|
||||||
|
"24h": 24 * 3600 * 1000,
|
||||||
|
"7d": 7 * 86400 * 1000,
|
||||||
|
}
|
||||||
|
window_ms = range_map.get(range_key, 60 * 60 * 1000)
|
||||||
|
now = now_ms()
|
||||||
|
since_ms = now - window_ms
|
||||||
|
bucket_ms = max(3000, window_ms // max(1, max_points))
|
||||||
|
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if range_key == "15m":
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT ts_ms, cpu_usage_pct, gpu_usage_pct, mem_used_mb, mem_total_mb,
|
||||||
|
storage_used_mb, storage_total_mb, battery_pct, battery_temp_c, max_thermal_c
|
||||||
|
FROM device_telemetry_history
|
||||||
|
WHERE device_id = ? AND ts_ms >= ?
|
||||||
|
ORDER BY ts_ms ASC
|
||||||
|
LIMIT 400
|
||||||
|
""",
|
||||||
|
(device_id, since_ms),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT
|
||||||
|
CAST(AVG(ts_ms) AS INTEGER) AS ts_ms,
|
||||||
|
ROUND(AVG(cpu_usage_pct), 1) AS cpu_usage_pct,
|
||||||
|
ROUND(AVG(gpu_usage_pct), 1) AS gpu_usage_pct,
|
||||||
|
CAST(AVG(mem_used_mb) AS INTEGER) AS mem_used_mb,
|
||||||
|
MAX(mem_total_mb) AS mem_total_mb,
|
||||||
|
CAST(AVG(storage_used_mb) AS INTEGER) AS storage_used_mb,
|
||||||
|
MAX(storage_total_mb) AS storage_total_mb,
|
||||||
|
CAST(AVG(battery_pct) AS INTEGER) AS battery_pct,
|
||||||
|
ROUND(AVG(battery_temp_c), 1) AS battery_temp_c,
|
||||||
|
ROUND(MAX(max_thermal_c), 1) AS max_thermal_c
|
||||||
|
FROM device_telemetry_history
|
||||||
|
WHERE device_id = ? AND ts_ms >= ?
|
||||||
|
GROUP BY CAST(ts_ms / ? AS INTEGER)
|
||||||
|
ORDER BY ts_ms ASC
|
||||||
|
""",
|
||||||
|
(device_id, since_ms, bucket_ms),
|
||||||
|
).fetchall()
|
||||||
|
|
||||||
|
points = [dict(r) for r in rows]
|
||||||
|
return {
|
||||||
|
"device_id": device_id,
|
||||||
|
"range": range_key,
|
||||||
|
"retention_days": 7,
|
||||||
|
"point_count": len(points),
|
||||||
|
"points": points,
|
||||||
|
}
|
||||||
|
|
||||||
|
def set_device_online(self, device_id: str, online: bool) -> None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE devices SET online = ?, last_seen_ms = ? WHERE device_id = ?",
|
||||||
|
(1 if online else 0, now_ms(), device_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
def set_device_lan_debug(self, device_id: str, allowed: bool, adb_target: str | None = None) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if adb_target is not None:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE devices SET lan_debug_allowed = ?, adb_target = ? WHERE device_id = ?",
|
||||||
|
(1 if allowed else 0, adb_target.strip(), device_id),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE devices SET lan_debug_allowed = ? WHERE device_id = ?",
|
||||||
|
(1 if allowed else 0, device_id),
|
||||||
|
)
|
||||||
|
self.add_audit(
|
||||||
|
"lan_debug_policy",
|
||||||
|
device_id,
|
||||||
|
f"Updated LAN debug authorization: allowed={allowed}",
|
||||||
|
{"allowed": allowed, "adb_target": adb_target},
|
||||||
|
)
|
||||||
|
return self.get_device(device_id)
|
||||||
|
|
||||||
|
def set_device_repair_ai(self, device_id: str, override: RepairAIConfig | None) -> dict[str, Any] | None:
|
||||||
|
raw = override.model_dump_json() if override is not None else ""
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE devices SET repair_ai_override_json = ? WHERE device_id = ?",
|
||||||
|
(raw, device_id),
|
||||||
|
)
|
||||||
|
summary = (
|
||||||
|
f"Updated device-specific Repair AI: {override.model} (enabled={override.enabled})"
|
||||||
|
if override is not None
|
||||||
|
else "Reset device Repair AI to inherit global default"
|
||||||
|
)
|
||||||
|
self.add_audit("device_ai_config", device_id, summary)
|
||||||
|
return self.get_device(device_id)
|
||||||
|
|
||||||
|
def get_effective_repair_ai(self, device_id: str) -> RepairAIConfig:
|
||||||
|
dev = self.get_device(device_id)
|
||||||
|
if dev and dev.get("repair_ai_override"):
|
||||||
|
return RepairAIConfig.model_validate(dev["repair_ai_override"])
|
||||||
|
return self.get_config().repair_ai
|
||||||
|
|
||||||
|
DEFAULT_UI_PREFS: dict[str, Any] = {"screen_mirror_enabled": True}
|
||||||
|
|
||||||
|
def set_device_ui_prefs(self, device_id: str, prefs: dict[str, Any]) -> dict[str, Any] | None:
|
||||||
|
dev = self.get_device(device_id)
|
||||||
|
if not dev:
|
||||||
|
return None
|
||||||
|
merged = {**self.DEFAULT_UI_PREFS, **(dev.get("ui_prefs") or {}), **prefs}
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE devices SET ui_prefs_json = ? WHERE device_id = ?",
|
||||||
|
(json.dumps(merged, ensure_ascii=False), device_id),
|
||||||
|
)
|
||||||
|
self.add_audit("device_ui_prefs", device_id, f"Updated admin UI prefs: {merged}")
|
||||||
|
return self.get_device(device_id)
|
||||||
|
|
||||||
|
def _row_to_device(self, row: sqlite3.Row) -> dict[str, Any]:
|
||||||
|
caps = json.loads(row["capabilities_json"] or '["basic"]')
|
||||||
|
if row["lan_debug_allowed"] and row["adb_target"] and "adb_lan" not in caps:
|
||||||
|
caps.append("adb_lan")
|
||||||
|
override_raw = row["repair_ai_override_json"] if "repair_ai_override_json" in row.keys() else ""
|
||||||
|
override_obj = json.loads(override_raw) if override_raw else None
|
||||||
|
prefs_raw = row["ui_prefs_json"] if "ui_prefs_json" in row.keys() else ""
|
||||||
|
try:
|
||||||
|
prefs_obj = {**self.DEFAULT_UI_PREFS, **(json.loads(prefs_raw) if prefs_raw else {})}
|
||||||
|
except Exception:
|
||||||
|
prefs_obj = dict(self.DEFAULT_UI_PREFS)
|
||||||
|
return {
|
||||||
|
"device_id": row["device_id"],
|
||||||
|
"device_name": row["device_name"],
|
||||||
|
"model": row["model"],
|
||||||
|
"android_sdk": row["android_sdk"],
|
||||||
|
"android_release": row["android_release"],
|
||||||
|
"app_version": row["app_version"],
|
||||||
|
"capabilities": caps,
|
||||||
|
"display_profile": json.loads(row["display_profile_json"] or "{}"),
|
||||||
|
"telemetry": json.loads(row["telemetry_json"] or "{}"),
|
||||||
|
"online": bool(row["online"]),
|
||||||
|
"lan_debug_allowed": bool(row["lan_debug_allowed"]),
|
||||||
|
"adb_target": row["adb_target"] or "",
|
||||||
|
"repair_ai_override": override_obj,
|
||||||
|
"ui_prefs": prefs_obj,
|
||||||
|
"last_seen_ms": row["last_seen_ms"],
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_devices(self) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM devices ORDER BY online DESC, last_seen_ms DESC").fetchall()
|
||||||
|
return [self._row_to_device(r) for r in rows]
|
||||||
|
|
||||||
|
def get_device(self, device_id: str) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM devices WHERE device_id = ?", (device_id,)).fetchone()
|
||||||
|
return self._row_to_device(row) if row else None
|
||||||
|
|
||||||
|
# ---- Snapshots ----
|
||||||
|
def create_snapshot(
|
||||||
|
self,
|
||||||
|
device_id: str,
|
||||||
|
task_id: str,
|
||||||
|
html: str,
|
||||||
|
mode: str = "full",
|
||||||
|
title: str = "",
|
||||||
|
data_context: dict[str, Any] | None = None,
|
||||||
|
status: str = "pending",
|
||||||
|
) -> str:
|
||||||
|
snapshot_id = f"snap_{uuid.uuid4().hex[:10]}"
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO snapshots (
|
||||||
|
snapshot_id, device_id, task_id, title, mode, html,
|
||||||
|
data_context_json, status, created_at_ms
|
||||||
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
snapshot_id,
|
||||||
|
device_id,
|
||||||
|
task_id,
|
||||||
|
title or "",
|
||||||
|
mode,
|
||||||
|
html,
|
||||||
|
json.dumps(data_context or {}, ensure_ascii=False),
|
||||||
|
status,
|
||||||
|
now_ms(),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
return snapshot_id
|
||||||
|
|
||||||
|
def update_snapshot_result(
|
||||||
|
self,
|
||||||
|
snapshot_id: str,
|
||||||
|
status: str,
|
||||||
|
final_html: str | None = None,
|
||||||
|
local_fix_summary: str = "",
|
||||||
|
) -> None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if final_html is not None:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE snapshots SET status = ?, html = ?, local_fix_summary = ? WHERE snapshot_id = ?",
|
||||||
|
(status, final_html, local_fix_summary, snapshot_id),
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE snapshots SET status = ?, local_fix_summary = ? WHERE snapshot_id = ?",
|
||||||
|
(status, local_fix_summary, snapshot_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
def get_snapshot(self, snapshot_id: str) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM snapshots WHERE snapshot_id = ?", (snapshot_id,)).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def get_snapshot_by_task(self, task_id: str) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"SELECT * FROM snapshots WHERE task_id = ? ORDER BY created_at_ms DESC LIMIT 1",
|
||||||
|
(task_id,),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def list_snapshots(self, device_id: str | None = None, limit: int = 20) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if device_id:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM snapshots WHERE device_id = ? ORDER BY created_at_ms DESC LIMIT ?",
|
||||||
|
(device_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM snapshots ORDER BY created_at_ms DESC LIMIT ?",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get_previous_healthy_snapshot(self, device_id: str, exclude_snapshot_id: str | None = None) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if exclude_snapshot_id:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT * FROM snapshots
|
||||||
|
WHERE device_id = ? AND status IN ('rendered', 'rendered_after_local_fix')
|
||||||
|
AND snapshot_id != ?
|
||||||
|
ORDER BY created_at_ms DESC LIMIT 1
|
||||||
|
""",
|
||||||
|
(device_id, exclude_snapshot_id),
|
||||||
|
).fetchone()
|
||||||
|
else:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT * FROM snapshots
|
||||||
|
WHERE device_id = ? AND status IN ('rendered', 'rendered_after_local_fix')
|
||||||
|
ORDER BY created_at_ms DESC LIMIT 1
|
||||||
|
""",
|
||||||
|
(device_id,),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
# ---- Events ----
|
||||||
|
def create_event(self, device_id: str, event_type: str, payload: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
event_id = f"evt_{uuid.uuid4().hex[:12]}"
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO events (event_id, device_id, event_type, payload_json, acked, created_at_ms) VALUES (?, ?, ?, ?, 0, ?)",
|
||||||
|
(event_id, device_id, event_type, json.dumps(payload, ensure_ascii=False), ts),
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"event_id": event_id,
|
||||||
|
"device_id": device_id,
|
||||||
|
"event_type": event_type,
|
||||||
|
"payload": payload,
|
||||||
|
"acked": False,
|
||||||
|
"created_at_ms": ts,
|
||||||
|
}
|
||||||
|
|
||||||
|
def list_pending_events(self, device_id: str | None = None, limit: int = 30) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if device_id:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM events WHERE acked = 0 AND device_id = ? ORDER BY created_at_ms ASC LIMIT ?",
|
||||||
|
(device_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM events WHERE acked = 0 ORDER BY created_at_ms ASC LIMIT ?",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"event_id": r["event_id"],
|
||||||
|
"device_id": r["device_id"],
|
||||||
|
"event_type": r["event_type"],
|
||||||
|
"payload": json.loads(r["payload_json"]),
|
||||||
|
"acked": bool(r["acked"]),
|
||||||
|
"created_at_ms": r["created_at_ms"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
def ack_events(self, event_ids: list[str]) -> int:
|
||||||
|
if not event_ids:
|
||||||
|
return 0
|
||||||
|
placeholders = ",".join("?" for _ in event_ids)
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
cur = conn.execute(f"UPDATE events SET acked = 1 WHERE event_id IN ({placeholders})", event_ids)
|
||||||
|
return cur.rowcount
|
||||||
|
|
||||||
|
# ---- Audit Logs ----
|
||||||
|
def add_audit(self, category: str, device_id: str, summary: str, detail: dict[str, Any] | None = None) -> None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO audit_logs (category, device_id, summary, detail_json, created_at_ms) VALUES (?, ?, ?, ?, ?)",
|
||||||
|
(category, device_id, summary, json.dumps(detail or {}, ensure_ascii=False), now_ms()),
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_audits(self, limit: int = 50, device_id: str | None = None) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
if device_id:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM audit_logs WHERE device_id = ? ORDER BY id DESC LIMIT ?",
|
||||||
|
(device_id, limit),
|
||||||
|
).fetchall()
|
||||||
|
else:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM audit_logs ORDER BY id DESC LIMIT ?",
|
||||||
|
(limit,),
|
||||||
|
).fetchall()
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
"id": r["id"],
|
||||||
|
"category": r["category"],
|
||||||
|
"device_id": r["device_id"],
|
||||||
|
"summary": r["summary"],
|
||||||
|
"detail": json.loads(r["detail_json"] or "{}"),
|
||||||
|
"created_at_ms": r["created_at_ms"],
|
||||||
|
}
|
||||||
|
for r in rows
|
||||||
|
]
|
||||||
|
|
||||||
|
# ---- Webhooks ----
|
||||||
|
def add_webhook(self, url: str, secret: str = "") -> dict[str, Any]:
|
||||||
|
wid = f"wh_{uuid.uuid4().hex[:10]}"
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO webhooks (id, url, secret, enabled, created_at_ms) VALUES (?, ?, ?, 1, ?)",
|
||||||
|
(wid, url, secret, ts),
|
||||||
|
)
|
||||||
|
return {"id": wid, "url": url, "enabled": True, "created_at_ms": ts}
|
||||||
|
|
||||||
|
def list_webhooks(self) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
rows = conn.execute("SELECT * FROM webhooks WHERE enabled = 1").fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def delete_webhook(self, webhook_id: str) -> bool:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
cur = conn.execute("DELETE FROM webhooks WHERE id = ?", (webhook_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
# ---- Chat Sessions & Persistent Messages ----
|
||||||
|
def create_chat_session(self, title: str = "新会话") -> dict[str, Any]:
|
||||||
|
sid = f"sess_{uuid.uuid4().hex[:10]}"
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO chat_sessions (session_id, title, status, active_run_id, created_at_ms, updated_at_ms) VALUES (?, ?, 'idle', '', ?, ?)",
|
||||||
|
(sid, title.strip() or "新会话", ts, ts),
|
||||||
|
)
|
||||||
|
return self.get_chat_session(sid) or {}
|
||||||
|
|
||||||
|
def list_chat_sessions(self) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT s.*,
|
||||||
|
(SELECT COUNT(1) FROM chat_messages m WHERE m.session_id = s.session_id) AS message_count
|
||||||
|
FROM chat_sessions s
|
||||||
|
ORDER BY s.updated_at_ms DESC
|
||||||
|
"""
|
||||||
|
).fetchall()
|
||||||
|
return [dict(r) for r in rows]
|
||||||
|
|
||||||
|
def get_chat_session(self, session_id: str) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute(
|
||||||
|
"""
|
||||||
|
SELECT s.*,
|
||||||
|
(SELECT COUNT(1) FROM chat_messages m WHERE m.session_id = s.session_id) AS message_count
|
||||||
|
FROM chat_sessions s
|
||||||
|
WHERE s.session_id = ?
|
||||||
|
""",
|
||||||
|
(session_id,),
|
||||||
|
).fetchone()
|
||||||
|
return dict(row) if row else None
|
||||||
|
|
||||||
|
def rename_chat_session(self, session_id: str, title: str) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE chat_sessions SET title = ?, updated_at_ms = ? WHERE session_id = ?",
|
||||||
|
(title.strip() or "未命名会话", now_ms(), session_id),
|
||||||
|
)
|
||||||
|
return self.get_chat_session(session_id)
|
||||||
|
|
||||||
|
def set_chat_session_status(self, session_id: str, status: str, active_run_id: str = "") -> None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE chat_sessions SET status = ?, active_run_id = ?, updated_at_ms = ? WHERE session_id = ?",
|
||||||
|
(status, active_run_id, now_ms(), session_id),
|
||||||
|
)
|
||||||
|
|
||||||
|
def delete_chat_session(self, session_id: str) -> bool:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute("DELETE FROM chat_messages WHERE session_id = ?", (session_id,))
|
||||||
|
cur = conn.execute("DELETE FROM chat_sessions WHERE session_id = ?", (session_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
def add_chat_message(
|
||||||
|
self,
|
||||||
|
session_id: str,
|
||||||
|
role: str,
|
||||||
|
content: str,
|
||||||
|
tool_trace: list[dict[str, Any]] | None = None,
|
||||||
|
status: str = "done",
|
||||||
|
run_id: str = "",
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
cur = conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO chat_messages (session_id, run_id, role, content, tool_trace_json, status, created_at_ms, updated_at_ms)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
session_id,
|
||||||
|
run_id,
|
||||||
|
role,
|
||||||
|
content,
|
||||||
|
json.dumps(tool_trace or [], ensure_ascii=False),
|
||||||
|
status,
|
||||||
|
ts,
|
||||||
|
ts,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
msg_id = cur.lastrowid
|
||||||
|
conn.execute("UPDATE chat_sessions SET updated_at_ms = ? WHERE session_id = ?", (ts, session_id))
|
||||||
|
row = conn.execute("SELECT * FROM chat_messages WHERE id = ?", (msg_id,)).fetchone()
|
||||||
|
return self._row_to_chat_msg(row)
|
||||||
|
|
||||||
|
def update_chat_message(
|
||||||
|
self,
|
||||||
|
message_id: int,
|
||||||
|
*,
|
||||||
|
role: str | None = None,
|
||||||
|
content: str | None = None,
|
||||||
|
tool_trace: list[dict[str, Any]] | None = None,
|
||||||
|
status: str | None = None,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM chat_messages WHERE id = ?", (message_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
new_role = role if role is not None else row["role"]
|
||||||
|
new_content = content if content is not None else row["content"]
|
||||||
|
new_trace = json.dumps(tool_trace, ensure_ascii=False) if tool_trace is not None else row["tool_trace_json"]
|
||||||
|
new_status = status if status is not None else row["status"]
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE chat_messages
|
||||||
|
SET role = ?, content = ?, tool_trace_json = ?, status = ?, updated_at_ms = ?
|
||||||
|
WHERE id = ?
|
||||||
|
""",
|
||||||
|
(new_role, new_content, new_trace, new_status, ts, message_id),
|
||||||
|
)
|
||||||
|
conn.execute("UPDATE chat_sessions SET updated_at_ms = ? WHERE session_id = ?", (ts, row["session_id"]))
|
||||||
|
updated = conn.execute("SELECT * FROM chat_messages WHERE id = ?", (message_id,)).fetchone()
|
||||||
|
return self._row_to_chat_msg(updated)
|
||||||
|
|
||||||
|
def list_chat_messages(self, session_id: str) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
rows = conn.execute(
|
||||||
|
"SELECT * FROM chat_messages WHERE session_id = ? ORDER BY id ASC",
|
||||||
|
(session_id,),
|
||||||
|
).fetchall()
|
||||||
|
return [self._row_to_chat_msg(r) for r in rows]
|
||||||
|
|
||||||
|
def _row_to_chat_msg(self, row: sqlite3.Row) -> dict[str, Any]:
|
||||||
|
return {
|
||||||
|
"id": row["id"],
|
||||||
|
"session_id": row["session_id"],
|
||||||
|
"run_id": row["run_id"],
|
||||||
|
"role": row["role"],
|
||||||
|
"content": row["content"],
|
||||||
|
"tool_trace": json.loads(row["tool_trace_json"] or "[]"),
|
||||||
|
"status": row["status"],
|
||||||
|
"created_at_ms": row["created_at_ms"],
|
||||||
|
"updated_at_ms": row["updated_at_ms"],
|
||||||
|
}
|
||||||
|
|
||||||
|
# ---- Quick Prompt Groups & Prompts ----
|
||||||
|
def _seed_default_prompts_locked(self, conn: sqlite3.Connection, ts: int) -> None:
|
||||||
|
g1 = "grp_inspect"
|
||||||
|
g2 = "grp_render_alarm"
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO prompt_groups (group_id, name, sort_order, created_at_ms) VALUES (?, ?, ?, ?)",
|
||||||
|
(g1, "设备巡检与交互", 10, ts),
|
||||||
|
)
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO prompt_groups (group_id, name, sort_order, created_at_ms) VALUES (?, ?, ?, ?)",
|
||||||
|
(g2, "动态页面与告警演练", 20, ts),
|
||||||
|
)
|
||||||
|
seeds = [
|
||||||
|
(
|
||||||
|
"prm_list_dev",
|
||||||
|
g1,
|
||||||
|
"巡检全部在线设备",
|
||||||
|
"请列出当前所有设备,并汇报每台设备的型号、屏幕视口分辨率、WebView 版本、实时温度和电量状态。",
|
||||||
|
10,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"prm_pending_evts",
|
||||||
|
g1,
|
||||||
|
"查看用户按钮回复",
|
||||||
|
"查询待处理的反向事件,看看用户在设备上刚刚点击了哪个按钮,或有没有端侧修复 AI 的数据追问。",
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"prm_tv_dash",
|
||||||
|
g2,
|
||||||
|
"自适应画大屏仪表盘",
|
||||||
|
"先查询当前在线设备的分辨率和形态(如 tv/phone/tablet),再为它设计并渲染一个高对比度暗色实时状态大屏,包含一个点击可回传中心桥的按钮。",
|
||||||
|
10,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"prm_red_alarm",
|
||||||
|
g2,
|
||||||
|
"演练全屏红色警报",
|
||||||
|
"模拟核心数据库主节点超时宕机,给当前在线设备触发一条全屏红色紧急警报,提供「确认收到」「自动切换备库」「静音 30 分钟」三个预设选项。",
|
||||||
|
20,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
"prm_restore_home",
|
||||||
|
g2,
|
||||||
|
"恢复设备默认首页",
|
||||||
|
"请把当前在线设备恢复到内置默认首页。",
|
||||||
|
30,
|
||||||
|
),
|
||||||
|
]
|
||||||
|
for pid, gid, title, content, order in seeds:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO quick_prompts (prompt_id, group_id, title, content, sort_order, created_at_ms, updated_at_ms)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(pid, gid, title, content, order, ts, ts),
|
||||||
|
)
|
||||||
|
|
||||||
|
def list_prompt_groups_with_items(self) -> list[dict[str, Any]]:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
groups = [
|
||||||
|
dict(r)
|
||||||
|
for r in conn.execute("SELECT * FROM prompt_groups ORDER BY sort_order ASC, created_at_ms ASC").fetchall()
|
||||||
|
]
|
||||||
|
prompts = [
|
||||||
|
dict(r)
|
||||||
|
for r in conn.execute("SELECT * FROM quick_prompts ORDER BY sort_order ASC, created_at_ms ASC").fetchall()
|
||||||
|
]
|
||||||
|
by_group: dict[str, list[dict[str, Any]]] = {}
|
||||||
|
for p in prompts:
|
||||||
|
by_group.setdefault(p["group_id"], []).append(p)
|
||||||
|
for g in groups:
|
||||||
|
g["prompts"] = by_group.get(g["group_id"], [])
|
||||||
|
return groups
|
||||||
|
|
||||||
|
def create_prompt_group(self, name: str, sort_order: int = 0) -> dict[str, Any]:
|
||||||
|
gid = f"grp_{uuid.uuid4().hex[:8]}"
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"INSERT INTO prompt_groups (group_id, name, sort_order, created_at_ms) VALUES (?, ?, ?, ?)",
|
||||||
|
(gid, name.strip() or "新分组", sort_order, ts),
|
||||||
|
)
|
||||||
|
row = conn.execute("SELECT * FROM prompt_groups WHERE group_id = ?", (gid,)).fetchone()
|
||||||
|
res = dict(row)
|
||||||
|
res["prompts"] = []
|
||||||
|
return res
|
||||||
|
|
||||||
|
def update_prompt_group(self, group_id: str, name: str, sort_order: int | None = None) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM prompt_groups WHERE group_id = ?", (group_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
new_order = sort_order if sort_order is not None else row["sort_order"]
|
||||||
|
conn.execute(
|
||||||
|
"UPDATE prompt_groups SET name = ?, sort_order = ? WHERE group_id = ?",
|
||||||
|
(name.strip() or row["name"], new_order, group_id),
|
||||||
|
)
|
||||||
|
updated = conn.execute("SELECT * FROM prompt_groups WHERE group_id = ?", (group_id,)).fetchone()
|
||||||
|
return dict(updated)
|
||||||
|
|
||||||
|
def delete_prompt_group(self, group_id: str) -> bool:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute("DELETE FROM quick_prompts WHERE group_id = ?", (group_id,))
|
||||||
|
cur = conn.execute("DELETE FROM prompt_groups WHERE group_id = ?", (group_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
|
|
||||||
|
def create_quick_prompt(self, group_id: str, title: str, content: str, sort_order: int = 0) -> dict[str, Any]:
|
||||||
|
pid = f"prm_{uuid.uuid4().hex[:8]}"
|
||||||
|
ts = now_ms()
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
INSERT INTO quick_prompts (prompt_id, group_id, title, content, sort_order, created_at_ms, updated_at_ms)
|
||||||
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
|
""",
|
||||||
|
(pid, group_id, title.strip() or "未命名指令", content.strip(), sort_order, ts, ts),
|
||||||
|
)
|
||||||
|
row = conn.execute("SELECT * FROM quick_prompts WHERE prompt_id = ?", (pid,)).fetchone()
|
||||||
|
return dict(row)
|
||||||
|
|
||||||
|
def update_quick_prompt(
|
||||||
|
self,
|
||||||
|
prompt_id: str,
|
||||||
|
*,
|
||||||
|
group_id: str | None = None,
|
||||||
|
title: str | None = None,
|
||||||
|
content: str | None = None,
|
||||||
|
sort_order: int | None = None,
|
||||||
|
) -> dict[str, Any] | None:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
row = conn.execute("SELECT * FROM quick_prompts WHERE prompt_id = ?", (prompt_id,)).fetchone()
|
||||||
|
if not row:
|
||||||
|
return None
|
||||||
|
conn.execute(
|
||||||
|
"""
|
||||||
|
UPDATE quick_prompts
|
||||||
|
SET group_id = ?, title = ?, content = ?, sort_order = ?, updated_at_ms = ?
|
||||||
|
WHERE prompt_id = ?
|
||||||
|
""",
|
||||||
|
(
|
||||||
|
group_id if group_id is not None else row["group_id"],
|
||||||
|
title.strip() if title is not None else row["title"],
|
||||||
|
content.strip() if content is not None else row["content"],
|
||||||
|
sort_order if sort_order is not None else row["sort_order"],
|
||||||
|
now_ms(),
|
||||||
|
prompt_id,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
updated = conn.execute("SELECT * FROM quick_prompts WHERE prompt_id = ?", (prompt_id,)).fetchone()
|
||||||
|
return dict(updated)
|
||||||
|
|
||||||
|
def delete_quick_prompt(self, prompt_id: str) -> bool:
|
||||||
|
with self._lock, self._connect() as conn:
|
||||||
|
cur = conn.execute("DELETE FROM quick_prompts WHERE prompt_id = ?", (prompt_id,))
|
||||||
|
return cur.rowcount > 0
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
[project]
|
||||||
|
name = "pulsewall-hub"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "PulseWall Central Bridge: Generic MCP Server, Android WebSocket Gateway, Config Center & LAN-only ADB Debug API"
|
||||||
|
requires-python = ">=3.11"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115.0",
|
||||||
|
"uvicorn[standard]>=0.32.0",
|
||||||
|
"mcp>=1.8.0",
|
||||||
|
"pydantic>=2.9.0",
|
||||||
|
"httpx>=0.27.0",
|
||||||
|
"websockets>=13.0",
|
||||||
|
"av>=14.0.0",
|
||||||
|
"pillow>=10.0.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.3.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=69.0"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
where = ["."]
|
||||||
|
include = ["app*"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
pythonpath = ["."]
|
||||||
|
|
||||||
Executable
+9
@@ -0,0 +1,9 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
|
||||||
|
export PATH="$ROOT_DIR/.toolchain/android-sdk/platform-tools:$PATH"
|
||||||
|
if [ -f "$ROOT_DIR/.toolchain/home/.android/adbkey" ]; then
|
||||||
|
export HOME="$ROOT_DIR/.toolchain/home"
|
||||||
|
fi
|
||||||
|
cd "$(dirname "$0")"
|
||||||
|
exec .venv/bin/python -m app.runner
|
||||||
@@ -0,0 +1,601 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
import time
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
|
||||||
|
def test_device_ws_config_interaction_and_lan_guard(tmp_path: Path) -> None:
|
||||||
|
app = create_app(str(tmp_path / "test.db"))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
resp = client.get("/health")
|
||||||
|
assert resp.status_code == 200
|
||||||
|
assert resp.json()["status"] == "ok"
|
||||||
|
|
||||||
|
with client.websocket_connect("/ws/device/android11-test") as ws:
|
||||||
|
cfg_frame = json.loads(ws.receive_text())
|
||||||
|
assert cfg_frame["type"] == "config.push"
|
||||||
|
assert "repair_ai" in cfg_frame["payload"]
|
||||||
|
|
||||||
|
ws.send_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "device.hello",
|
||||||
|
"payload": {
|
||||||
|
"device_id": "android11-test",
|
||||||
|
"device_name": "客厅 Android 11",
|
||||||
|
"model": "Mi 10",
|
||||||
|
"android_sdk": 30,
|
||||||
|
"android_release": "11",
|
||||||
|
"capabilities": ["basic", "root"],
|
||||||
|
"display_profile": {
|
||||||
|
"device_type": "phone",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"viewport_css_w": 392,
|
||||||
|
"viewport_css_h": 850,
|
||||||
|
"dpr": 2.75,
|
||||||
|
"webview_version": "114.0.5735.196",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
cfg_frame2 = json.loads(ws.receive_text())
|
||||||
|
assert cfg_frame2["type"] == "config.push"
|
||||||
|
|
||||||
|
devs = client.get("/api/admin/devices").json()["devices"]
|
||||||
|
assert len(devs) == 1
|
||||||
|
assert devs[0]["online"] is True
|
||||||
|
assert devs[0]["display_profile"]["viewport_css_w"] == 392
|
||||||
|
|
||||||
|
ws.send_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "interaction.reply",
|
||||||
|
"payload": {
|
||||||
|
"interaction_id": "int_123",
|
||||||
|
"selected_preset_id": "ack",
|
||||||
|
"selected_label": "确认收到",
|
||||||
|
"custom_text": None,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
time.sleep(0.05)
|
||||||
|
evts = client.get("/api/admin/events").json()["events"]
|
||||||
|
assert len(evts) == 1
|
||||||
|
assert evts[0]["event_type"] == "user_interaction_reply"
|
||||||
|
assert evts[0]["payload"]["selected_preset_id"] == "ack"
|
||||||
|
|
||||||
|
# LAN-only ADB guard MUST reject public forwarded IP
|
||||||
|
r_pub = client.post(
|
||||||
|
"/api/lan-debug/android11-test/action",
|
||||||
|
json={"action": "status"},
|
||||||
|
headers={"X-Forwarded-For": "8.8.8.8"},
|
||||||
|
)
|
||||||
|
assert r_pub.status_code == 403
|
||||||
|
|
||||||
|
# LAN request blocked until global switch is turned on
|
||||||
|
r_disabled = client.post("/api/lan-debug/android11-test/action", json={"action": "status"})
|
||||||
|
assert r_disabled.status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_mcp_streamable_http_tools_list(tmp_path: Path) -> None:
|
||||||
|
app = create_app(str(tmp_path / "mcp_test.db"))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
headers = {
|
||||||
|
"Accept": "application/json, text/event-stream",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
}
|
||||||
|
init_req = {
|
||||||
|
"jsonrpc": "2.0",
|
||||||
|
"id": 1,
|
||||||
|
"method": "initialize",
|
||||||
|
"params": {
|
||||||
|
"protocolVersion": "2025-03-26",
|
||||||
|
"capabilities": {},
|
||||||
|
"clientInfo": {"name": "pytest-client", "version": "1.0"},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
r1 = client.post("/mcp/", json=init_req, headers=headers)
|
||||||
|
assert r1.status_code == 200
|
||||||
|
body1 = r1.json()
|
||||||
|
assert body1["result"]["serverInfo"]["name"] == "PulseWall Hub"
|
||||||
|
|
||||||
|
tools_req = {"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}
|
||||||
|
r2 = client.post("/mcp/", json=tools_req, headers=headers)
|
||||||
|
assert r2.status_code == 200
|
||||||
|
tool_names = {t["name"] for t in r2.json()["result"]["tools"]}
|
||||||
|
assert {
|
||||||
|
"list_devices",
|
||||||
|
"get_device_status",
|
||||||
|
"push_feed_item",
|
||||||
|
"trigger_alert",
|
||||||
|
"render_page",
|
||||||
|
"reply_clarification",
|
||||||
|
"get_pending_events",
|
||||||
|
"lan_adb_action",
|
||||||
|
}.issubset(tool_names)
|
||||||
|
|
||||||
|
|
||||||
|
def test_render_clarification_bidirectional_flow(tmp_path: Path) -> None:
|
||||||
|
import threading
|
||||||
|
|
||||||
|
app = create_app(str(tmp_path / "clarify.db"))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
with client.websocket_connect("/ws/device/tablet-01") as ws:
|
||||||
|
# Consume initial config.push
|
||||||
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
||||||
|
|
||||||
|
# Trigger render from a background thread (simulating upstream AI MCP/Admin call)
|
||||||
|
result_box: dict = {}
|
||||||
|
|
||||||
|
def do_render() -> None:
|
||||||
|
r = client.post("/api/admin/test/render", json={"device_id": "tablet-01"})
|
||||||
|
result_box["status_code"] = r.status_code
|
||||||
|
result_box["body"] = r.json()
|
||||||
|
|
||||||
|
t = threading.Thread(target=do_render)
|
||||||
|
t.start()
|
||||||
|
|
||||||
|
# Mock Android receives render.apply and returns needs_clarification from Repair AI
|
||||||
|
render_frame = json.loads(ws.receive_text())
|
||||||
|
assert render_frame["type"] == "render.apply"
|
||||||
|
task_id = render_frame["payload"]["task_id"]
|
||||||
|
snapshot_id = render_frame["payload"]["snapshot_id"]
|
||||||
|
|
||||||
|
ws.send_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "render.result",
|
||||||
|
"payload": {
|
||||||
|
"task_id": task_id,
|
||||||
|
"snapshot_id": snapshot_id,
|
||||||
|
"trigger": "initial_render",
|
||||||
|
"status": "needs_clarification",
|
||||||
|
"attempts": 1,
|
||||||
|
"clarification_questions": [
|
||||||
|
{"field": "server.gpu_temp", "question": "缺少 gpu_temp 字段,请问应显示什么?"}
|
||||||
|
],
|
||||||
|
"errors": ["ReferenceError: gpu_temp is not defined"],
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
t.join(timeout=5)
|
||||||
|
assert result_box["status_code"] == 200
|
||||||
|
assert result_box["body"]["status"] == "needs_clarification"
|
||||||
|
assert len(result_box["body"]["clarification_questions"]) == 1
|
||||||
|
|
||||||
|
# Verify reverse event was also persisted for upstream plugins / polling
|
||||||
|
evts = client.get("/api/admin/events").json()["events"]
|
||||||
|
assert any(e["event_type"] == "repair_data_clarification" for e in evts)
|
||||||
|
|
||||||
|
|
||||||
|
def test_ota_latest_download_and_push(tmp_path: Path) -> None:
|
||||||
|
releases = tmp_path / "releases"
|
||||||
|
releases.mkdir()
|
||||||
|
apk_bytes = b"PK\x03\x04fake-apk-payload"
|
||||||
|
(releases / "pulsewall-latest.apk").write_bytes(apk_bytes)
|
||||||
|
(releases / "latest.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"version_code": 2,
|
||||||
|
"version_name": "0.1.1",
|
||||||
|
"filename": "pulsewall-latest.apk",
|
||||||
|
"size_bytes": len(apk_bytes),
|
||||||
|
"sha256": "deadbeef",
|
||||||
|
"changelog": "测试 OTA 更新",
|
||||||
|
}
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
app = create_app(str(tmp_path / "ota.db"), releases_dir=releases)
|
||||||
|
with TestClient(app) as client:
|
||||||
|
r = client.get("/api/ota/latest")
|
||||||
|
assert r.status_code == 200
|
||||||
|
data = r.json()
|
||||||
|
assert data["available"] is True
|
||||||
|
assert data["version_code"] == 2
|
||||||
|
assert data["download_path"] == "/api/ota/download/pulsewall-latest.apk"
|
||||||
|
|
||||||
|
dl = client.get(data["download_path"])
|
||||||
|
assert dl.status_code == 200
|
||||||
|
assert dl.content == apk_bytes
|
||||||
|
|
||||||
|
with client.websocket_connect("/ws/device/ota-phone") as ws:
|
||||||
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
||||||
|
push_res = client.post("/api/admin/ota/push").json()
|
||||||
|
assert push_res["pushed_devices"] == 1
|
||||||
|
ota_frame = json.loads(ws.receive_text())
|
||||||
|
assert ota_frame["type"] == "ota.available"
|
||||||
|
assert ota_frame["payload"]["version_code"] == 2
|
||||||
|
|
||||||
|
|
||||||
|
def test_ai_config_persistence_and_auto_push_to_new_and_existing_devices(tmp_path: Path) -> None:
|
||||||
|
db_file = str(tmp_path / "cfg_persist.db")
|
||||||
|
|
||||||
|
# 1. Save AI config in Hub instance #1 and verify active devices get immediate live sync
|
||||||
|
app1 = create_app(db_file)
|
||||||
|
with TestClient(app1) as client1:
|
||||||
|
with client1.websocket_connect("/ws/device/old-box") as ws_old:
|
||||||
|
init_cfg = json.loads(ws_old.receive_text())
|
||||||
|
assert init_cfg["type"] == "config.push"
|
||||||
|
assert init_cfg["payload"]["repair_ai"]["enabled"] is False
|
||||||
|
|
||||||
|
# Admin updates & saves AI config -> pushed live to online device
|
||||||
|
save_res = client1.put(
|
||||||
|
"/api/admin/config",
|
||||||
|
json={
|
||||||
|
"repair_ai": {
|
||||||
|
"enabled": True,
|
||||||
|
"base_url": "https://api.deepseek.com/v1",
|
||||||
|
"api_key": "sk-live-secret",
|
||||||
|
"model": "deepseek-chat",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"max_retries": 3,
|
||||||
|
"runtime_cooldown_sec": 20,
|
||||||
|
},
|
||||||
|
"telemetry_interval_sec": 10,
|
||||||
|
"theme": "dark-glass",
|
||||||
|
"lan_debug_enabled": False,
|
||||||
|
"auth_token": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert save_res.status_code == 200
|
||||||
|
assert save_res.json()["pushed_devices"] == 1
|
||||||
|
|
||||||
|
pushed_frame = json.loads(ws_old.receive_text())
|
||||||
|
assert pushed_frame["type"] == "config.push"
|
||||||
|
assert pushed_frame["payload"]["repair_ai"]["enabled"] is True
|
||||||
|
assert pushed_frame["payload"]["repair_ai"]["model"] == "deepseek-chat"
|
||||||
|
assert pushed_frame["payload"]["repair_ai"]["api_key"] == "sk-live-secret"
|
||||||
|
|
||||||
|
# 2. Simulate Hub restart (instance #2 using same SQLite DB):
|
||||||
|
# both reconnecting old device AND brand-new device auto-receive persisted AI config!
|
||||||
|
app2 = create_app(db_file)
|
||||||
|
with TestClient(app2) as client2:
|
||||||
|
with client2.websocket_connect("/ws/device/old-box") as ws_old_reconn:
|
||||||
|
f1 = json.loads(ws_old_reconn.receive_text())
|
||||||
|
assert f1["type"] == "config.push"
|
||||||
|
assert f1["payload"]["repair_ai"]["base_url"] == "https://api.deepseek.com/v1"
|
||||||
|
assert f1["payload"]["repair_ai"]["model"] == "deepseek-chat"
|
||||||
|
|
||||||
|
with client2.websocket_connect("/ws/device/brand-new-tablet") as ws_new:
|
||||||
|
f2 = json.loads(ws_new.receive_text())
|
||||||
|
assert f2["type"] == "config.push"
|
||||||
|
assert f2["payload"]["repair_ai"]["enabled"] is True
|
||||||
|
assert f2["payload"]["repair_ai"]["api_key"] == "sk-live-secret"
|
||||||
|
|
||||||
|
|
||||||
|
def test_per_device_ai_override_isolation_and_hub_mcp_chat_agent(tmp_path: Path) -> None:
|
||||||
|
import asyncio
|
||||||
|
import httpx
|
||||||
|
from app.admin.chat_agent import HubMcpChatAgent
|
||||||
|
|
||||||
|
db_file = str(tmp_path / "per_dev_chat.db")
|
||||||
|
app = create_app(db_file)
|
||||||
|
|
||||||
|
with TestClient(app) as client:
|
||||||
|
# 1. Connect two different devices: tv-box and tablet
|
||||||
|
with client.websocket_connect("/ws/device/tv-box") as ws_tv, client.websocket_connect("/ws/device/tablet") as ws_tab:
|
||||||
|
assert json.loads(ws_tv.receive_text())["type"] == "config.push"
|
||||||
|
assert json.loads(ws_tab.receive_text())["type"] == "config.push"
|
||||||
|
|
||||||
|
ws_tv.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "客厅机顶盒", "model": "TVBox", "display_profile": {"device_type": "tv", "viewport_css_w": 960, "viewport_css_h": 540}}}))
|
||||||
|
assert json.loads(ws_tv.receive_text())["type"] == "config.push"
|
||||||
|
ws_tab.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "桌面平板", "model": "Pad", "display_profile": {"device_type": "tablet", "viewport_css_w": 1200, "viewport_css_h": 800}}}))
|
||||||
|
assert json.loads(ws_tab.receive_text())["type"] == "config.push"
|
||||||
|
|
||||||
|
# 2. Set device-specific AI config ONLY for tv-box
|
||||||
|
r = client.put(
|
||||||
|
"/api/admin/devices/tv-box/repair-ai",
|
||||||
|
json={
|
||||||
|
"use_custom": True,
|
||||||
|
"repair_ai": {
|
||||||
|
"enabled": True,
|
||||||
|
"base_url": "http://192.168.1.50:11434/v1",
|
||||||
|
"api_key": "ollama-local",
|
||||||
|
"model": "qwen2.5-coder:7b",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"max_retries": 2,
|
||||||
|
"runtime_cooldown_sec": 15,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r.status_code == 200
|
||||||
|
assert r.json()["pushed_online"] is True
|
||||||
|
|
||||||
|
# Only tv-box receives the custom model
|
||||||
|
tv_cfg = json.loads(ws_tv.receive_text())
|
||||||
|
assert tv_cfg["type"] == "config.push"
|
||||||
|
assert tv_cfg["payload"]["repair_ai"]["model"] == "qwen2.5-coder:7b"
|
||||||
|
|
||||||
|
# 3. Updating global default config keeps tv-box on its custom AI while pushing global default to tablet
|
||||||
|
client.put(
|
||||||
|
"/api/admin/config",
|
||||||
|
json={
|
||||||
|
"repair_ai": {
|
||||||
|
"enabled": True,
|
||||||
|
"base_url": "https://api.openai.com/v1",
|
||||||
|
"api_key": "sk-global",
|
||||||
|
"model": "gpt-4o-mini",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"max_retries": 3,
|
||||||
|
"runtime_cooldown_sec": 30,
|
||||||
|
},
|
||||||
|
"telemetry_interval_sec": 10,
|
||||||
|
"theme": "dark-glass",
|
||||||
|
"lan_debug_enabled": False,
|
||||||
|
"auth_token": "",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
tv_after = json.loads(ws_tv.receive_text())
|
||||||
|
tab_after = json.loads(ws_tab.receive_text())
|
||||||
|
assert tv_after["payload"]["repair_ai"]["model"] == "qwen2.5-coder:7b"
|
||||||
|
assert tab_after["payload"]["repair_ai"]["model"] == "gpt-4o-mini"
|
||||||
|
|
||||||
|
# 4. Save dedicated Hub Chat AI config & test multi-step MCP tool calling with mocked OpenAI API
|
||||||
|
r_chat_cfg = client.put(
|
||||||
|
"/api/admin/chat-ai-config",
|
||||||
|
json={
|
||||||
|
"base_url": "https://mock-openai.local/v1",
|
||||||
|
"api_key": "sk-hub-chat",
|
||||||
|
"model": "gpt-4o",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"system_prompt": "Test system prompt",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r_chat_cfg.status_code == 200
|
||||||
|
assert r_chat_cfg.json()["hub_chat_ai"]["max_tool_steps"] == 30
|
||||||
|
|
||||||
|
r_chat_cfg2 = client.put(
|
||||||
|
"/api/admin/chat-ai-config",
|
||||||
|
json={
|
||||||
|
"base_url": "https://mock-openai.local/v1",
|
||||||
|
"api_key": "sk-hub-chat",
|
||||||
|
"model": "gpt-4o",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"max_tool_steps": 45,
|
||||||
|
"system_prompt": "Test system prompt",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert r_chat_cfg2.status_code == 200
|
||||||
|
assert r_chat_cfg2.json()["hub_chat_ai"]["max_tool_steps"] == 45
|
||||||
|
|
||||||
|
call_idx = {"n": 0}
|
||||||
|
|
||||||
|
def mock_handler(request: httpx.Request) -> httpx.Response:
|
||||||
|
call_idx["n"] += 1
|
||||||
|
body = json.loads(request.content.decode("utf-8"))
|
||||||
|
if call_idx["n"] == 1:
|
||||||
|
assert any(t["function"]["name"] == "list_devices" for t in body["tools"])
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={
|
||||||
|
"choices": [
|
||||||
|
{
|
||||||
|
"message": {
|
||||||
|
"role": "assistant",
|
||||||
|
"content": "",
|
||||||
|
"tool_calls": [
|
||||||
|
{
|
||||||
|
"id": "call_1",
|
||||||
|
"type": "function",
|
||||||
|
"function": {"name": "list_devices", "arguments": "{}"},
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
)
|
||||||
|
# Second call must include the real MCP tool output containing tv-box & tablet
|
||||||
|
tool_msgs = [m for m in body["messages"] if m.get("role") == "tool"]
|
||||||
|
assert len(tool_msgs) == 1
|
||||||
|
assert "tv-box" in tool_msgs[0]["content"]
|
||||||
|
assert "tablet" in tool_msgs[0]["content"]
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={"choices": [{"message": {"role": "assistant", "content": "已查到 2 台在线设备:客厅机顶盒与桌面平板。"}}]},
|
||||||
|
)
|
||||||
|
|
||||||
|
agent = HubMcpChatAgent(app.state.db, app.state.mcp_server, transport=httpx.MockTransport(mock_handler))
|
||||||
|
chat_res = asyncio.run(agent.chat("查询所有在线设备"))
|
||||||
|
assert chat_res["ok"] is True
|
||||||
|
assert "客厅机顶盒" in chat_res["reply"]
|
||||||
|
assert len(chat_res["tool_trace"]) == 1
|
||||||
|
assert chat_res["tool_trace"][0]["name"] == "list_devices"
|
||||||
|
assert chat_res["tool_trace"][0]["is_error"] is False
|
||||||
|
|
||||||
|
|
||||||
|
def test_persistent_multi_session_background_run_and_prompt_groups(tmp_path: Path) -> None:
|
||||||
|
import httpx
|
||||||
|
from app.admin.chat_agent import HubMcpChatAgent
|
||||||
|
|
||||||
|
db_file = str(tmp_path / "sessions_prompts.db")
|
||||||
|
app = create_app(db_file)
|
||||||
|
|
||||||
|
# Inject a slightly delayed mock OpenAI transport to verify detached background execution
|
||||||
|
def delayed_mock(request: httpx.Request) -> httpx.Response:
|
||||||
|
time.sleep(0.15)
|
||||||
|
return httpx.Response(
|
||||||
|
200,
|
||||||
|
json={"choices": [{"message": {"role": "assistant", "content": "后台任务已完成,即使浏览器关闭也不受影响!"}}]},
|
||||||
|
)
|
||||||
|
|
||||||
|
app.state.chat_agent._transport = httpx.MockTransport(delayed_mock)
|
||||||
|
|
||||||
|
with TestClient(app) as client:
|
||||||
|
# Configure hub chat AI
|
||||||
|
client.put(
|
||||||
|
"/api/admin/chat-ai-config",
|
||||||
|
json={
|
||||||
|
"base_url": "https://mock-openai.local/v1",
|
||||||
|
"api_key": "sk-bg",
|
||||||
|
"model": "gpt-4o-mini",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"system_prompt": "bg test",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 1. Create two separate sessions
|
||||||
|
s1 = client.post("/api/admin/chat/sessions", json={"title": "新会话"}).json()["session"]
|
||||||
|
s2 = client.post("/api/admin/chat/sessions", json={"title": "第二会话"}).json()["session"]
|
||||||
|
assert s1["session_id"] != s2["session_id"]
|
||||||
|
|
||||||
|
# 2. Send message in session 1 -> returns immediately while running in background
|
||||||
|
send_res = client.post(
|
||||||
|
f"/api/admin/chat/sessions/{s1['session_id']}/messages",
|
||||||
|
json={"message": "测试关闭浏览器不中断后台任务"},
|
||||||
|
)
|
||||||
|
assert send_res.status_code == 200
|
||||||
|
data = send_res.json()
|
||||||
|
assert data["ok"] is True
|
||||||
|
assert data["assistant_message"]["status"] == "running"
|
||||||
|
# Auto-titled from first message
|
||||||
|
assert "测试关闭浏览器" in data["session"]["title"]
|
||||||
|
|
||||||
|
# 3. Poll until background task completes (simulating reopening browser later)
|
||||||
|
final_msgs = []
|
||||||
|
for _ in range(30):
|
||||||
|
mres = client.get(f"/api/admin/chat/sessions/{s1['session_id']}/messages").json()
|
||||||
|
final_msgs = mres["messages"]
|
||||||
|
if mres["session"]["status"] == "idle":
|
||||||
|
break
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
assert len(final_msgs) == 2
|
||||||
|
assert final_msgs[0]["role"] == "user"
|
||||||
|
assert final_msgs[1]["role"] == "assistant"
|
||||||
|
assert final_msgs[1]["status"] == "done"
|
||||||
|
assert "后台任务已完成" in final_msgs[1]["content"]
|
||||||
|
|
||||||
|
# 4. Prompt groups seeded & CRUD works cleanly
|
||||||
|
groups = client.get("/api/admin/prompts").json()["groups"]
|
||||||
|
assert len(groups) >= 2
|
||||||
|
|
||||||
|
new_grp = client.post("/api/admin/prompt-groups", json={"name": "我的压测分组", "sort_order": 5}).json()["group"]
|
||||||
|
new_prm = client.post(
|
||||||
|
"/api/admin/prompts",
|
||||||
|
json={"group_id": new_grp["group_id"], "title": "一键全检", "content": "检查全部设备", "sort_order": 1},
|
||||||
|
).json()["prompt"]
|
||||||
|
upd_prm = client.put(
|
||||||
|
f"/api/admin/prompts/{new_prm['prompt_id']}",
|
||||||
|
json={"group_id": new_grp["group_id"], "title": "一键全检v2", "content": "检查全部设备与温度", "sort_order": 2},
|
||||||
|
).json()["prompt"]
|
||||||
|
assert upd_prm["title"] == "一键全检v2"
|
||||||
|
|
||||||
|
groups_after = client.get("/api/admin/prompts").json()["groups"]
|
||||||
|
mine = next(g for g in groups_after if g["group_id"] == new_grp["group_id"])
|
||||||
|
assert len(mine["prompts"]) == 1 and mine["prompts"][0]["title"] == "一键全检v2"
|
||||||
|
|
||||||
|
assert client.delete(f"/api/admin/prompt-groups/{new_grp['group_id']}").json()["deleted"] is True
|
||||||
|
|
||||||
|
|
||||||
|
def test_telemetry_history_7d_storage_cpu_and_metrics_api(tmp_path: Path) -> None:
|
||||||
|
app = create_app(str(tmp_path / "metrics.db"))
|
||||||
|
with TestClient(app) as client:
|
||||||
|
# Default interval is 3s
|
||||||
|
assert client.get("/api/admin/config").json()["telemetry_interval_sec"] == 3
|
||||||
|
|
||||||
|
with client.websocket_connect("/ws/device/box-metrics") as ws:
|
||||||
|
init_cfg = json.loads(ws.receive_text())
|
||||||
|
assert init_cfg["payload"]["telemetry_interval_sec"] == 3
|
||||||
|
|
||||||
|
ws.send_text(json.dumps({"type": "device.hello", "payload": {"device_name": "监控盒"}}))
|
||||||
|
assert json.loads(ws.receive_text())["type"] == "config.push"
|
||||||
|
|
||||||
|
ws.send_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"type": "device.telemetry",
|
||||||
|
"payload": {
|
||||||
|
"cpu_usage_pct": 23.5,
|
||||||
|
"gpu_usage_pct": 18.5,
|
||||||
|
"mem_used_mb": 1400,
|
||||||
|
"mem_total_mb": 4096,
|
||||||
|
"storage_used_mb": 12288,
|
||||||
|
"storage_total_mb": 32768,
|
||||||
|
"battery_temp_c": 34.2,
|
||||||
|
"thermal_zones": {"cpu": 46.8, "gpu": 42.1},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
)
|
||||||
|
)
|
||||||
|
time.sleep(0.05)
|
||||||
|
|
||||||
|
m15 = client.get("/api/admin/devices/box-metrics/metrics?range=15m").json()
|
||||||
|
assert m15["retention_days"] == 7
|
||||||
|
assert m15["point_count"] == 1
|
||||||
|
pt = m15["points"][0]
|
||||||
|
assert pt["cpu_usage_pct"] == 23.5
|
||||||
|
assert pt["gpu_usage_pct"] == 18.5
|
||||||
|
assert pt["storage_used_mb"] == 12288
|
||||||
|
assert pt["storage_total_mb"] == 32768
|
||||||
|
assert pt["max_thermal_c"] == 46.8
|
||||||
|
|
||||||
|
m7d = client.get("/api/admin/devices/box-metrics/metrics?range=7d").json()
|
||||||
|
assert m7d["point_count"] == 1
|
||||||
|
assert m7d["points"][0]["gpu_usage_pct"] == 18.5
|
||||||
|
|
||||||
|
|
||||||
|
def test_zero_latency_fmp4_muxer_no_frame_hold_and_seamless_restart() -> None:
|
||||||
|
import io
|
||||||
|
import av
|
||||||
|
from app.adb_lan.fmp4_muxer import AnnexBAccessUnitFramer, ZeroLatencyFmp4Muxer
|
||||||
|
|
||||||
|
enc_buf = io.BytesIO()
|
||||||
|
c = av.open(enc_buf, mode="w", format="h264")
|
||||||
|
s = c.add_stream("libx264", rate=25)
|
||||||
|
s.width, s.height = 320, 180
|
||||||
|
s.options = {"profile": "baseline", "tune": "zerolatency", "preset": "ultrafast"}
|
||||||
|
raw_frames: list[bytes] = []
|
||||||
|
for _ in range(4):
|
||||||
|
f = av.VideoFrame(320, 180, "rgb24")
|
||||||
|
for p in s.encode(f):
|
||||||
|
raw_frames.append(bytes(p))
|
||||||
|
for p in s.encode(None):
|
||||||
|
raw_frames.append(bytes(p))
|
||||||
|
|
||||||
|
framer = AnnexBAccessUnitFramer()
|
||||||
|
muxer = ZeroLatencyFmp4Muxer()
|
||||||
|
muxer.update_dimensions(320, 180)
|
||||||
|
|
||||||
|
out = bytearray()
|
||||||
|
for idx, rf in enumerate(raw_frames):
|
||||||
|
aus = framer.feed(rf) + framer.flush_idle()
|
||||||
|
assert len(aus) == 1
|
||||||
|
new_init, frag = muxer.mux_access_unit(aus[0][0], aus[0][1])
|
||||||
|
if idx == 0:
|
||||||
|
assert new_init is not None
|
||||||
|
out.extend(new_init)
|
||||||
|
else:
|
||||||
|
assert new_init is None
|
||||||
|
assert frag is not None
|
||||||
|
out.extend(frag)
|
||||||
|
|
||||||
|
# Seamless restart at identical SPS/PPS must NOT re-emit init segment
|
||||||
|
framer.reset()
|
||||||
|
aus_re = framer.feed(raw_frames[0]) + framer.flush_idle()
|
||||||
|
new_init2, frag2 = muxer.mux_access_unit(aus_re[0][0], aus_re[0][1])
|
||||||
|
assert new_init2 is None
|
||||||
|
assert frag2 is not None
|
||||||
|
out.extend(frag2)
|
||||||
|
|
||||||
|
dec = av.open(io.BytesIO(bytes(out)), format="mp4")
|
||||||
|
decoded = list(dec.decode(video=0))
|
||||||
|
assert len(decoded) == len(raw_frames) + 1
|
||||||
|
assert decoded[0].width == 320 and decoded[0].height == 180
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>PulseWall 控制中心</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Generated
+1288
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,20 @@
|
|||||||
|
{
|
||||||
|
"name": "pulsewall-admin-web",
|
||||||
|
"version": "0.2.0",
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build",
|
||||||
|
"preview": "vite preview"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"echarts": "^6.1.0",
|
||||||
|
"marked": "^15.0.0",
|
||||||
|
"vue": "^3.5.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"vite": "^6.0.0"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,243 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||||
|
import { hubApi } from './api'
|
||||||
|
import DeviceManager from './components/DeviceManager.vue'
|
||||||
|
import ChatWorkbench from './components/ChatWorkbench.vue'
|
||||||
|
import PromptManager from './components/PromptManager.vue'
|
||||||
|
import GlobalSettings from './components/GlobalSettings.vue'
|
||||||
|
|
||||||
|
const activeTab = ref('chat')
|
||||||
|
const devices = ref([])
|
||||||
|
const config = ref(null)
|
||||||
|
const promptGroups = ref([])
|
||||||
|
const ota = ref(null)
|
||||||
|
const events = ref([])
|
||||||
|
const audits = ref([])
|
||||||
|
const toastMsg = ref('')
|
||||||
|
const chatRef = ref(null)
|
||||||
|
|
||||||
|
let toastTimer = null
|
||||||
|
let pollTimer = null
|
||||||
|
|
||||||
|
const onlineCount = computed(() => devices.value.filter((d) => d.online).length)
|
||||||
|
|
||||||
|
function showToast(msg) {
|
||||||
|
toastMsg.value = msg
|
||||||
|
clearTimeout(toastTimer)
|
||||||
|
toastTimer = setTimeout(() => {
|
||||||
|
toastMsg.value = ''
|
||||||
|
}, 3200)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConfig() {
|
||||||
|
try {
|
||||||
|
config.value = await hubApi.getConfig()
|
||||||
|
} catch (e) {
|
||||||
|
showToast(`读取配置失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadPrompts() {
|
||||||
|
try {
|
||||||
|
const res = await hubApi.listPrompts()
|
||||||
|
promptGroups.value = res.groups || []
|
||||||
|
} catch (e) {
|
||||||
|
showToast(`读取快捷指令失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshLive() {
|
||||||
|
try {
|
||||||
|
const [dRes, eRes, aRes, oRes] = await Promise.all([
|
||||||
|
hubApi.getDevices(),
|
||||||
|
hubApi.getEvents(),
|
||||||
|
hubApi.getAudits(),
|
||||||
|
hubApi.getOtaLatest()
|
||||||
|
])
|
||||||
|
devices.value = dRes.devices || []
|
||||||
|
events.value = eRes.events || []
|
||||||
|
audits.value = aRes.audits || []
|
||||||
|
ota.value = oRes
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleSendPromptToChat(content) {
|
||||||
|
activeTab.value = 'chat'
|
||||||
|
setTimeout(() => {
|
||||||
|
chatRef.value?.sendPrompt(content)
|
||||||
|
}, 50)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([loadConfig(), loadPrompts(), refreshLive()])
|
||||||
|
pollTimer = setInterval(refreshLive, 5000)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
clearInterval(pollTimer)
|
||||||
|
clearTimeout(toastTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="app-shell">
|
||||||
|
<header class="topbar">
|
||||||
|
<div class="brand">
|
||||||
|
<span class="brand-dot"></span>
|
||||||
|
<span class="brand-name">PulseWall</span>
|
||||||
|
<span class="brand-sub mono">/mcp/</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<nav class="nav-tabs">
|
||||||
|
<button class="nav-tab" :class="{ active: activeTab === 'devices' }" @click="activeTab = 'devices'">
|
||||||
|
设备列表
|
||||||
|
<span class="tab-count">{{ devices.length }}</span>
|
||||||
|
</button>
|
||||||
|
<button class="nav-tab" :class="{ active: activeTab === 'chat' }" @click="activeTab = 'chat'">
|
||||||
|
AI 会话测试
|
||||||
|
</button>
|
||||||
|
<button class="nav-tab" :class="{ active: activeTab === 'prompts' }" @click="activeTab = 'prompts'">
|
||||||
|
快捷指令
|
||||||
|
<span class="tab-count">{{ promptGroups.length }}</span>
|
||||||
|
</button>
|
||||||
|
<button class="nav-tab" :class="{ active: activeTab === 'global' }" @click="activeTab = 'global'">
|
||||||
|
全局配置与日志
|
||||||
|
<span v-if="events.length" class="tab-count warn">{{ events.length }}</span>
|
||||||
|
</button>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<div class="topbar-right">
|
||||||
|
<span class="pill" :class="onlineCount > 0 ? 'online' : 'offline'">
|
||||||
|
{{ onlineCount }} 台在线
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main class="stage">
|
||||||
|
<DeviceManager
|
||||||
|
v-show="activeTab === 'devices'"
|
||||||
|
:devices="devices"
|
||||||
|
:global-config="config"
|
||||||
|
:is-active="activeTab === 'devices'"
|
||||||
|
@refresh="refreshLive"
|
||||||
|
@toast="showToast"
|
||||||
|
/>
|
||||||
|
<ChatWorkbench
|
||||||
|
ref="chatRef"
|
||||||
|
v-show="activeTab === 'chat'"
|
||||||
|
:devices="devices"
|
||||||
|
:hub-chat-ai="config?.hub_chat_ai"
|
||||||
|
:prompt-groups="promptGroups"
|
||||||
|
@config-saved="loadConfig"
|
||||||
|
@refresh="refreshLive"
|
||||||
|
@open-prompts-tab="activeTab = 'prompts'"
|
||||||
|
@toast="showToast"
|
||||||
|
/>
|
||||||
|
<PromptManager
|
||||||
|
v-show="activeTab === 'prompts'"
|
||||||
|
:groups="promptGroups"
|
||||||
|
@changed="loadPrompts"
|
||||||
|
@send-prompt="handleSendPromptToChat"
|
||||||
|
@toast="showToast"
|
||||||
|
/>
|
||||||
|
<GlobalSettings
|
||||||
|
v-show="activeTab === 'global'"
|
||||||
|
:global-config="config"
|
||||||
|
:ota="ota"
|
||||||
|
:events="events"
|
||||||
|
:audits="audits"
|
||||||
|
@config-saved="loadConfig"
|
||||||
|
@refresh="refreshLive"
|
||||||
|
@toast="showToast"
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<Transition name="toast-fade">
|
||||||
|
<div v-if="toastMsg" class="toast-bar">{{ toastMsg }}</div>
|
||||||
|
</Transition>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.app-shell { display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
|
||||||
|
.topbar {
|
||||||
|
height: 54px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 0 20px;
|
||||||
|
background: #11151e;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.brand { display: flex; align-items: center; gap: 9px; }
|
||||||
|
.brand-dot {
|
||||||
|
width: 9px;
|
||||||
|
height: 9px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent-signal);
|
||||||
|
box-shadow: 0 0 10px rgba(45, 212, 191, 0.7);
|
||||||
|
}
|
||||||
|
.brand-name { font-size: 15.5px; font-weight: 700; letter-spacing: 0.2px; }
|
||||||
|
.brand-sub {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
padding: 2px 7px;
|
||||||
|
border-radius: 6px;
|
||||||
|
}
|
||||||
|
.nav-tabs {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 4px;
|
||||||
|
background: #0b0e14;
|
||||||
|
padding: 4px;
|
||||||
|
border-radius: 10px;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
|
.nav-tab {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
padding: 6px 14px;
|
||||||
|
border-radius: 7px;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: all 0.14s;
|
||||||
|
}
|
||||||
|
.nav-tab:hover { color: var(--ink-primary); }
|
||||||
|
.nav-tab.active {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
box-shadow: inset 0 0 0 1px var(--border-strong);
|
||||||
|
}
|
||||||
|
.tab-count {
|
||||||
|
font-size: 11px;
|
||||||
|
padding: 1px 6px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: rgba(148, 163, 184, 0.16);
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
}
|
||||||
|
.tab-count.warn { background: var(--status-amber-dim); color: var(--status-amber); }
|
||||||
|
.stage { flex: 1; min-height: 0; overflow: hidden; display: flex; flex-direction: column; }
|
||||||
|
.toast-bar {
|
||||||
|
position: fixed;
|
||||||
|
bottom: 22px;
|
||||||
|
right: 22px;
|
||||||
|
z-index: 200;
|
||||||
|
background: #1d2636;
|
||||||
|
color: var(--ink-primary);
|
||||||
|
border: 1px solid var(--accent-signal);
|
||||||
|
padding: 10px 16px;
|
||||||
|
border-radius: 10px;
|
||||||
|
font-size: 13px;
|
||||||
|
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.45);
|
||||||
|
}
|
||||||
|
.toast-fade-enter-active, .toast-fade-leave-active { transition: opacity 0.2s, transform 0.2s; }
|
||||||
|
.toast-fade-enter-from, .toast-fade-leave-to { opacity: 0; transform: translateY(8px); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
async function request(path, options = {}) {
|
||||||
|
const res = await fetch(path, {
|
||||||
|
headers: { 'Content-Type': 'application/json', ...(options.headers || {}) },
|
||||||
|
...options
|
||||||
|
})
|
||||||
|
if (!res.ok) {
|
||||||
|
const text = await res.text().catch(() => '')
|
||||||
|
let detail = text || res.statusText
|
||||||
|
try {
|
||||||
|
const j = JSON.parse(text)
|
||||||
|
if (j.detail) detail = j.detail
|
||||||
|
} catch (_) {}
|
||||||
|
throw new Error(detail)
|
||||||
|
}
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
export const hubApi = {
|
||||||
|
getDevices: () => request('/api/admin/devices'),
|
||||||
|
getDeviceMetrics: (deviceId, range = '1h') =>
|
||||||
|
request(`/api/admin/devices/${encodeURIComponent(deviceId)}/metrics?range=${encodeURIComponent(range)}`),
|
||||||
|
getConfig: () => request('/api/admin/config'),
|
||||||
|
saveGlobalConfig: (body) => request('/api/admin/config', { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
saveChatAiConfig: (body) => request('/api/admin/chat-ai-config', { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
saveDeviceRepairAi: (deviceId, body) =>
|
||||||
|
request(`/api/admin/devices/${encodeURIComponent(deviceId)}/repair-ai`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
setDeviceLanDebug: (deviceId, body) =>
|
||||||
|
request(`/api/admin/devices/${encodeURIComponent(deviceId)}/lan-debug`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
lanAdbAction: (deviceId, action, params = {}) =>
|
||||||
|
request(`/api/lan-debug/${encodeURIComponent(deviceId)}/action`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ action, params })
|
||||||
|
}),
|
||||||
|
pairWirelessAdb: (pairAddress, pairingCode, deviceId = null) =>
|
||||||
|
request('/api/lan-debug/pair', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ pair_address: pairAddress, pairing_code: pairingCode, device_id: deviceId })
|
||||||
|
}),
|
||||||
|
getSnapshots: (deviceId) => request(`/api/admin/snapshots/${encodeURIComponent(deviceId)}`),
|
||||||
|
rollbackDevice: (deviceId, snapshotId) =>
|
||||||
|
request(`/api/admin/devices/${encodeURIComponent(deviceId)}/rollback`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ snapshot_id: snapshotId })
|
||||||
|
}),
|
||||||
|
quickAction: (kind, deviceId) =>
|
||||||
|
request(`/api/admin/test/${kind}`, { method: 'POST', body: JSON.stringify({ device_id: deviceId }) }),
|
||||||
|
getOtaLatest: () => request('/api/ota/latest'),
|
||||||
|
pushOta: (deviceId = null) => {
|
||||||
|
const q = deviceId ? `?device_id=${encodeURIComponent(deviceId)}` : ''
|
||||||
|
return request(`/api/admin/ota/push${q}`, { method: 'POST' })
|
||||||
|
},
|
||||||
|
getAdbOtaStatus: (deviceId) => request(`/api/admin/ota/adb-status/${encodeURIComponent(deviceId)}`),
|
||||||
|
saveDeviceUiPrefs: (deviceId, body) =>
|
||||||
|
request(`/api/admin/devices/${encodeURIComponent(deviceId)}/ui-prefs`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
getEvents: () => request('/api/admin/events'),
|
||||||
|
getAudits: () => request('/api/admin/audits'),
|
||||||
|
|
||||||
|
// Persistent multi-session background chat
|
||||||
|
listChatSessions: () => request('/api/admin/chat/sessions'),
|
||||||
|
createChatSession: (title = '新会话') =>
|
||||||
|
request('/api/admin/chat/sessions', { method: 'POST', body: JSON.stringify({ title }) }),
|
||||||
|
renameChatSession: (sessionId, title) =>
|
||||||
|
request(`/api/admin/chat/sessions/${encodeURIComponent(sessionId)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ title })
|
||||||
|
}),
|
||||||
|
deleteChatSession: (sessionId) =>
|
||||||
|
request(`/api/admin/chat/sessions/${encodeURIComponent(sessionId)}`, { method: 'DELETE' }),
|
||||||
|
getSessionMessages: (sessionId) =>
|
||||||
|
request(`/api/admin/chat/sessions/${encodeURIComponent(sessionId)}/messages`),
|
||||||
|
sendSessionMessage: (sessionId, message) =>
|
||||||
|
request(`/api/admin/chat/sessions/${encodeURIComponent(sessionId)}/messages`, {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify({ message })
|
||||||
|
}),
|
||||||
|
|
||||||
|
// Quick prompt groups & items
|
||||||
|
listPrompts: () => request('/api/admin/prompts'),
|
||||||
|
createPromptGroup: (name, sortOrder = 0) =>
|
||||||
|
request('/api/admin/prompt-groups', { method: 'POST', body: JSON.stringify({ name, sort_order: sortOrder }) }),
|
||||||
|
updatePromptGroup: (groupId, name, sortOrder = 0) =>
|
||||||
|
request(`/api/admin/prompt-groups/${encodeURIComponent(groupId)}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ name, sort_order: sortOrder })
|
||||||
|
}),
|
||||||
|
deletePromptGroup: (groupId) =>
|
||||||
|
request(`/api/admin/prompt-groups/${encodeURIComponent(groupId)}`, { method: 'DELETE' }),
|
||||||
|
createPrompt: (body) => request('/api/admin/prompts', { method: 'POST', body: JSON.stringify(body) }),
|
||||||
|
updatePrompt: (promptId, body) =>
|
||||||
|
request(`/api/admin/prompts/${encodeURIComponent(promptId)}`, { method: 'PUT', body: JSON.stringify(body) }),
|
||||||
|
deletePrompt: (promptId) =>
|
||||||
|
request(`/api/admin/prompts/${encodeURIComponent(promptId)}`, { method: 'DELETE' })
|
||||||
|
}
|
||||||
@@ -0,0 +1,759 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import { marked } from 'marked'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
devices: { type: Array, default: () => [] },
|
||||||
|
hubChatAi: { type: Object, default: null },
|
||||||
|
promptGroups: { type: Array, default: () => [] }
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['config-saved', 'refresh', 'open-prompts-tab', 'toast'])
|
||||||
|
|
||||||
|
marked.setOptions({ breaks: true, gfm: true })
|
||||||
|
|
||||||
|
const LAST_SESSION_KEY = 'pulsewall_last_chat_session'
|
||||||
|
|
||||||
|
const railTab = ref('sessions') // 'sessions' | 'prompts'
|
||||||
|
const sessions = ref([])
|
||||||
|
const activeSessionId = ref(null)
|
||||||
|
const activeSession = computed(() => sessions.value.find((s) => s.session_id === activeSessionId.value) || null)
|
||||||
|
const messages = ref([])
|
||||||
|
|
||||||
|
const inputText = ref('')
|
||||||
|
const submitting = ref(false)
|
||||||
|
const streamRef = ref(null)
|
||||||
|
|
||||||
|
// Hub AI Config Modal
|
||||||
|
const showConfigModal = ref(false)
|
||||||
|
const savingCfg = ref(false)
|
||||||
|
const cfgForm = ref({
|
||||||
|
base_url: 'https://api.openai.com/v1',
|
||||||
|
api_key: '',
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
system_prompt: '',
|
||||||
|
timeout_sec: 60,
|
||||||
|
max_tool_steps: 30
|
||||||
|
})
|
||||||
|
|
||||||
|
let pollTimer = null
|
||||||
|
let lastActiveStatus = 'idle'
|
||||||
|
|
||||||
|
const isConfigured = computed(() => !!(props.hubChatAi?.api_key && props.hubChatAi?.model && props.hubChatAi?.base_url))
|
||||||
|
const isActiveRunning = computed(() => activeSession.value?.status === 'running')
|
||||||
|
const anySessionRunning = computed(() => sessions.value.some((s) => s.status === 'running'))
|
||||||
|
|
||||||
|
function renderMarkdown(text) {
|
||||||
|
return marked.parse(String(text || ''))
|
||||||
|
}
|
||||||
|
|
||||||
|
async function scrollToBottom() {
|
||||||
|
await nextTick()
|
||||||
|
if (streamRef.value) {
|
||||||
|
streamRef.value.scrollTop = streamRef.value.scrollHeight
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSessions(preserveSelection = true) {
|
||||||
|
const res = await hubApi.listChatSessions()
|
||||||
|
sessions.value = res.sessions || []
|
||||||
|
if (!sessions.value.length) return
|
||||||
|
|
||||||
|
const savedId = localStorage.getItem(LAST_SESSION_KEY)
|
||||||
|
if (preserveSelection && activeSessionId.value && sessions.value.some((s) => s.session_id === activeSessionId.value)) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (savedId && sessions.value.some((s) => s.session_id === savedId)) {
|
||||||
|
await selectSession(savedId)
|
||||||
|
} else {
|
||||||
|
await selectSession(sessions.value[0].session_id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function selectSession(sessionId) {
|
||||||
|
activeSessionId.value = sessionId
|
||||||
|
localStorage.setItem(LAST_SESSION_KEY, sessionId)
|
||||||
|
await loadActiveMessages(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadActiveMessages(forceScroll = false) {
|
||||||
|
if (!activeSessionId.value) return
|
||||||
|
try {
|
||||||
|
const prevCount = messages.value.length
|
||||||
|
const prevLast = messages.value[messages.value.length - 1]
|
||||||
|
const prevTraceLen = prevLast?.tool_trace?.length || 0
|
||||||
|
const prevStatus = prevLast?.status || ''
|
||||||
|
|
||||||
|
const res = await hubApi.getSessionMessages(activeSessionId.value)
|
||||||
|
messages.value = res.messages || []
|
||||||
|
|
||||||
|
// Update active session metadata in list
|
||||||
|
const idx = sessions.value.findIndex((s) => s.session_id === activeSessionId.value)
|
||||||
|
if (idx >= 0 && res.session) {
|
||||||
|
sessions.value[idx] = res.session
|
||||||
|
}
|
||||||
|
|
||||||
|
const curStatus = res.session?.status || 'idle'
|
||||||
|
if (lastActiveStatus === 'running' && curStatus !== 'running') {
|
||||||
|
emit('refresh')
|
||||||
|
}
|
||||||
|
lastActiveStatus = curStatus
|
||||||
|
|
||||||
|
const newLast = messages.value[messages.value.length - 1]
|
||||||
|
const changed =
|
||||||
|
forceScroll ||
|
||||||
|
messages.value.length !== prevCount ||
|
||||||
|
(newLast?.tool_trace?.length || 0) !== prevTraceLen ||
|
||||||
|
(newLast?.status || '') !== prevStatus
|
||||||
|
if (changed) {
|
||||||
|
await scrollToBottom()
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function createNewSession() {
|
||||||
|
try {
|
||||||
|
const res = await hubApi.createChatSession('新会话')
|
||||||
|
await loadSessions(false)
|
||||||
|
await selectSession(res.session.session_id)
|
||||||
|
railTab.value = 'sessions'
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `新建会话失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function renameSession(sess) {
|
||||||
|
const next = prompt('请输入新的会话名称:', sess.title)
|
||||||
|
if (next === null || !next.trim()) return
|
||||||
|
try {
|
||||||
|
await hubApi.renameChatSession(sess.session_id, next.trim())
|
||||||
|
await loadSessions(true)
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `重命名失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function deleteSession(sess) {
|
||||||
|
if (!confirm(`确定删除会话「${sess.title}」及其全部聊天记录吗?`)) return
|
||||||
|
try {
|
||||||
|
await hubApi.deleteChatSession(sess.session_id)
|
||||||
|
if (activeSessionId.value === sess.session_id) {
|
||||||
|
activeSessionId.value = null
|
||||||
|
localStorage.removeItem(LAST_SESSION_KEY)
|
||||||
|
}
|
||||||
|
await loadSessions(false)
|
||||||
|
emit('toast', '会话已删除')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `删除失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendPrompt(textOverride = null) {
|
||||||
|
const text = (textOverride ?? inputText.value).trim()
|
||||||
|
if (!text || submitting.value) return
|
||||||
|
if (!isConfigured.value) {
|
||||||
|
openConfigModal()
|
||||||
|
emit('toast', '请先配置中心桥专用 AI 的 API Key 和模型')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!activeSessionId.value) {
|
||||||
|
await createNewSession()
|
||||||
|
}
|
||||||
|
if (isActiveRunning.value) {
|
||||||
|
emit('toast', '当前会话有 AI 正在后台执行,可等待完成或新建会话并发测试')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (textOverride == null) inputText.value = ''
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
await hubApi.sendSessionMessage(activeSessionId.value, text)
|
||||||
|
lastActiveStatus = 'running'
|
||||||
|
await loadSessions(true)
|
||||||
|
await loadActiveMessages(true)
|
||||||
|
ensurePolling()
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `发送失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function insertDeviceMention(dev) {
|
||||||
|
const snippet = `设备 ${dev.device_name} (${dev.device_id}) `
|
||||||
|
inputText.value = inputText.value ? `${inputText.value} ${snippet}` : snippet
|
||||||
|
}
|
||||||
|
|
||||||
|
function openConfigModal() {
|
||||||
|
const c = props.hubChatAi || {}
|
||||||
|
cfgForm.value = {
|
||||||
|
base_url: c.base_url || 'https://api.openai.com/v1',
|
||||||
|
api_key: c.api_key || '',
|
||||||
|
model: c.model || 'gpt-4o-mini',
|
||||||
|
system_prompt: c.system_prompt || '',
|
||||||
|
timeout_sec: c.timeout_sec || 60,
|
||||||
|
max_tool_steps: c.max_tool_steps ?? 30
|
||||||
|
}
|
||||||
|
showConfigModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveConfig() {
|
||||||
|
savingCfg.value = true
|
||||||
|
try {
|
||||||
|
await hubApi.saveChatAiConfig({
|
||||||
|
base_url: cfgForm.value.base_url.trim(),
|
||||||
|
api_key: cfgForm.value.api_key.trim(),
|
||||||
|
model: cfgForm.value.model.trim(),
|
||||||
|
system_prompt: cfgForm.value.system_prompt.trim(),
|
||||||
|
timeout_sec: Number(cfgForm.value.timeout_sec) || 60,
|
||||||
|
max_tool_steps: Math.min(100, Math.max(1, Number(cfgForm.value.max_tool_steps) || 30))
|
||||||
|
})
|
||||||
|
showConfigModal.value = false
|
||||||
|
emit('config-saved')
|
||||||
|
emit('toast', '中心桥专用 AI 配置已保存')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `保存失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
savingCfg.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onComposerKeydown(e) {
|
||||||
|
if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') {
|
||||||
|
e.preventDefault()
|
||||||
|
sendPrompt()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensurePolling() {
|
||||||
|
clearInterval(pollTimer)
|
||||||
|
const interval = anySessionRunning.value || isActiveRunning.value ? 1200 : 5000
|
||||||
|
pollTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const res = await hubApi.listChatSessions()
|
||||||
|
sessions.value = res.sessions || []
|
||||||
|
if (activeSessionId.value) {
|
||||||
|
await loadActiveMessages(false)
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}, interval)
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(anySessionRunning, ensurePolling)
|
||||||
|
|
||||||
|
defineExpose({ sendPrompt })
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await loadSessions(false)
|
||||||
|
ensurePolling()
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
clearInterval(pollTimer)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="chat-workspace">
|
||||||
|
<!-- Left Sidebar: Multi-session switcher & Grouped Quick Prompts -->
|
||||||
|
<aside class="chat-rail">
|
||||||
|
<div class="rail-top">
|
||||||
|
<button class="btn btn-primary new-sess-btn" @click="createNewSession">+ 新建会话</button>
|
||||||
|
<div class="rail-tabs">
|
||||||
|
<button :class="{ active: railTab === 'sessions' }" @click="railTab = 'sessions'">
|
||||||
|
会话 ({{ sessions.length }})
|
||||||
|
</button>
|
||||||
|
<button :class="{ active: railTab === 'prompts' }" @click="railTab = 'prompts'">
|
||||||
|
快捷指令
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Sessions List -->
|
||||||
|
<div v-if="railTab === 'sessions'" class="rail-scroll">
|
||||||
|
<div
|
||||||
|
v-for="s in sessions"
|
||||||
|
:key="s.session_id"
|
||||||
|
class="sess-item"
|
||||||
|
:class="{ active: s.session_id === activeSessionId }"
|
||||||
|
@click="selectSession(s.session_id)"
|
||||||
|
>
|
||||||
|
<div class="sess-row">
|
||||||
|
<span class="sess-title">{{ s.title }}</span>
|
||||||
|
<span v-if="s.status === 'running'" class="running-badge">
|
||||||
|
<span class="pulse-dot sm"></span> 运行中
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="sess-meta">
|
||||||
|
<span>{{ s.message_count || 0 }} 条消息</span>
|
||||||
|
<div class="sess-ops" @click.stop>
|
||||||
|
<button class="icon-btn" title="重命名" @click="renameSession(s)">改名</button>
|
||||||
|
<button class="icon-btn danger" title="删除" @click="deleteSession(s)">删</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Grouped Quick Prompts & Online Devices -->
|
||||||
|
<div v-else class="rail-scroll">
|
||||||
|
<div class="rail-subhead">
|
||||||
|
<span>自定义快捷指令</span>
|
||||||
|
<button class="icon-btn accent" @click="emit('open-prompts-tab')">管理分组</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="!promptGroups.length" class="rail-empty">暂无快捷指令,请点右上角管理创建。</div>
|
||||||
|
<div v-for="g in promptGroups" :key="g.group_id" class="p-group">
|
||||||
|
<div class="p-group-name">{{ g.name }}</div>
|
||||||
|
<button
|
||||||
|
v-for="p in g.prompts"
|
||||||
|
:key="p.prompt_id"
|
||||||
|
class="prompt-btn"
|
||||||
|
:disabled="isActiveRunning || submitting"
|
||||||
|
@click="sendPrompt(p.content)"
|
||||||
|
>
|
||||||
|
{{ p.title }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="rail-subhead" style="margin-top:16px;">
|
||||||
|
<span>在线设备(点击填入)</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="!devices.length" class="rail-empty">暂无接入设备</div>
|
||||||
|
<button
|
||||||
|
v-for="d in devices"
|
||||||
|
:key="d.device_id"
|
||||||
|
class="mini-dev"
|
||||||
|
@click="insertDeviceMention(d)"
|
||||||
|
>
|
||||||
|
<span class="mini-dot" :class="d.online ? 'on' : 'off'"></span>
|
||||||
|
<span class="mini-info">
|
||||||
|
<strong>{{ d.device_name }}</strong>
|
||||||
|
<small class="mono">{{ d.display_profile?.viewport_css_w || '?' }}×{{ d.display_profile?.viewport_css_h || '?' }}</small>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- Expansive Main Chat Stage -->
|
||||||
|
<section class="chat-stage">
|
||||||
|
<div class="chat-toolbar">
|
||||||
|
<div class="toolbar-left">
|
||||||
|
<span class="toolbar-title">{{ activeSession?.title || 'AI 会话测试' }}</span>
|
||||||
|
<span v-if="isActiveRunning" class="pill online">
|
||||||
|
<span class="pulse-dot sm"></span> 后台执行中(关闭浏览器不中断)
|
||||||
|
</span>
|
||||||
|
<span class="pill" :class="isConfigured ? '' : 'amber'">
|
||||||
|
{{ isConfigured ? hubChatAi.model : '未配置中心桥 AI' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="toolbar-actions">
|
||||||
|
<button class="btn btn-sm" @click="railTab = railTab === 'prompts' ? 'sessions' : 'prompts'">
|
||||||
|
{{ railTab === 'prompts' ? '看会话列表' : '快捷指令' }}
|
||||||
|
</button>
|
||||||
|
<button class="btn btn-sm" @click="openConfigModal">AI 模型配置</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div ref="streamRef" class="chat-stream">
|
||||||
|
<div class="stream-inner">
|
||||||
|
<div v-if="!messages.length" class="welcome-card">
|
||||||
|
<h3>开始新的 MCP 联调会话</h3>
|
||||||
|
<p>历史对话会自动持久化到中心桥 SQLite,刷新或关闭浏览器均不会丢失上下文或中断正在运行的 AI 任务。</p>
|
||||||
|
<div v-if="promptGroups.length" class="welcome-chips">
|
||||||
|
<button
|
||||||
|
v-for="p in (promptGroups[0]?.prompts || []).slice(0, 4)"
|
||||||
|
:key="p.prompt_id"
|
||||||
|
class="chip-btn"
|
||||||
|
@click="sendPrompt(p.content)"
|
||||||
|
>
|
||||||
|
{{ p.title }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-for="m in messages" :key="m.id" class="msg-row" :class="m.role">
|
||||||
|
<div class="msg-bubble" :class="m.role">
|
||||||
|
<div v-if="m.status === 'running'" class="running-line">
|
||||||
|
<span class="pulse-dot"></span>
|
||||||
|
<span>
|
||||||
|
AI 正在中心桥后台运行中
|
||||||
|
<template v-if="m.tool_trace?.length">(已完成 {{ m.tool_trace.length }} 步 MCP 工具调用)</template>
|
||||||
|
,可随时切换会话或关闭浏览器…
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div v-else-if="m.role === 'assistant'" class="md-body" v-html="renderMarkdown(m.content)"></div>
|
||||||
|
<div v-else class="plain-body">{{ m.content }}</div>
|
||||||
|
|
||||||
|
<div v-if="m.tool_trace && m.tool_trace.length" class="trace-list">
|
||||||
|
<details v-for="(t, ti) in m.tool_trace" :key="ti" class="trace-item">
|
||||||
|
<summary>
|
||||||
|
<span class="trace-tag" :class="t.is_error ? 'err' : 'ok'">{{ t.is_error ? 'ERR' : 'MCP' }}</span>
|
||||||
|
<span class="mono">{{ t.name }}</span>
|
||||||
|
</summary>
|
||||||
|
<div class="trace-body">
|
||||||
|
<div class="trace-lbl">入参</div>
|
||||||
|
<pre class="mono">{{ JSON.stringify(t.arguments, null, 2) }}</pre>
|
||||||
|
<div class="trace-lbl">返回</div>
|
||||||
|
<pre class="mono">{{ t.result }}</pre>
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="composer-bar">
|
||||||
|
<div class="composer-inner">
|
||||||
|
<textarea
|
||||||
|
v-model="inputText"
|
||||||
|
class="composer-input"
|
||||||
|
rows="3"
|
||||||
|
:disabled="isActiveRunning"
|
||||||
|
:placeholder="isActiveRunning ? '当前会话正在后台运行,可新建其他会话并行测试…' : '输入测试指令,让 AI 自动调用 MCP 检查设备、画页面或发告警… (Ctrl+Enter 发送)'"
|
||||||
|
@keydown="onComposerKeydown"
|
||||||
|
></textarea>
|
||||||
|
<div class="composer-foot">
|
||||||
|
<span class="composer-hint">对话与任务全程持久化在中心桥后端 · Ctrl + Enter 发送</span>
|
||||||
|
<button class="btn btn-primary" :disabled="submitting || isActiveRunning || !inputText.trim()" @click="sendPrompt()">
|
||||||
|
{{ isActiveRunning ? '后台执行中…' : submitting ? '提交中…' : '发送消息' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Hub Chat AI Config Modal -->
|
||||||
|
<Teleport to="body">
|
||||||
|
<div v-if="showConfigModal" class="modal-backdrop" @click.self="showConfigModal = false">
|
||||||
|
<div class="modal-box">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>中心桥专用 AI 模型配置</h3>
|
||||||
|
<button class="btn btn-ghost btn-sm" @click="showConfigModal = false">关闭</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<p class="modal-desc">
|
||||||
|
此配置仅用于中心桥「AI 会话测试」自动调用 MCP 工具,与各 Android 设备上的端侧修复 AI 完全独立。
|
||||||
|
</p>
|
||||||
|
<label class="field-label">OpenAI 兼容 Base URL</label>
|
||||||
|
<input v-model="cfgForm.base_url" class="input mono" placeholder="https://api.openai.com/v1" />
|
||||||
|
|
||||||
|
<label class="field-label">API Key</label>
|
||||||
|
<input v-model="cfgForm.api_key" class="input mono" type="password" placeholder="sk-..." />
|
||||||
|
|
||||||
|
<div class="form-row-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">Model(需支持 Tool Calling)</label>
|
||||||
|
<input v-model="cfgForm.model" class="input mono" placeholder="gpt-4o-mini / deepseek-chat" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">请求超时(秒)</label>
|
||||||
|
<input v-model.number="cfgForm.timeout_sec" class="input" type="number" min="10" max="180" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="field-label">单轮最大 MCP 工具调用步数(默认 30 轮,范围 1~100)</label>
|
||||||
|
<input v-model.number="cfgForm.max_tool_steps" class="input" type="number" min="1" max="100" />
|
||||||
|
|
||||||
|
<label class="field-label">System Prompt</label>
|
||||||
|
<textarea v-model="cfgForm.system_prompt" class="textarea" rows="4"></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button class="btn" @click="showConfigModal = false">取消</button>
|
||||||
|
<button class="btn btn-primary" :disabled="savingCfg" @click="saveConfig">
|
||||||
|
{{ savingCfg ? '保存中…' : '保存配置' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.chat-workspace { display: flex; flex: 1; min-height: 0; height: 100%; }
|
||||||
|
|
||||||
|
.chat-rail {
|
||||||
|
width: 280px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: #11151e;
|
||||||
|
border-right: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.chat-rail { display: none; }
|
||||||
|
}
|
||||||
|
.rail-top {
|
||||||
|
padding: 12px 12px 10px;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 10px;
|
||||||
|
}
|
||||||
|
.new-sess-btn { width: 100%; }
|
||||||
|
.rail-tabs {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1fr 1fr;
|
||||||
|
gap: 4px;
|
||||||
|
background: #0b0e14;
|
||||||
|
padding: 3px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
|
.rail-tabs button {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 6px;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.rail-tabs button.active {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.rail-scroll {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 10px 12px 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.sess-item {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 9px;
|
||||||
|
padding: 10px 11px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.14s, background 0.14s;
|
||||||
|
}
|
||||||
|
.sess-item:hover { border-color: var(--border-strong); }
|
||||||
|
.sess-item.active { border-color: var(--accent-signal); background: #182230; }
|
||||||
|
.sess-row { display: flex; align-items: center; justify-content: space-between; gap: 6px; }
|
||||||
|
.sess-title {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
}
|
||||||
|
.running-badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
font-size: 11px;
|
||||||
|
color: var(--accent-signal);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.sess-meta {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
margin-top: 6px;
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
}
|
||||||
|
.sess-ops { display: flex; gap: 6px; }
|
||||||
|
.icon-btn {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
font-size: 11.5px;
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 2px 4px;
|
||||||
|
}
|
||||||
|
.icon-btn:hover { color: var(--ink-primary); }
|
||||||
|
.icon-btn.accent { color: var(--accent-signal); }
|
||||||
|
.icon-btn.danger:hover { color: #fca5a5; }
|
||||||
|
|
||||||
|
.rail-subhead {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
margin-bottom: 8px;
|
||||||
|
}
|
||||||
|
.rail-empty { font-size: 12px; color: var(--ink-muted); }
|
||||||
|
.p-group { margin-bottom: 12px; }
|
||||||
|
.p-group-name {
|
||||||
|
font-size: 11.5px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
margin-bottom: 5px;
|
||||||
|
padding-left: 2px;
|
||||||
|
}
|
||||||
|
.prompt-btn {
|
||||||
|
width: 100%;
|
||||||
|
text-align: left;
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 7px 10px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
margin-bottom: 5px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.prompt-btn:hover:not(:disabled) { border-color: var(--accent-signal); color: var(--ink-primary); }
|
||||||
|
|
||||||
|
.mini-dev {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 9px;
|
||||||
|
padding: 7px 10px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 8px;
|
||||||
|
color: var(--ink-primary);
|
||||||
|
text-align: left;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.mini-dev:hover { border-color: var(--border-strong); background: var(--bg-elevated); }
|
||||||
|
.mini-dot { width: 8px; height: 8px; border-radius: 50%; flex-shrink: 0; }
|
||||||
|
.mini-dot.on { background: var(--accent-signal); }
|
||||||
|
.mini-dot.off { background: #4b5563; }
|
||||||
|
.mini-info { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
|
||||||
|
.mini-info strong { font-size: 12.5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||||
|
.mini-info small { font-size: 11px; color: var(--ink-muted); }
|
||||||
|
|
||||||
|
/* Main Stage */
|
||||||
|
.chat-stage { flex: 1; min-width: 0; display: flex; flex-direction: column; background: var(--bg-canvas); }
|
||||||
|
.chat-toolbar {
|
||||||
|
height: 48px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
padding: 0 22px;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
background: #10141d;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
.toolbar-left, .toolbar-actions { display: flex; align-items: center; gap: 10px; min-width: 0; }
|
||||||
|
.toolbar-title { font-size: 14px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 340px; }
|
||||||
|
|
||||||
|
.chat-stream { flex: 1; min-height: 0; overflow-y: auto; padding: 24px 28px; }
|
||||||
|
.stream-inner { max-width: 940px; margin: 0 auto; display: flex; flex-direction: column; gap: 18px; }
|
||||||
|
|
||||||
|
.welcome-card {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 14px;
|
||||||
|
padding: 24px;
|
||||||
|
margin-top: 24px;
|
||||||
|
}
|
||||||
|
.welcome-card h3 { margin: 0 0 8px; font-size: 17px; }
|
||||||
|
.welcome-card p { margin: 0 0 16px; color: var(--ink-secondary); line-height: 1.6; }
|
||||||
|
.welcome-chips { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.chip-btn {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
border-radius: 999px;
|
||||||
|
padding: 7px 14px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.chip-btn:hover { border-color: var(--accent-signal); }
|
||||||
|
|
||||||
|
.msg-row { display: flex; }
|
||||||
|
.msg-row.user { justify-content: flex-end; }
|
||||||
|
.msg-row.assistant, .msg-row.error { justify-content: flex-start; }
|
||||||
|
|
||||||
|
.msg-bubble {
|
||||||
|
max-width: 84%;
|
||||||
|
padding: 13px 17px;
|
||||||
|
border-radius: 13px;
|
||||||
|
font-size: 14.5px;
|
||||||
|
line-height: 1.65;
|
||||||
|
}
|
||||||
|
.msg-bubble.user {
|
||||||
|
background: #143b42;
|
||||||
|
border: 1px solid rgba(45, 212, 191, 0.35);
|
||||||
|
color: #f0fdfa;
|
||||||
|
border-bottom-right-radius: 4px;
|
||||||
|
}
|
||||||
|
.msg-bubble.assistant {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
border-bottom-left-radius: 4px;
|
||||||
|
}
|
||||||
|
.msg-bubble.error {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 100%;
|
||||||
|
background: var(--status-crimson-dim);
|
||||||
|
border: 1px solid rgba(239, 68, 68, 0.45);
|
||||||
|
color: #fecaca;
|
||||||
|
}
|
||||||
|
.plain-body { white-space: pre-wrap; word-break: break-word; }
|
||||||
|
|
||||||
|
.running-line {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 10px;
|
||||||
|
color: var(--accent-signal);
|
||||||
|
font-size: 13.5px;
|
||||||
|
}
|
||||||
|
.pulse-dot {
|
||||||
|
width: 8px;
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--accent-signal);
|
||||||
|
display: inline-block;
|
||||||
|
animation: pulse 1.2s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
.pulse-dot.sm { width: 6px; height: 6px; }
|
||||||
|
@keyframes pulse {
|
||||||
|
0%, 100% { opacity: 0.35; transform: scale(0.9); }
|
||||||
|
50% { opacity: 1; transform: scale(1.25); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.trace-list {
|
||||||
|
margin-top: 12px;
|
||||||
|
padding-top: 10px;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 6px;
|
||||||
|
}
|
||||||
|
.trace-item { background: #0d1118; border: 1px solid var(--border-subtle); border-radius: 8px; padding: 7px 11px; }
|
||||||
|
.trace-item summary { cursor: pointer; display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--ink-secondary); }
|
||||||
|
.trace-tag { font-size: 10.5px; font-weight: 700; padding: 1px 6px; border-radius: 5px; }
|
||||||
|
.trace-tag.ok { background: var(--accent-signal-dim); color: var(--accent-signal); }
|
||||||
|
.trace-tag.err { background: var(--status-crimson-dim); color: #fca5a5; }
|
||||||
|
.trace-body { margin-top: 8px; display: flex; flex-direction: column; gap: 6px; }
|
||||||
|
.trace-lbl { font-size: 11px; color: var(--ink-muted); }
|
||||||
|
.trace-body pre {
|
||||||
|
margin: 0;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: #090c12;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 6px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: #cbd5e1;
|
||||||
|
max-height: 200px;
|
||||||
|
overflow: auto;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.composer-bar { flex-shrink: 0; padding: 14px 28px 18px; border-top: 1px solid var(--border-subtle); background: #10141d; }
|
||||||
|
.composer-inner { max-width: 940px; margin: 0 auto; background: var(--bg-panel); border: 1px solid var(--border-strong); border-radius: 12px; padding: 10px 12px; }
|
||||||
|
.composer-inner:focus-within { border-color: var(--accent-signal); }
|
||||||
|
.composer-input { width: 100%; background: transparent; border: none; outline: none; color: var(--ink-primary); font-size: 14.5px; line-height: 1.55; font-family: inherit; resize: none; }
|
||||||
|
.composer-foot { margin-top: 8px; padding-top: 8px; border-top: 1px solid var(--border-subtle); display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||||
|
.composer-hint { font-size: 12px; color: var(--ink-muted); }
|
||||||
|
.modal-desc { margin: 0 0 10px; font-size: 12.5px; color: var(--ink-muted); line-height: 1.5; }
|
||||||
|
.form-row-2 { display: grid; grid-template-columns: 1.5fr 1fr; gap: 12px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,611 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
import DeviceMetricsCharts from './DeviceMetricsCharts.vue'
|
||||||
|
import DeviceScreenMirror from './DeviceScreenMirror.vue'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
devices: { type: Array, default: () => [] },
|
||||||
|
globalConfig: { type: Object, default: null },
|
||||||
|
isActive: { type: Boolean, default: true }
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['refresh', 'toast'])
|
||||||
|
|
||||||
|
const selectedId = ref(null)
|
||||||
|
const snapshots = ref([])
|
||||||
|
const actionResult = ref('')
|
||||||
|
const aiDirty = ref(false)
|
||||||
|
const savingAi = ref(false)
|
||||||
|
const adbTargetDraft = ref('')
|
||||||
|
|
||||||
|
// Right-side floating settings drawer
|
||||||
|
const showSettings = ref(false)
|
||||||
|
const savingPrefs = ref(false)
|
||||||
|
const mirrorEnabledOverride = ref(null) // optimistic value until next device poll
|
||||||
|
|
||||||
|
// OTA progress (ADB direct install)
|
||||||
|
const otaBusy = ref(false)
|
||||||
|
const otaStatusText = ref('')
|
||||||
|
let otaPollTimer = null
|
||||||
|
|
||||||
|
const aiMode = ref('inherit')
|
||||||
|
const aiForm = ref({
|
||||||
|
enabled: false,
|
||||||
|
base_url: 'https://api.openai.com/v1',
|
||||||
|
api_key: '',
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
max_retries: 3,
|
||||||
|
runtime_cooldown_sec: 30,
|
||||||
|
timeout_sec: 30
|
||||||
|
})
|
||||||
|
|
||||||
|
const selectedDevice = computed(() => props.devices.find((d) => d.device_id === selectedId.value) || null)
|
||||||
|
const mirrorModuleEnabled = computed(() => {
|
||||||
|
if (mirrorEnabledOverride.value !== null) return mirrorEnabledOverride.value
|
||||||
|
return selectedDevice.value?.ui_prefs?.screen_mirror_enabled !== false
|
||||||
|
})
|
||||||
|
const otaButtonLabel = computed(() => {
|
||||||
|
if (otaBusy.value) return 'ADB 安装中…'
|
||||||
|
return selectedDevice.value?.adb_connected ? '更新 App(ADB 直装)' : '更新 App(OTA 自更新)'
|
||||||
|
})
|
||||||
|
|
||||||
|
function syncFormFromDevice(dev) {
|
||||||
|
if (!dev) return
|
||||||
|
const override = dev.repair_ai_override
|
||||||
|
aiMode.value = override ? 'custom' : 'inherit'
|
||||||
|
const src = override || props.globalConfig?.repair_ai || {}
|
||||||
|
aiForm.value = {
|
||||||
|
enabled: !!src.enabled,
|
||||||
|
base_url: src.base_url || 'https://api.openai.com/v1',
|
||||||
|
api_key: src.api_key || '',
|
||||||
|
model: src.model || 'gpt-4o-mini',
|
||||||
|
max_retries: src.max_retries ?? 3,
|
||||||
|
runtime_cooldown_sec: src.runtime_cooldown_sec ?? 30,
|
||||||
|
timeout_sec: src.timeout_sec ?? 30
|
||||||
|
}
|
||||||
|
adbTargetDraft.value = dev.adb_target || ''
|
||||||
|
aiDirty.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSnapshots(deviceId) {
|
||||||
|
if (!deviceId) {
|
||||||
|
snapshots.value = []
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const res = await hubApi.getSnapshots(deviceId)
|
||||||
|
snapshots.value = res.snapshots || []
|
||||||
|
} catch (_) {
|
||||||
|
snapshots.value = []
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectDevice(deviceId) {
|
||||||
|
if (selectedId.value === deviceId) return
|
||||||
|
if (aiDirty.value && !confirm('当前设备的「端侧修复 AI」配置有未保存修改,确定切换设备并放弃修改吗?')) return
|
||||||
|
selectedId.value = deviceId
|
||||||
|
actionResult.value = ''
|
||||||
|
mirrorEnabledOverride.value = null
|
||||||
|
stopOtaPoll()
|
||||||
|
otaBusy.value = false
|
||||||
|
otaStatusText.value = ''
|
||||||
|
const dev = props.devices.find((d) => d.device_id === deviceId)
|
||||||
|
syncFormFromDevice(dev)
|
||||||
|
loadSnapshots(deviceId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Drop optimistic override once server state catches up
|
||||||
|
watch(
|
||||||
|
() => selectedDevice.value?.ui_prefs?.screen_mirror_enabled,
|
||||||
|
(val) => {
|
||||||
|
if (mirrorEnabledOverride.value !== null && (val !== false) === mirrorEnabledOverride.value) {
|
||||||
|
mirrorEnabledOverride.value = null
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
function openSettings() {
|
||||||
|
showSettings.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeSettings() {
|
||||||
|
if (aiDirty.value && !confirm('「端侧修复 AI」配置有未保存修改,确定关闭并放弃修改吗?')) return
|
||||||
|
if (aiDirty.value) syncFormFromDevice(selectedDevice.value)
|
||||||
|
showSettings.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function onKeydown(e) {
|
||||||
|
if (e.key === 'Escape' && showSettings.value) closeSettings()
|
||||||
|
}
|
||||||
|
|
||||||
|
async function setMirrorModuleEnabled(enabled) {
|
||||||
|
if (!selectedDevice.value) return
|
||||||
|
const prev = mirrorModuleEnabled.value
|
||||||
|
mirrorEnabledOverride.value = enabled
|
||||||
|
savingPrefs.value = true
|
||||||
|
try {
|
||||||
|
await hubApi.saveDeviceUiPrefs(selectedDevice.value.device_id, { screen_mirror_enabled: enabled })
|
||||||
|
emit('refresh')
|
||||||
|
emit('toast', enabled ? '已启用「设备界面」模块' : '已停用「设备界面」模块(页面中不再显示,投屏同时关闭)')
|
||||||
|
} catch (e) {
|
||||||
|
mirrorEnabledOverride.value = prev
|
||||||
|
emit('toast', `保存失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
savingPrefs.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopOtaPoll() {
|
||||||
|
clearInterval(otaPollTimer)
|
||||||
|
otaPollTimer = null
|
||||||
|
}
|
||||||
|
|
||||||
|
function startOtaPoll(deviceId) {
|
||||||
|
stopOtaPoll()
|
||||||
|
otaPollTimer = setInterval(async () => {
|
||||||
|
try {
|
||||||
|
const st = await hubApi.getAdbOtaStatus(deviceId)
|
||||||
|
if (selectedId.value !== deviceId) {
|
||||||
|
stopOtaPoll()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
otaStatusText.value = st.message || ''
|
||||||
|
if (st.state !== 'installing') {
|
||||||
|
stopOtaPoll()
|
||||||
|
otaBusy.value = false
|
||||||
|
emit('toast', st.message || 'ADB 更新已结束')
|
||||||
|
emit('refresh')
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}, 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => window.addEventListener('keydown', onKeydown))
|
||||||
|
onUnmounted(() => {
|
||||||
|
window.removeEventListener('keydown', onKeydown)
|
||||||
|
stopOtaPoll()
|
||||||
|
})
|
||||||
|
|
||||||
|
// Auto-select first device on initial load without ever overwriting dirty edits
|
||||||
|
watch(
|
||||||
|
() => props.devices,
|
||||||
|
(list) => {
|
||||||
|
if (!list.length) return
|
||||||
|
if (!selectedId.value || !list.some((d) => d.device_id === selectedId.value)) {
|
||||||
|
selectDevice(list[0].device_id)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
async function saveDeviceAi() {
|
||||||
|
if (!selectedDevice.value) return
|
||||||
|
savingAi.value = true
|
||||||
|
try {
|
||||||
|
const isCustom = aiMode.value === 'custom'
|
||||||
|
const r = await hubApi.saveDeviceRepairAi(selectedDevice.value.device_id, {
|
||||||
|
use_custom: isCustom,
|
||||||
|
repair_ai: isCustom ? { ...aiForm.value } : null
|
||||||
|
})
|
||||||
|
aiDirty.value = false
|
||||||
|
emit('refresh')
|
||||||
|
emit('toast', r.pushed_online ? '已保存并实时同步至该设备' : '已保存(设备下次上线自动下发)')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `保存失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
savingAi.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function runQuick(kind) {
|
||||||
|
if (!selectedDevice.value) return
|
||||||
|
try {
|
||||||
|
const r = await hubApi.quickAction(kind, selectedDevice.value.device_id)
|
||||||
|
actionResult.value = JSON.stringify(r)
|
||||||
|
if (kind === 'render') loadSnapshots(selectedDevice.value.device_id)
|
||||||
|
emit('toast', '指令已下发至设备')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `执行失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pushOtaSingle() {
|
||||||
|
if (!selectedDevice.value || otaBusy.value) return
|
||||||
|
const deviceId = selectedDevice.value.device_id
|
||||||
|
try {
|
||||||
|
const r = await hubApi.pushOta(deviceId)
|
||||||
|
const res = (r.results || [])[0] || {}
|
||||||
|
if (res.method === 'adb') {
|
||||||
|
otaBusy.value = true
|
||||||
|
otaStatusText.value = `正在通过 ADB 直接安装 v${r.release?.version_name}(无线传输约 30~90 秒)…`
|
||||||
|
emit('toast', `ADB 已连接:开始直接安装 v${r.release?.version_name}`)
|
||||||
|
startOtaPoll(deviceId)
|
||||||
|
} else if (res.method === 'app') {
|
||||||
|
otaStatusText.value = ''
|
||||||
|
emit('toast', `ADB 未连接:已向 App 推送 OTA 自更新 v${r.release?.version_name}`)
|
||||||
|
} else {
|
||||||
|
emit('toast', '设备离线且 ADB 未连接,无法更新')
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `更新失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function toggleLanAdb() {
|
||||||
|
if (!selectedDevice.value) return
|
||||||
|
try {
|
||||||
|
await hubApi.setDeviceLanDebug(selectedDevice.value.device_id, {
|
||||||
|
allowed: !selectedDevice.value.lan_debug_allowed,
|
||||||
|
adb_target: adbTargetDraft.value.trim()
|
||||||
|
})
|
||||||
|
emit('refresh')
|
||||||
|
emit('toast', 'LAN ADB 授权状态已更新')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `操作失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function rollbackTo(snapshotId) {
|
||||||
|
if (!selectedDevice.value) return
|
||||||
|
try {
|
||||||
|
await hubApi.rollbackDevice(selectedDevice.value.device_id, snapshotId)
|
||||||
|
emit('toast', `已下发回滚至 ${snapshotId}`)
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `回滚失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatThermals(zones) {
|
||||||
|
if (!zones || typeof zones !== 'object') return '--'
|
||||||
|
const entries = Object.entries(zones).slice(0, 3)
|
||||||
|
return entries.length ? entries.map(([k, v]) => `${k}: ${v}°C`).join(' · ') : '--'
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="device-layout">
|
||||||
|
<aside class="device-sidebar">
|
||||||
|
<div class="sidebar-head">
|
||||||
|
<span>已接入设备({{ devices.length }})</span>
|
||||||
|
<button class="btn btn-sm" @click="emit('refresh')">刷新</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="!devices.length" class="empty-tip">
|
||||||
|
暂无设备上线。请在 Android App 填入中心桥地址 <code class="mono">ws://<HubIP>:8765</code> 或使用局域网自动发现。
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="d in devices"
|
||||||
|
:key="d.device_id"
|
||||||
|
class="dev-item"
|
||||||
|
:class="{ active: d.device_id === selectedId }"
|
||||||
|
@click="selectDevice(d.device_id)"
|
||||||
|
>
|
||||||
|
<div class="dev-row">
|
||||||
|
<strong>{{ d.device_name }}</strong>
|
||||||
|
<span class="pill" :class="d.online ? 'online' : 'offline'">{{ d.online ? '在线' : '离线' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="dev-meta mono">
|
||||||
|
{{ d.device_id }} · {{ d.display_profile?.device_type || 'android' }} · {{ d.display_profile?.viewport_css_w || '?' }}×{{ d.display_profile?.viewport_css_h || '?' }}
|
||||||
|
</div>
|
||||||
|
<div class="dev-tags">
|
||||||
|
<span v-if="d.adb_connected" class="pill online">ADB已连接</span>
|
||||||
|
<span class="pill" :class="d.repair_ai_override ? 'amber' : ''">
|
||||||
|
{{ d.repair_ai_override ? `独立 AI: ${d.repair_ai_override.model}` : '继承全局 AI' }}
|
||||||
|
</span>
|
||||||
|
<span v-for="c in d.capabilities" :key="c" class="pill">{{ c }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="device-inspector">
|
||||||
|
<div v-if="!selectedDevice" class="panel-card">请在左侧选择一台设备进行查看与独立配置。</div>
|
||||||
|
<div v-else class="inspector-inner">
|
||||||
|
<!-- Overview & Quick Actions -->
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title">
|
||||||
|
<span>{{ selectedDevice.device_name }} <small class="mono muted">({{ selectedDevice.device_id }})</small></span>
|
||||||
|
<div style="display:flex;gap:6px;align-items:center;">
|
||||||
|
<span v-if="selectedDevice.adb_connected" class="pill online">ADB已连接</span>
|
||||||
|
<span class="pill" :class="selectedDevice.online ? 'online' : 'offline'">
|
||||||
|
{{ selectedDevice.online ? 'ONLINE' : 'OFFLINE' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="telemetry-grid">
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">设备型号 / 系统</span>
|
||||||
|
<span class="tele-v">{{ selectedDevice.model || '-' }} · Android {{ selectedDevice.android_release }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">App / WebView</span>
|
||||||
|
<span class="tele-v mono">{{ selectedDevice.app_version || '-' }} / {{ selectedDevice.display_profile?.webview_version || '-' }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">视口规格 / 形态</span>
|
||||||
|
<span class="tele-v mono">{{ selectedDevice.display_profile?.viewport_css_w || '?' }}×{{ selectedDevice.display_profile?.viewport_css_h || '?' }} ({{ selectedDevice.display_profile?.device_type || '-' }})</span>
|
||||||
|
</div>
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">CPU / GPU / 内存</span>
|
||||||
|
<span class="tele-v mono">CPU {{ selectedDevice.telemetry?.cpu_usage_pct ?? '--' }}% · GPU {{ selectedDevice.telemetry?.gpu_usage_pct ?? '--' }}% · {{ selectedDevice.telemetry?.mem_used_mb ?? '?' }}/{{ selectedDevice.telemetry?.mem_total_mb ?? '?' }}MB</span>
|
||||||
|
</div>
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">电源 / 温度</span>
|
||||||
|
<span class="tele-v mono">{{ selectedDevice.telemetry?.battery_pct ?? '外接' }}% · {{ selectedDevice.telemetry?.battery_temp_c ?? '--' }}°C · {{ formatThermals(selectedDevice.telemetry?.thermal_zones) }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="tele-cell">
|
||||||
|
<span class="tele-k">硬盘存储</span>
|
||||||
|
<span class="tele-v mono">
|
||||||
|
<template v-if="selectedDevice.telemetry?.storage_total_mb">
|
||||||
|
{{ (selectedDevice.telemetry.storage_used_mb / 1024).toFixed(1) }} / {{ (selectedDevice.telemetry.storage_total_mb / 1024).toFixed(1) }} GB
|
||||||
|
</template>
|
||||||
|
<template v-else>--</template>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="action-bar">
|
||||||
|
<button class="btn btn-primary btn-sm" @click="runQuick('feed')">推送普通消息</button>
|
||||||
|
<button class="btn btn-danger btn-sm" @click="runQuick('alarm')">全屏红色警报</button>
|
||||||
|
<button class="btn btn-sm" @click="runQuick('render')">下发测试动态页</button>
|
||||||
|
<button class="btn btn-sm" @click="runQuick('home')">恢复默认首页</button>
|
||||||
|
<button class="btn btn-sm" @click="pushOtaSingle">推送 OTA 更新</button>
|
||||||
|
</div>
|
||||||
|
<div v-if="actionResult" class="action-out mono">{{ actionResult }}</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Full-Width Live Device Screen Mirror & Virtual Remote Control -->
|
||||||
|
<DeviceScreenMirror
|
||||||
|
:device="selectedDevice"
|
||||||
|
:is-active="isActive"
|
||||||
|
@refresh="emit('refresh')"
|
||||||
|
@toast="(m) => emit('toast', m)"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Balanced 2-Column Lower Grid: Charts on Left, AI Config & Snapshots on Right -->
|
||||||
|
<div class="inspector-columns">
|
||||||
|
<div class="inspector-col-left">
|
||||||
|
<!-- Live & 7-Day Historical Charts (CPU, GPU, Memory, Temperature, Storage) -->
|
||||||
|
<DeviceMetricsCharts
|
||||||
|
:device="selectedDevice"
|
||||||
|
:interval-sec="globalConfig?.telemetry_interval_sec || 3"
|
||||||
|
:is-active="isActive"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="inspector-col-right">
|
||||||
|
<!-- Per-Device AI Config -->
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title">
|
||||||
|
<span>本设备专属「端侧修复 AI」配置</span>
|
||||||
|
<span v-if="aiDirty" class="pill amber">有未保存修改</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="mode-switch">
|
||||||
|
<label class="radio-opt">
|
||||||
|
<input v-model="aiMode" type="radio" value="inherit" @change="aiDirty = true" />
|
||||||
|
继承全局默认配置
|
||||||
|
</label>
|
||||||
|
<label class="radio-opt">
|
||||||
|
<input v-model="aiMode" type="radio" value="custom" @change="aiDirty = true" />
|
||||||
|
使用本设备独立配置
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="ai-fields" :class="{ dimmed: aiMode !== 'custom' }">
|
||||||
|
<label class="check-opt">
|
||||||
|
<input v-model="aiForm.enabled" type="checkbox" :disabled="aiMode !== 'custom'" @change="aiDirty = true" />
|
||||||
|
启用该设备的端侧自动修复哨兵
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="form-grid-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">OpenAI Base URL</label>
|
||||||
|
<input v-model="aiForm.base_url" class="input mono" :disabled="aiMode !== 'custom'" @input="aiDirty = true" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">Model</label>
|
||||||
|
<input v-model="aiForm.model" class="input mono" :disabled="aiMode !== 'custom'" @input="aiDirty = true" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="field-label">API Key</label>
|
||||||
|
<input v-model="aiForm.api_key" class="input mono" type="password" :disabled="aiMode !== 'custom'" @input="aiDirty = true" />
|
||||||
|
|
||||||
|
<div class="form-grid-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">最大修复重试次数</label>
|
||||||
|
<input v-model.number="aiForm.max_retries" class="input" type="number" :disabled="aiMode !== 'custom'" @input="aiDirty = true" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">运行时报错冷却(秒)</label>
|
||||||
|
<input v-model.number="aiForm.runtime_cooldown_sec" class="input" type="number" :disabled="aiMode !== 'custom'" @input="aiDirty = true" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-actions">
|
||||||
|
<button class="btn btn-primary" :disabled="savingAi" @click="saveDeviceAi">
|
||||||
|
{{ savingAi ? '保存中…' : '保存并立即同步至该设备' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- LAN ADB & Snapshots -->
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title"><span>局域网开发者调试(LAN ADB)与页面快照</span></div>
|
||||||
|
<div class="adb-row">
|
||||||
|
<input v-model="adbTargetDraft" class="input mono" placeholder="局域网 ADB 地址如 192.168.1.50:5555" />
|
||||||
|
<button class="btn" @click="toggleLanAdb">
|
||||||
|
{{ selectedDevice.lan_debug_allowed ? '撤销 LAN ADB 授权' : '授权 LAN ADB' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="snap-list">
|
||||||
|
<div v-if="!snapshots.length" class="muted">该设备暂无动态页面快照</div>
|
||||||
|
<div v-for="s in snapshots" :key="s.snapshot_id" class="snap-row">
|
||||||
|
<div>
|
||||||
|
<span class="pill">{{ s.status }}</span>
|
||||||
|
<strong style="margin-left:8px;">{{ s.title || s.snapshot_id }}</strong>
|
||||||
|
<span class="muted mono" style="margin-left:8px;">{{ new Date(s.created_at_ms).toLocaleTimeString() }}</span>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-sm" @click="rollbackTo(s.snapshot_id)">回滚此页</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.device-layout {
|
||||||
|
display: flex;
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
.device-sidebar {
|
||||||
|
width: 268px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: #11151e;
|
||||||
|
border-right: 1px solid var(--border-subtle);
|
||||||
|
padding: 14px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.device-layout { flex-direction: column; overflow-y: auto; }
|
||||||
|
.device-sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--border-subtle); }
|
||||||
|
}
|
||||||
|
|
||||||
|
.sidebar-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.empty-tip {
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
line-height: 1.6;
|
||||||
|
}
|
||||||
|
.dev-item {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 12px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color 0.14s, background 0.14s;
|
||||||
|
}
|
||||||
|
.dev-item:hover { border-color: var(--border-strong); }
|
||||||
|
.dev-item.active {
|
||||||
|
border-color: var(--accent-signal);
|
||||||
|
background: #182230;
|
||||||
|
}
|
||||||
|
.dev-row { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||||
|
.dev-meta { font-size: 11.5px; color: var(--ink-muted); margin: 6px 0; }
|
||||||
|
.dev-tags { display: flex; flex-wrap: wrap; gap: 5px; }
|
||||||
|
|
||||||
|
.device-inspector {
|
||||||
|
flex: 1;
|
||||||
|
min-width: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px 24px 36px;
|
||||||
|
}
|
||||||
|
.inspector-inner {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 1720px;
|
||||||
|
margin: 0 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.inspector-columns {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: minmax(0, 1.3fr) minmax(0, 1fr);
|
||||||
|
gap: 16px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
.inspector-col-left,
|
||||||
|
.inspector-col-right {
|
||||||
|
min-width: 0;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
@media (max-width: 1200px) {
|
||||||
|
.inspector-columns {
|
||||||
|
grid-template-columns: minmax(0, 1fr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.muted { color: var(--ink-muted); font-size: 12.5px; font-weight: 400; }
|
||||||
|
|
||||||
|
.telemetry-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||||
|
gap: 10px;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.tele-cell {
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 9px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 4px;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
.tele-k { font-size: 11px; color: var(--ink-muted); white-space: nowrap; }
|
||||||
|
.tele-v {
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
white-space: nowrap;
|
||||||
|
overflow: hidden;
|
||||||
|
text-overflow: ellipsis;
|
||||||
|
font-variant-numeric: tabular-nums;
|
||||||
|
}
|
||||||
|
|
||||||
|
.action-bar { display: flex; flex-wrap: wrap; gap: 8px; }
|
||||||
|
.action-out {
|
||||||
|
margin-top: 10px;
|
||||||
|
padding: 8px 10px;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border-radius: 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mode-switch { display: flex; gap: 18px; margin-bottom: 12px; flex-wrap: wrap; }
|
||||||
|
.radio-opt, .check-opt {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 7px;
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--ink-primary);
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.ai-fields.dimmed { opacity: 0.48; }
|
||||||
|
.form-grid-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||||
|
@media (max-width: 680px) { .form-grid-2 { grid-template-columns: 1fr; } }
|
||||||
|
.form-actions { margin-top: 14px; }
|
||||||
|
|
||||||
|
.adb-row { display: flex; gap: 10px; margin-bottom: 14px; }
|
||||||
|
.adb-row .input { flex: 1; }
|
||||||
|
.snap-list { display: flex; flex-direction: column; gap: 8px; }
|
||||||
|
.snap-row {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 10px;
|
||||||
|
padding: 8px 0;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,440 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import * as echarts from 'echarts/core'
|
||||||
|
import { LineChart } from 'echarts/charts'
|
||||||
|
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
|
||||||
|
import { CanvasRenderer } from 'echarts/renderers'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
|
||||||
|
echarts.use([LineChart, GridComponent, TooltipComponent, LegendComponent, CanvasRenderer])
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
device: { type: Object, required: true },
|
||||||
|
intervalSec: { type: Number, default: 3 },
|
||||||
|
isActive: { type: Boolean, default: true }
|
||||||
|
})
|
||||||
|
|
||||||
|
const ranges = [
|
||||||
|
{ key: '15m', label: '15 分钟' },
|
||||||
|
{ key: '1h', label: '1 小时' },
|
||||||
|
{ key: '6h', label: '6 小时' },
|
||||||
|
{ key: '24h', label: '24 小时' },
|
||||||
|
{ key: '7d', label: '7 天' }
|
||||||
|
]
|
||||||
|
|
||||||
|
const selectedRange = ref('15m')
|
||||||
|
const points = ref([])
|
||||||
|
|
||||||
|
const wrapRef = ref(null)
|
||||||
|
const cpuEl = ref(null)
|
||||||
|
const memEl = ref(null)
|
||||||
|
const tempEl = ref(null)
|
||||||
|
|
||||||
|
let cpuChart = null
|
||||||
|
let memChart = null
|
||||||
|
let tempChart = null
|
||||||
|
let resizeObs = null
|
||||||
|
let timer = null
|
||||||
|
|
||||||
|
const latestPoint = computed(() => (points.value.length ? points.value[points.value.length - 1] : null))
|
||||||
|
|
||||||
|
const storageInfo = computed(() => {
|
||||||
|
const t = props.device?.telemetry || {}
|
||||||
|
const usedMb = Number(t.storage_used_mb || 0)
|
||||||
|
const totalMb = Number(t.storage_total_mb || 0)
|
||||||
|
if (!totalMb) return null
|
||||||
|
const pct = Math.min(100, Math.round((usedMb / totalMb) * 1000) / 10)
|
||||||
|
return {
|
||||||
|
usedGb: (usedMb / 1024).toFixed(2),
|
||||||
|
totalGb: (totalMb / 1024).toFixed(2),
|
||||||
|
freeGb: ((totalMb - usedMb) / 1024).toFixed(2),
|
||||||
|
pct
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
function fmtTime(ts) {
|
||||||
|
const d = new Date(ts)
|
||||||
|
if (selectedRange.value === '7d' || selectedRange.value === '24h') {
|
||||||
|
return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')} ${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}:${String(d.getSeconds()).padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseOption(labels, series, yAxisExtra = {}) {
|
||||||
|
return {
|
||||||
|
backgroundColor: 'transparent',
|
||||||
|
animation: false,
|
||||||
|
grid: { left: 10, right: 16, top: 32, bottom: 8, containLabel: true },
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'axis',
|
||||||
|
backgroundColor: '#111622',
|
||||||
|
borderColor: '#33415c',
|
||||||
|
textStyle: { color: '#e8edf5', fontSize: 12 }
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
top: 0,
|
||||||
|
right: 4,
|
||||||
|
itemWidth: 12,
|
||||||
|
itemHeight: 8,
|
||||||
|
textStyle: { color: '#94a3b8', fontSize: 11 }
|
||||||
|
},
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
data: labels,
|
||||||
|
boundaryGap: false,
|
||||||
|
axisLine: { lineStyle: { color: '#252e3f' } },
|
||||||
|
axisTick: { show: false },
|
||||||
|
axisLabel: { color: '#7f8da6', fontSize: 10.5, hideOverlap: true }
|
||||||
|
},
|
||||||
|
yAxis: {
|
||||||
|
type: 'value',
|
||||||
|
splitNumber: 4,
|
||||||
|
splitLine: { lineStyle: { color: 'rgba(148,163,184,0.12)', type: 'dashed' } },
|
||||||
|
axisLabel: { color: '#7f8da6', fontSize: 10.5 },
|
||||||
|
...yAxisExtra
|
||||||
|
},
|
||||||
|
series
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ensureChart(el, existing) {
|
||||||
|
if (!el || el.clientWidth < 20 || el.clientHeight < 20) return existing
|
||||||
|
if (!existing) {
|
||||||
|
return echarts.init(el)
|
||||||
|
}
|
||||||
|
existing.resize()
|
||||||
|
return existing
|
||||||
|
}
|
||||||
|
|
||||||
|
function renderCharts() {
|
||||||
|
if (!props.isActive) return
|
||||||
|
const pts = points.value
|
||||||
|
const labels = pts.map((p) => fmtTime(p.ts_ms))
|
||||||
|
const showDot = pts.length > 0 && pts.length <= 24
|
||||||
|
|
||||||
|
cpuChart = ensureChart(cpuEl.value, cpuChart)
|
||||||
|
if (cpuChart) {
|
||||||
|
cpuChart.setOption(
|
||||||
|
baseOption(
|
||||||
|
labels,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: 'CPU %',
|
||||||
|
type: 'line',
|
||||||
|
smooth: 0.25,
|
||||||
|
showSymbol: showDot,
|
||||||
|
symbolSize: 5,
|
||||||
|
connectNulls: true,
|
||||||
|
data: pts.map((p) => p.cpu_usage_pct),
|
||||||
|
lineStyle: { color: '#2dd4bf', width: 2 },
|
||||||
|
itemStyle: { color: '#2dd4bf' },
|
||||||
|
areaStyle: { color: 'rgba(45, 212, 191, 0.14)' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'GPU %',
|
||||||
|
type: 'line',
|
||||||
|
smooth: 0.25,
|
||||||
|
showSymbol: showDot,
|
||||||
|
symbolSize: 5,
|
||||||
|
connectNulls: true,
|
||||||
|
data: pts.map((p) => p.gpu_usage_pct),
|
||||||
|
lineStyle: { color: '#a78bfa', width: 2 },
|
||||||
|
itemStyle: { color: '#a78bfa' },
|
||||||
|
areaStyle: { color: 'rgba(167, 139, 250, 0.12)' }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
{ min: 0, max: 100, axisLabel: { color: '#7f8da6', fontSize: 10.5, formatter: '{value}%' } }
|
||||||
|
),
|
||||||
|
true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
memChart = ensureChart(memEl.value, memChart)
|
||||||
|
if (memChart) {
|
||||||
|
const memTotal = latestPoint.value?.mem_total_mb || props.device?.telemetry?.mem_total_mb
|
||||||
|
memChart.setOption(
|
||||||
|
baseOption(
|
||||||
|
labels,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: '已用内存',
|
||||||
|
type: 'line',
|
||||||
|
smooth: 0.25,
|
||||||
|
showSymbol: showDot,
|
||||||
|
symbolSize: 5,
|
||||||
|
connectNulls: true,
|
||||||
|
data: pts.map((p) => p.mem_used_mb),
|
||||||
|
lineStyle: { color: '#38bdf8', width: 2 },
|
||||||
|
itemStyle: { color: '#38bdf8' },
|
||||||
|
areaStyle: { color: 'rgba(56, 189, 248, 0.14)' }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
{
|
||||||
|
min: 0,
|
||||||
|
...(memTotal ? { max: memTotal } : {}),
|
||||||
|
axisLabel: { color: '#7f8da6', fontSize: 10.5, formatter: '{value}M' }
|
||||||
|
}
|
||||||
|
),
|
||||||
|
true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
tempChart = ensureChart(tempEl.value, tempChart)
|
||||||
|
if (tempChart) {
|
||||||
|
tempChart.setOption(
|
||||||
|
baseOption(
|
||||||
|
labels,
|
||||||
|
[
|
||||||
|
{
|
||||||
|
name: 'SoC 热区最高',
|
||||||
|
type: 'line',
|
||||||
|
smooth: 0.25,
|
||||||
|
showSymbol: showDot,
|
||||||
|
symbolSize: 5,
|
||||||
|
connectNulls: true,
|
||||||
|
data: pts.map((p) => p.max_thermal_c),
|
||||||
|
lineStyle: { color: '#f97316', width: 2 },
|
||||||
|
itemStyle: { color: '#f97316' },
|
||||||
|
areaStyle: { color: 'rgba(249, 115, 22, 0.12)' }
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '电池温度',
|
||||||
|
type: 'line',
|
||||||
|
smooth: 0.25,
|
||||||
|
showSymbol: showDot,
|
||||||
|
symbolSize: 5,
|
||||||
|
connectNulls: true,
|
||||||
|
data: pts.map((p) => p.battery_temp_c),
|
||||||
|
lineStyle: { color: '#facc15', width: 2 },
|
||||||
|
itemStyle: { color: '#facc15' }
|
||||||
|
}
|
||||||
|
],
|
||||||
|
{ axisLabel: { color: '#7f8da6', fontSize: 10.5, formatter: '{value}°C' } }
|
||||||
|
),
|
||||||
|
true
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchMetrics() {
|
||||||
|
if (!props.device?.device_id) return
|
||||||
|
try {
|
||||||
|
const res = await hubApi.getDeviceMetrics(props.device.device_id, selectedRange.value)
|
||||||
|
points.value = res.points || []
|
||||||
|
await nextTick()
|
||||||
|
renderCharts()
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleResize() {
|
||||||
|
if (!props.isActive) return
|
||||||
|
renderCharts()
|
||||||
|
}
|
||||||
|
|
||||||
|
function restartTimer() {
|
||||||
|
clearInterval(timer)
|
||||||
|
const ms = Math.max(3000, (props.intervalSec || 3) * 1000)
|
||||||
|
timer = setInterval(() => {
|
||||||
|
if (props.isActive) fetchMetrics()
|
||||||
|
}, ms)
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => [props.device?.device_id, selectedRange.value],
|
||||||
|
() => {
|
||||||
|
fetchMetrics()
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.isActive,
|
||||||
|
async (active) => {
|
||||||
|
if (active) {
|
||||||
|
await nextTick()
|
||||||
|
fetchMetrics()
|
||||||
|
setTimeout(handleResize, 60)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
watch(() => props.intervalSec, restartTimer)
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
fetchMetrics()
|
||||||
|
restartTimer()
|
||||||
|
if (typeof ResizeObserver !== 'undefined' && wrapRef.value) {
|
||||||
|
resizeObs = new ResizeObserver(() => {
|
||||||
|
if (props.isActive) handleResize()
|
||||||
|
})
|
||||||
|
resizeObs.observe(wrapRef.value)
|
||||||
|
}
|
||||||
|
window.addEventListener('resize', handleResize)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
clearInterval(timer)
|
||||||
|
resizeObs?.disconnect()
|
||||||
|
window.removeEventListener('resize', handleResize)
|
||||||
|
cpuChart?.dispose()
|
||||||
|
memChart?.dispose()
|
||||||
|
tempChart?.dispose()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div ref="wrapRef" class="panel-card">
|
||||||
|
<div class="panel-title">
|
||||||
|
<span>实时与 7 天历史监控图表(每 {{ intervalSec }} 秒采集 · 共 {{ points.length }} 点)</span>
|
||||||
|
<div class="range-bar">
|
||||||
|
<button
|
||||||
|
v-for="r in ranges"
|
||||||
|
:key="r.key"
|
||||||
|
class="range-btn"
|
||||||
|
:class="{ active: selectedRange === r.key }"
|
||||||
|
@click="selectedRange = r.key"
|
||||||
|
>
|
||||||
|
{{ r.label }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="storageInfo" class="storage-box">
|
||||||
|
<div class="storage-head">
|
||||||
|
<span>内部存储(/data 硬盘空间)</span>
|
||||||
|
<span class="mono">
|
||||||
|
已用 <strong>{{ storageInfo.usedGb }} GB</strong> / {{ storageInfo.totalGb }} GB(剩余 {{ storageInfo.freeGb }} GB · {{ storageInfo.pct }}%)
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="storage-track">
|
||||||
|
<div
|
||||||
|
class="storage-fill"
|
||||||
|
:class="{ warn: storageInfo.pct > 80, danger: storageInfo.pct > 92 }"
|
||||||
|
:style="{ width: storageInfo.pct + '%' }"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-else class="storage-empty">等待设备上报硬盘存储空间数据(升级至 v0.3.1 后自动上报)</div>
|
||||||
|
|
||||||
|
<div class="charts-grid">
|
||||||
|
<div class="chart-card full">
|
||||||
|
<div class="chart-head">
|
||||||
|
<span class="chart-label">CPU & GPU 性能占用</span>
|
||||||
|
<span class="chart-val mono">
|
||||||
|
CPU {{ latestPoint?.cpu_usage_pct != null ? `${latestPoint.cpu_usage_pct}%` : '--' }}
|
||||||
|
· GPU {{ latestPoint?.gpu_usage_pct != null ? `${latestPoint.gpu_usage_pct}%` : '--' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div ref="cpuEl" class="chart-box"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chart-card full">
|
||||||
|
<div class="chart-head">
|
||||||
|
<span class="chart-label">内存占用</span>
|
||||||
|
<span class="chart-val mono">
|
||||||
|
{{ latestPoint?.mem_used_mb != null ? `${latestPoint.mem_used_mb} / ${latestPoint.mem_total_mb || '?'} MB` : '--' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div ref="memEl" class="chart-box"></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="chart-card full">
|
||||||
|
<div class="chart-head">
|
||||||
|
<span class="chart-label">温度监控(SoC 热区最高 & 电池)</span>
|
||||||
|
<span class="chart-val mono">
|
||||||
|
SoC {{ latestPoint?.max_thermal_c != null ? `${latestPoint.max_thermal_c}°C` : '--' }}
|
||||||
|
· 电池 {{ latestPoint?.battery_temp_c != null ? `${latestPoint.battery_temp_c}°C` : '--' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div ref="tempEl" class="chart-box"></div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.range-bar {
|
||||||
|
display: flex;
|
||||||
|
gap: 4px;
|
||||||
|
background: var(--bg-input);
|
||||||
|
padding: 3px;
|
||||||
|
border-radius: 8px;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
|
.range-btn {
|
||||||
|
border: none;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
font-size: 11.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
padding: 4px 9px;
|
||||||
|
border-radius: 6px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.range-btn.active {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--accent-signal);
|
||||||
|
}
|
||||||
|
|
||||||
|
.storage-box {
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 14px;
|
||||||
|
}
|
||||||
|
.storage-head {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
font-size: 12.5px;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
margin-bottom: 7px;
|
||||||
|
}
|
||||||
|
.storage-track {
|
||||||
|
height: 8px;
|
||||||
|
border-radius: 99px;
|
||||||
|
background: #1f293d;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.storage-fill {
|
||||||
|
height: 100%;
|
||||||
|
background: var(--accent-signal);
|
||||||
|
border-radius: 99px;
|
||||||
|
transition: width 0.3s ease;
|
||||||
|
}
|
||||||
|
.storage-fill.warn { background: var(--status-amber); }
|
||||||
|
.storage-fill.danger { background: var(--status-crimson); }
|
||||||
|
.storage-empty { font-size: 12px; color: var(--ink-muted); margin-bottom: 12px; }
|
||||||
|
|
||||||
|
.charts-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||||
|
gap: 12px;
|
||||||
|
}
|
||||||
|
@media (max-width: 780px) {
|
||||||
|
.charts-grid { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
.chart-card {
|
||||||
|
min-width: 0;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 12px 12px 8px;
|
||||||
|
}
|
||||||
|
.chart-card.full { grid-column: 1 / -1; }
|
||||||
|
.chart-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
.chart-label { font-size: 12.5px; font-weight: 600; color: var(--ink-secondary); white-space: nowrap; }
|
||||||
|
.chart-val { font-size: 12px; color: var(--accent-signal); white-space: nowrap; font-variant-numeric: tabular-nums; }
|
||||||
|
.chart-box {
|
||||||
|
width: 100%;
|
||||||
|
height: 195px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
device: { type: Object, required: true },
|
||||||
|
isActive: { type: Boolean, default: true }
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['refresh', 'toast'])
|
||||||
|
|
||||||
|
const stageRef = ref(null)
|
||||||
|
const videoRef = ref(null)
|
||||||
|
const canvasRef = ref(null)
|
||||||
|
|
||||||
|
const webCodecsSupported =
|
||||||
|
typeof window !== 'undefined' &&
|
||||||
|
typeof window.VideoDecoder === 'function' &&
|
||||||
|
typeof window.EncodedVideoChunk === 'function'
|
||||||
|
|
||||||
|
const COLLAPSE_KEY = 'pulsewall_mirror_collapsed'
|
||||||
|
const decodeEngine = ref(webCodecsSupported ? 'webcodecs' : 'mse') // 'webcodecs' | 'mse'
|
||||||
|
// Default PAUSED: stream only starts after user explicitly clicks「播放」
|
||||||
|
const streamEnabled = ref(false)
|
||||||
|
const collapsed = ref(localStorage.getItem(COLLAPSE_KEY) === '1')
|
||||||
|
const quality = ref('hd')
|
||||||
|
const streamStatus = ref('idle') // 'idle' | 'connecting' | 'playing' | 'error'
|
||||||
|
const hasRenderedFrame = ref(false)
|
||||||
|
const streamErr = ref('')
|
||||||
|
const videoMeta = ref('')
|
||||||
|
const bitrateKbps = ref(0)
|
||||||
|
const tapRipple = ref(null)
|
||||||
|
const adbLatched = ref(!!props.device?.adb_connected)
|
||||||
|
|
||||||
|
// Inline wireless pairing form
|
||||||
|
const pairAddr = ref('')
|
||||||
|
const pairCode = ref('')
|
||||||
|
const pairing = ref(false)
|
||||||
|
|
||||||
|
let ws = null
|
||||||
|
// MSE state (fallback when WebCodecs unavailable on non-HTTPS LAN HTTP)
|
||||||
|
let mediaSource = null
|
||||||
|
let sourceBuffer = null
|
||||||
|
let mediaObjectUrl = ''
|
||||||
|
let appendQueue = []
|
||||||
|
// WebCodecs GPU Decoder state (direct raw Annex-B H.264 -> GPU VideoDecoder -> <canvas>)
|
||||||
|
let videoDecoder = null
|
||||||
|
let wcConfigured = false
|
||||||
|
let wcGotKeyFrame = false
|
||||||
|
let wcFrameSeq = 0
|
||||||
|
let wcPendingFrames = []
|
||||||
|
|
||||||
|
let bytesWindow = 0
|
||||||
|
let statsTimer = null
|
||||||
|
let reconnectTimer = null
|
||||||
|
let destroyed = false
|
||||||
|
|
||||||
|
const isPortrait = computed(() => {
|
||||||
|
const p = props.device?.display_profile
|
||||||
|
return p && Number(p.height_px) > Number(p.width_px)
|
||||||
|
})
|
||||||
|
|
||||||
|
const hasAdb = computed(() => adbLatched.value || !!props.device?.adb_connected)
|
||||||
|
const shouldStream = computed(() => props.isActive && streamEnabled.value && !collapsed.value && hasAdb.value)
|
||||||
|
|
||||||
|
function toggleCollapse() {
|
||||||
|
collapsed.value = !collapsed.value
|
||||||
|
localStorage.setItem(COLLAPSE_KEY, collapsed.value ? '1' : '0')
|
||||||
|
if (collapsed.value) {
|
||||||
|
// Collapsing always pauses the stream so the device encoder is released
|
||||||
|
streamEnabled.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const engineBadgeText = computed(() =>
|
||||||
|
decodeEngine.value === 'webcodecs' ? 'WebCodecs GPU 直解' : 'MSE GPU 硬解'
|
||||||
|
)
|
||||||
|
const engineBadgeTitle = computed(() =>
|
||||||
|
decodeEngine.value === 'webcodecs'
|
||||||
|
? '原始 H.264 裸流直推浏览器 WebCodecs 硬件 GPU 解码器(极低延迟)'
|
||||||
|
: '当前通过明文 HTTP 局域网访问,浏览器禁用 WebCodecs API;已自动切换零转码 fMP4 硬件 GPU 解码(如需裸流直解,可通过 localhost / HTTPS 或在 chrome://flags/#unsafely-treat-insecure-origin-as-secure 添加本地址)'
|
||||||
|
)
|
||||||
|
|
||||||
|
function cleanupWebCodecs(clearCanvas = false) {
|
||||||
|
wcConfigured = false
|
||||||
|
wcGotKeyFrame = false
|
||||||
|
wcFrameSeq = 0
|
||||||
|
wcPendingFrames = []
|
||||||
|
if (videoDecoder) {
|
||||||
|
const old = videoDecoder
|
||||||
|
videoDecoder = null
|
||||||
|
try {
|
||||||
|
if (old.state !== 'closed') old.close()
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (clearCanvas && canvasRef.value) {
|
||||||
|
const ctx = canvasRef.value.getContext('2d')
|
||||||
|
if (ctx) ctx.clearRect(0, 0, canvasRef.value.width, canvasRef.value.height)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanupMse() {
|
||||||
|
appendQueue = []
|
||||||
|
sourceBuffer = null
|
||||||
|
if (mediaSource) {
|
||||||
|
try {
|
||||||
|
if (mediaSource.readyState === 'open') mediaSource.endOfStream()
|
||||||
|
} catch (_) {}
|
||||||
|
mediaSource = null
|
||||||
|
}
|
||||||
|
if (videoRef.value) {
|
||||||
|
try {
|
||||||
|
videoRef.value.pause()
|
||||||
|
videoRef.value.removeAttribute('src')
|
||||||
|
videoRef.value.load()
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (mediaObjectUrl) {
|
||||||
|
URL.revokeObjectURL(mediaObjectUrl)
|
||||||
|
mediaObjectUrl = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopStream(clearSurface = true) {
|
||||||
|
clearTimeout(reconnectTimer)
|
||||||
|
if (ws) {
|
||||||
|
const old = ws
|
||||||
|
ws = null
|
||||||
|
old.onclose = null
|
||||||
|
old.onerror = null
|
||||||
|
old.onmessage = null
|
||||||
|
try {
|
||||||
|
old.close(1000, 'stop')
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
cleanupWebCodecs(clearSurface)
|
||||||
|
if (clearSurface) {
|
||||||
|
cleanupMse()
|
||||||
|
hasRenderedFrame.value = false
|
||||||
|
}
|
||||||
|
bitrateKbps.value = 0
|
||||||
|
if (!streamEnabled.value) {
|
||||||
|
streamStatus.value = 'idle'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Mode 1: Direct raw H.264 -> Browser WebCodecs GPU VideoDecoder -> <canvas> ----
|
||||||
|
async function initWebCodecsDecoder(codec, width, height, socket) {
|
||||||
|
cleanupWebCodecs(false)
|
||||||
|
videoMeta.value = `${width}×${height}`
|
||||||
|
|
||||||
|
const hwCfg = {
|
||||||
|
codec: codec || 'avc1.42c029',
|
||||||
|
codedWidth: width || 960,
|
||||||
|
codedHeight: height || 540,
|
||||||
|
hardwareAcceleration: 'prefer-hardware',
|
||||||
|
optimizeForLatency: true
|
||||||
|
}
|
||||||
|
|
||||||
|
let chosenCfg = hwCfg
|
||||||
|
try {
|
||||||
|
const sup = await window.VideoDecoder.isConfigSupported(hwCfg)
|
||||||
|
if (!sup.supported) {
|
||||||
|
const swCfg = { ...hwCfg, hardwareAcceleration: 'no-preference' }
|
||||||
|
const sup2 = await window.VideoDecoder.isConfigSupported(swCfg)
|
||||||
|
if (!sup2.supported) {
|
||||||
|
// Transparently fall back to zero-buffering fMP4 MSE GPU decode
|
||||||
|
decodeEngine.value = 'mse'
|
||||||
|
if (ws === socket && !destroyed && shouldStream.value) {
|
||||||
|
startStream(false)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
chosenCfg = swCfg
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
decodeEngine.value = 'mse'
|
||||||
|
if (ws === socket && !destroyed && shouldStream.value) {
|
||||||
|
startStream(false)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ws !== socket || destroyed) return
|
||||||
|
|
||||||
|
const dec = new window.VideoDecoder({
|
||||||
|
output: (frame) => {
|
||||||
|
try {
|
||||||
|
const cvs = canvasRef.value
|
||||||
|
if (cvs) {
|
||||||
|
const fw = frame.displayWidth || width || 960
|
||||||
|
const fh = frame.displayHeight || height || 540
|
||||||
|
if (cvs.width !== fw || cvs.height !== fh) {
|
||||||
|
cvs.width = fw
|
||||||
|
cvs.height = fh
|
||||||
|
}
|
||||||
|
const ctx = cvs.getContext('2d', { alpha: false, desynchronized: true })
|
||||||
|
if (ctx) {
|
||||||
|
ctx.drawImage(frame, 0, 0, fw, fh)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
streamStatus.value = 'playing'
|
||||||
|
hasRenderedFrame.value = true
|
||||||
|
} finally {
|
||||||
|
frame.close()
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error: () => {
|
||||||
|
// Recover cleanly on decoder error by falling back or reconnecting
|
||||||
|
wcGotKeyFrame = false
|
||||||
|
if (ws === socket && !destroyed && shouldStream.value) {
|
||||||
|
startStream(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
dec.configure(chosenCfg)
|
||||||
|
videoDecoder = dec
|
||||||
|
wcConfigured = true
|
||||||
|
wcGotKeyFrame = false
|
||||||
|
const queued = wcPendingFrames
|
||||||
|
wcPendingFrames = []
|
||||||
|
for (const pkt of queued) {
|
||||||
|
feedWebCodecsPacket(pkt)
|
||||||
|
}
|
||||||
|
} catch (_) {
|
||||||
|
decodeEngine.value = 'mse'
|
||||||
|
if (ws === socket && !destroyed && shouldStream.value) {
|
||||||
|
startStream(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function feedWebCodecsPacket(u8) {
|
||||||
|
if (u8.byteLength < 6) return
|
||||||
|
if (!wcConfigured || !videoDecoder || videoDecoder.state !== 'configured') {
|
||||||
|
if (wcPendingFrames.length < 30) {
|
||||||
|
wcPendingFrames.push(u8)
|
||||||
|
}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const isKey = u8[0] === 1
|
||||||
|
if (!wcGotKeyFrame) {
|
||||||
|
if (!isKey) return
|
||||||
|
wcGotKeyFrame = true
|
||||||
|
}
|
||||||
|
// Drop stale delta frames if browser decoder queue falls behind so latency stays near zero
|
||||||
|
if (!isKey && videoDecoder.decodeQueueSize > 6) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const payload = u8.subarray(1)
|
||||||
|
try {
|
||||||
|
videoDecoder.decode(
|
||||||
|
new window.EncodedVideoChunk({
|
||||||
|
type: isKey ? 'key' : 'delta',
|
||||||
|
timestamp: wcFrameSeq * 40000,
|
||||||
|
duration: 40000,
|
||||||
|
data: payload
|
||||||
|
})
|
||||||
|
)
|
||||||
|
wcFrameSeq++
|
||||||
|
} catch (_) {
|
||||||
|
wcGotKeyFrame = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- Mode 2: Zero-transcode fMP4 -> HTML5 <video> MSE GPU decoder (plain HTTP LAN fallback) ----
|
||||||
|
function flushQueue() {
|
||||||
|
if (!sourceBuffer || sourceBuffer.updating || !appendQueue.length) return
|
||||||
|
if (!mediaSource || mediaSource.readyState !== 'open') return
|
||||||
|
const nextBuf = appendQueue.shift()
|
||||||
|
try {
|
||||||
|
sourceBuffer.appendBuffer(nextBuf)
|
||||||
|
} catch (e) {
|
||||||
|
try {
|
||||||
|
if (sourceBuffer.buffered.length > 0) {
|
||||||
|
const end = sourceBuffer.buffered.end(sourceBuffer.buffered.length - 1)
|
||||||
|
sourceBuffer.remove(0, Math.max(0, end - 1))
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function syncLiveEdge() {
|
||||||
|
if (decodeEngine.value !== 'mse') return
|
||||||
|
const v = videoRef.value
|
||||||
|
if (!v || !v.buffered || !v.buffered.length) return
|
||||||
|
const start = v.buffered.start(0)
|
||||||
|
const end = v.buffered.end(v.buffered.length - 1)
|
||||||
|
if (end > 0 && (end - v.currentTime > 0.02 || v.currentTime < start || v.currentTime === 0)) {
|
||||||
|
try {
|
||||||
|
v.currentTime = Math.max(start, end - 0.004)
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
if (v.paused && streamEnabled.value) {
|
||||||
|
v.play().catch(() => {})
|
||||||
|
}
|
||||||
|
if (sourceBuffer && !sourceBuffer.updating && end - start > 10) {
|
||||||
|
try {
|
||||||
|
sourceBuffer.remove(start, end - 2)
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function initMediaSource(mime, width, height) {
|
||||||
|
cleanupMse()
|
||||||
|
if (typeof MediaSource === 'undefined') {
|
||||||
|
streamStatus.value = 'error'
|
||||||
|
streamErr.value = '当前浏览器不支持 MediaSource (MSE) 播放'
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const chosenMime = MediaSource.isTypeSupported(mime)
|
||||||
|
? mime
|
||||||
|
: 'video/mp4; codecs="avc1.42E01E"'
|
||||||
|
|
||||||
|
videoMeta.value = `${width}×${height}`
|
||||||
|
|
||||||
|
const ms = new MediaSource()
|
||||||
|
mediaSource = ms
|
||||||
|
mediaObjectUrl = URL.createObjectURL(ms)
|
||||||
|
if (videoRef.value) {
|
||||||
|
videoRef.value.src = mediaObjectUrl
|
||||||
|
}
|
||||||
|
|
||||||
|
ms.addEventListener('sourceopen', () => {
|
||||||
|
if (mediaSource !== ms) return
|
||||||
|
try {
|
||||||
|
const sb = ms.addSourceBuffer(chosenMime)
|
||||||
|
sb.mode = 'sequence'
|
||||||
|
sb.addEventListener('updateend', () => {
|
||||||
|
syncLiveEdge()
|
||||||
|
flushQueue()
|
||||||
|
})
|
||||||
|
sourceBuffer = sb
|
||||||
|
flushQueue()
|
||||||
|
} catch (e) {
|
||||||
|
streamStatus.value = 'error'
|
||||||
|
streamErr.value = `MSE 初始化失败: ${e.message}`
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function startStream(silentReconnect = false) {
|
||||||
|
stopStream(!silentReconnect)
|
||||||
|
if (destroyed || !shouldStream.value || !props.device?.device_id) return
|
||||||
|
|
||||||
|
streamStatus.value = 'connecting'
|
||||||
|
streamErr.value = ''
|
||||||
|
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
|
||||||
|
const fmt = decodeEngine.value === 'webcodecs' ? 'h264' : 'fmp4'
|
||||||
|
const url = `${proto}://${location.host}/ws/lan-debug/${encodeURIComponent(props.device.device_id)}/video?quality=${quality.value}&format=${fmt}`
|
||||||
|
|
||||||
|
const socket = new WebSocket(url)
|
||||||
|
socket.binaryType = 'arraybuffer'
|
||||||
|
ws = socket
|
||||||
|
|
||||||
|
socket.onmessage = (ev) => {
|
||||||
|
if (ws !== socket) return
|
||||||
|
if (typeof ev.data === 'string') {
|
||||||
|
try {
|
||||||
|
const msg = JSON.parse(ev.data)
|
||||||
|
if (msg.type === 'ping') return
|
||||||
|
if (msg.type === 'init_h264' && decodeEngine.value === 'webcodecs') {
|
||||||
|
initWebCodecsDecoder(msg.codec || 'avc1.42c029', msg.width || 960, msg.height || 540, socket)
|
||||||
|
} else if (msg.type === 'init' && decodeEngine.value === 'mse') {
|
||||||
|
initMediaSource(msg.mime || 'video/mp4; codecs="avc1.42c029"', msg.width || 960, msg.height || 540)
|
||||||
|
} else if (msg.type === 'error') {
|
||||||
|
streamStatus.value = 'error'
|
||||||
|
streamErr.value = msg.message || '视频流异常'
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (ev.data instanceof ArrayBuffer) {
|
||||||
|
bytesWindow += ev.data.byteLength
|
||||||
|
if (decodeEngine.value === 'webcodecs') {
|
||||||
|
feedWebCodecsPacket(new Uint8Array(ev.data))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (ev.data.byteLength > 100 && streamStatus.value !== 'playing') {
|
||||||
|
const header = new Uint8Array(ev.data, 0, Math.min(8, ev.data.byteLength))
|
||||||
|
const isFtyp =
|
||||||
|
header.length >= 8 &&
|
||||||
|
header[4] === 0x66 &&
|
||||||
|
header[5] === 0x74 &&
|
||||||
|
header[6] === 0x79 &&
|
||||||
|
header[7] === 0x70
|
||||||
|
if (!isFtyp) {
|
||||||
|
streamStatus.value = 'playing'
|
||||||
|
hasRenderedFrame.value = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (appendQueue.length > 80) {
|
||||||
|
startStream(true)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
appendQueue.push(new Uint8Array(ev.data))
|
||||||
|
flushQueue()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.onerror = () => {
|
||||||
|
if (ws !== socket) return
|
||||||
|
if (!hasRenderedFrame.value) {
|
||||||
|
streamStatus.value = 'error'
|
||||||
|
streamErr.value = 'WebSocket 视频流连接异常,正在自动重连…'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
socket.onclose = () => {
|
||||||
|
if (ws !== socket) return
|
||||||
|
ws = null
|
||||||
|
if (!destroyed && shouldStream.value) {
|
||||||
|
streamStatus.value = 'connecting'
|
||||||
|
clearTimeout(reconnectTimer)
|
||||||
|
reconnectTimer = setTimeout(() => {
|
||||||
|
if (!destroyed && shouldStream.value) startStream(true)
|
||||||
|
}, 1200)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleStream() {
|
||||||
|
streamEnabled.value = !streamEnabled.value
|
||||||
|
if (streamEnabled.value && collapsed.value) {
|
||||||
|
collapsed.value = false
|
||||||
|
localStorage.setItem(COLLAPSE_KEY, '0')
|
||||||
|
}
|
||||||
|
// Actual start/stop is driven by the shouldStream watcher
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleFullscreen() {
|
||||||
|
const el = stageRef.value
|
||||||
|
if (!el) return
|
||||||
|
if (document.fullscreenElement) {
|
||||||
|
document.exitFullscreen().catch(() => {})
|
||||||
|
} else {
|
||||||
|
el.requestFullscreen?.().catch(() => {})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onScreenClick(event) {
|
||||||
|
const surface = decodeEngine.value === 'webcodecs' ? canvasRef.value : videoRef.value
|
||||||
|
if (!surface) return
|
||||||
|
const rect = surface.getBoundingClientRect()
|
||||||
|
if (!rect.width || !rect.height) return
|
||||||
|
|
||||||
|
const vidW =
|
||||||
|
(decodeEngine.value === 'webcodecs' ? surface.width : surface.videoWidth) ||
|
||||||
|
Number(props.device?.display_profile?.width_px || 1920)
|
||||||
|
const vidH =
|
||||||
|
(decodeEngine.value === 'webcodecs' ? surface.height : surface.videoHeight) ||
|
||||||
|
Number(props.device?.display_profile?.height_px || 1080)
|
||||||
|
const boxRatio = rect.width / rect.height
|
||||||
|
const vidRatio = vidW / vidH
|
||||||
|
|
||||||
|
let drawW = rect.width
|
||||||
|
let drawH = rect.height
|
||||||
|
let offsetX = 0
|
||||||
|
let offsetY = 0
|
||||||
|
if (vidRatio > boxRatio) {
|
||||||
|
drawH = rect.width / vidRatio
|
||||||
|
offsetY = (rect.height - drawH) / 2
|
||||||
|
} else {
|
||||||
|
drawW = rect.height * vidRatio
|
||||||
|
offsetX = (rect.width - drawW) / 2
|
||||||
|
}
|
||||||
|
|
||||||
|
const relX = Math.max(0, Math.min(1, (event.clientX - rect.left - offsetX) / drawW))
|
||||||
|
const relY = Math.max(0, Math.min(1, (event.clientY - rect.top - offsetY) / drawH))
|
||||||
|
|
||||||
|
const realW = Number(props.device?.display_profile?.width_px || vidW || 1920)
|
||||||
|
const realH = Number(props.device?.display_profile?.height_px || vidH || 1080)
|
||||||
|
const realX = Math.max(0, Math.min(realW - 1, Math.round(relX * realW)))
|
||||||
|
const realY = Math.max(0, Math.min(realH - 1, Math.round(relY * realH)))
|
||||||
|
|
||||||
|
tapRipple.value = {
|
||||||
|
left: `${((offsetX + relX * drawW) / rect.width) * 100}%`,
|
||||||
|
top: `${((offsetY + relY * drawH) / rect.height) * 100}%`
|
||||||
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
tapRipple.value = null
|
||||||
|
}, 420)
|
||||||
|
|
||||||
|
try {
|
||||||
|
await hubApi.lanAdbAction(props.device.device_id, 'tap', { x: realX, y: realY })
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `点击控制失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function sendKey(key) {
|
||||||
|
try {
|
||||||
|
if (key === 'WAKE') {
|
||||||
|
await hubApi.lanAdbAction(props.device.device_id, 'screen_wake')
|
||||||
|
} else {
|
||||||
|
await hubApi.lanAdbAction(props.device.device_id, 'keyevent', { key })
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `遥控指令失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function doWirelessPair() {
|
||||||
|
if (!pairAddr.value.trim() || !pairCode.value.trim()) {
|
||||||
|
emit('toast', '请填写配对地址 (IP:端口) 与 6 位配对码')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
pairing.value = true
|
||||||
|
try {
|
||||||
|
const r = await hubApi.pairWirelessAdb(pairAddr.value.trim(), pairCode.value.trim(), props.device.device_id)
|
||||||
|
if (r.ok) {
|
||||||
|
pairAddr.value = ''
|
||||||
|
pairCode.value = ''
|
||||||
|
adbLatched.value = true
|
||||||
|
emit('toast', `无线 ADB 配对成功!(${r.adb_serial || '已连接'})`)
|
||||||
|
emit('refresh')
|
||||||
|
} else {
|
||||||
|
emit('toast', `配对失败: ${r.error || r.output}`)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `配对失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
pairing.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.device?.device_id,
|
||||||
|
() => {
|
||||||
|
adbLatched.value = !!props.device?.adb_connected
|
||||||
|
// Switching device always returns to the default paused state
|
||||||
|
streamEnabled.value = false
|
||||||
|
stopStream(true)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.device?.adb_connected,
|
||||||
|
(val) => {
|
||||||
|
if (val && !adbLatched.value) {
|
||||||
|
adbLatched.value = true
|
||||||
|
if (shouldStream.value) startStream(false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
watch(shouldStream, (active) => {
|
||||||
|
if (active) startStream(false)
|
||||||
|
else stopStream(true)
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(quality, () => {
|
||||||
|
if (shouldStream.value) startStream(false)
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
if (shouldStream.value) startStream(false)
|
||||||
|
statsTimer = setInterval(() => {
|
||||||
|
bitrateKbps.value = Math.round((bytesWindow * 8) / 1000)
|
||||||
|
bytesWindow = 0
|
||||||
|
if (streamStatus.value === 'playing' && decodeEngine.value === 'mse') {
|
||||||
|
syncLiveEdge()
|
||||||
|
}
|
||||||
|
}, 1000)
|
||||||
|
})
|
||||||
|
|
||||||
|
onUnmounted(() => {
|
||||||
|
destroyed = true
|
||||||
|
clearInterval(statsTimer)
|
||||||
|
stopStream(true)
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="panel-card" :class="{ 'is-collapsed': collapsed }">
|
||||||
|
<div class="mirror-header">
|
||||||
|
<div class="title-left">
|
||||||
|
<button
|
||||||
|
class="collapse-btn"
|
||||||
|
:title="collapsed ? '展开设备界面' : '折叠设备界面(同时暂停投屏)'"
|
||||||
|
@click="toggleCollapse"
|
||||||
|
>
|
||||||
|
<span class="chev" :class="{ open: !collapsed }">▸</span>
|
||||||
|
</button>
|
||||||
|
<span class="title-main" @click="toggleCollapse">设备界面(H.264 浏览器 GPU 硬解)</span>
|
||||||
|
<span class="pill" :class="hasAdb ? 'online' : 'offline'">
|
||||||
|
{{ hasAdb ? 'ADB已连接' : 'ADB未连接' }}
|
||||||
|
</span>
|
||||||
|
<span
|
||||||
|
class="pill engine-pill"
|
||||||
|
:class="decodeEngine === 'webcodecs' ? 'online' : ''"
|
||||||
|
:title="engineBadgeTitle"
|
||||||
|
>
|
||||||
|
{{ engineBadgeText }}
|
||||||
|
</span>
|
||||||
|
<span class="pill live-pill" :class="streamStatus === 'playing' ? 'online' : ''">
|
||||||
|
<span class="live-dot" :class="{ active: streamStatus === 'playing' }"></span>
|
||||||
|
<span class="mono tabular">{{ streamStatus === 'playing' ? `LIVE ${bitrateKbps} kbps` : !streamEnabled ? '已暂停' : (hasRenderedFrame ? '重连中…' : 'WAIT') }}</span>
|
||||||
|
</span>
|
||||||
|
<span v-if="videoMeta && !collapsed" class="mono meta-txt">{{ videoMeta }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="hasAdb" class="mirror-controls">
|
||||||
|
<select v-if="!collapsed" v-model="quality" class="select-mini">
|
||||||
|
<option value="sd">流畅 640p</option>
|
||||||
|
<option value="hd">高清 960p</option>
|
||||||
|
<option value="fhd">超清 1280p</option>
|
||||||
|
</select>
|
||||||
|
<button class="btn btn-sm" :class="streamEnabled ? '' : 'btn-primary'" @click="toggleStream">
|
||||||
|
{{ streamEnabled ? '⏸ 暂停' : '▶ 播放' }}
|
||||||
|
</button>
|
||||||
|
<template v-if="!collapsed">
|
||||||
|
<button class="btn btn-sm" :disabled="!streamEnabled" @click="startStream(false)">重连</button>
|
||||||
|
<button class="btn btn-sm" :disabled="!shouldStream" @click="toggleFullscreen">全屏</button>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="hasAdb" v-show="!collapsed">
|
||||||
|
<!-- Fixed height video stage: wide full-width view, ZERO layout shift -->
|
||||||
|
<div ref="stageRef" class="screen-stage" :class="{ portrait: isPortrait }">
|
||||||
|
<canvas
|
||||||
|
v-show="decodeEngine === 'webcodecs'"
|
||||||
|
ref="canvasRef"
|
||||||
|
class="screen-video"
|
||||||
|
title="点击画面可直接模拟点击设备对应位置"
|
||||||
|
@click="onScreenClick"
|
||||||
|
></canvas>
|
||||||
|
|
||||||
|
<video
|
||||||
|
v-show="decodeEngine === 'mse'"
|
||||||
|
ref="videoRef"
|
||||||
|
class="screen-video"
|
||||||
|
autoplay
|
||||||
|
muted
|
||||||
|
playsinline
|
||||||
|
title="点击视频画面可直接模拟点击设备对应位置"
|
||||||
|
@loadeddata="streamStatus = 'playing'; hasRenderedFrame = true; syncLiveEdge()"
|
||||||
|
@click="onScreenClick"
|
||||||
|
></video>
|
||||||
|
|
||||||
|
<div v-if="!streamEnabled || !isActive || (!hasRenderedFrame && streamStatus !== 'playing')" class="screen-overlay">
|
||||||
|
<button v-if="!streamEnabled" class="btn btn-primary play-cta" @click="toggleStream">▶ 点击播放实时投屏</button>
|
||||||
|
<span v-else-if="!isActive">切回此页面自动恢复播放…</span>
|
||||||
|
<span v-else-if="streamStatus === 'error'">{{ streamErr || '流播异常,请点重连' }}</span>
|
||||||
|
<span v-else>正在建立零转码 H.264 GPU 视频流…</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<span v-if="tapRipple" class="tap-ripple" :style="{ left: tapRipple.left, top: tapRipple.top }"></span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="remote-bar">
|
||||||
|
<span class="remote-lbl">虚拟遥控 / 控屏(可直接点击画面操控):</span>
|
||||||
|
<div class="remote-keys">
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_DPAD_LEFT')">◀ 左</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_DPAD_UP')">▲ 上</button>
|
||||||
|
<button class="btn btn-primary btn-sm" @click="sendKey('KEYCODE_DPAD_CENTER')">OK</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_DPAD_DOWN')">▼ 下</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_DPAD_RIGHT')">▶ 右</button>
|
||||||
|
<span class="sep"></span>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_BACK')">返回</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_HOME')">主页</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('KEYCODE_MENU')">菜单</button>
|
||||||
|
<button class="btn btn-sm" @click="sendKey('WAKE')">亮屏</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else v-show="!collapsed" class="pair-box">
|
||||||
|
<p class="pair-tip">
|
||||||
|
该设备尚未建立局域网无线 ADB 连接。在设备的「开发者选项 → 无线调试 → 使用配对码配对设备」中查看地址与配对码,直接在此配对即可开启视频流播:
|
||||||
|
</p>
|
||||||
|
<div class="pair-row">
|
||||||
|
<input v-model="pairAddr" class="input mono" placeholder="配对地址,如 192.168.1.18:35239" />
|
||||||
|
<input v-model="pairCode" class="input mono" style="max-width:160px;" placeholder="6位配对码" />
|
||||||
|
<button class="btn btn-primary" :disabled="pairing" @click="doWirelessPair">
|
||||||
|
{{ pairing ? '配对中…' : '配对并连接' }}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.mirror-header {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 12px;
|
||||||
|
min-height: 34px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.title-left { display: flex; align-items: center; gap: 8px; flex-wrap: nowrap; overflow: hidden; }
|
||||||
|
.title-main { font-size: 14.5px; font-weight: 600; white-space: nowrap; cursor: pointer; user-select: none; }
|
||||||
|
.is-collapsed .mirror-header { margin-bottom: 0; }
|
||||||
|
.collapse-btn {
|
||||||
|
width: 24px;
|
||||||
|
height: 24px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 6px;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
cursor: pointer;
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
.collapse-btn:hover { border-color: var(--border-strong); color: var(--ink-primary); }
|
||||||
|
.chev { display: inline-block; font-size: 12px; transition: transform 0.16s ease; }
|
||||||
|
.chev.open { transform: rotate(90deg); }
|
||||||
|
.play-cta { pointer-events: auto; padding: 10px 22px; font-size: 14px; }
|
||||||
|
.meta-txt { font-size: 11.5px; color: var(--ink-muted); font-weight: 400; white-space: nowrap; }
|
||||||
|
.tabular { font-variant-numeric: tabular-nums; }
|
||||||
|
.engine-pill { font-size: 11px; flex-shrink: 0; cursor: help; }
|
||||||
|
.live-pill { gap: 6px; min-width: 118px; justify-content: center; flex-shrink: 0; }
|
||||||
|
.live-dot {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
border-radius: 50%;
|
||||||
|
background: var(--ink-muted);
|
||||||
|
}
|
||||||
|
.live-dot.active {
|
||||||
|
background: var(--accent-signal);
|
||||||
|
animation: blink 1.2s infinite ease-in-out;
|
||||||
|
}
|
||||||
|
@keyframes blink {
|
||||||
|
0%, 100% { opacity: 1; }
|
||||||
|
50% { opacity: 0.3; }
|
||||||
|
}
|
||||||
|
.mirror-controls { display: flex; align-items: center; gap: 6px; flex-shrink: 0; }
|
||||||
|
.select-mini {
|
||||||
|
background: var(--bg-input);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 7px;
|
||||||
|
padding: 5px 8px;
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.screen-stage {
|
||||||
|
position: relative;
|
||||||
|
width: 100%;
|
||||||
|
height: 490px;
|
||||||
|
background: #05070c;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 10px;
|
||||||
|
overflow: hidden;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
}
|
||||||
|
@media (max-width: 960px) {
|
||||||
|
.screen-stage { height: 320px; }
|
||||||
|
}
|
||||||
|
.screen-stage.portrait {
|
||||||
|
height: 500px;
|
||||||
|
}
|
||||||
|
.screen-stage:fullscreen {
|
||||||
|
aspect-ratio: auto;
|
||||||
|
width: 100vw;
|
||||||
|
height: 100vh;
|
||||||
|
border-radius: 0;
|
||||||
|
border: none;
|
||||||
|
}
|
||||||
|
.screen-video {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
display: block;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
object-fit: contain;
|
||||||
|
cursor: crosshair;
|
||||||
|
background: #05070c;
|
||||||
|
}
|
||||||
|
.screen-overlay {
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
z-index: 2;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
background: rgba(5, 7, 12, 0.78);
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
pointer-events: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tap-ripple {
|
||||||
|
position: absolute;
|
||||||
|
z-index: 3;
|
||||||
|
width: 26px;
|
||||||
|
height: 26px;
|
||||||
|
margin-left: -13px;
|
||||||
|
margin-top: -13px;
|
||||||
|
border-radius: 50%;
|
||||||
|
border: 2px solid var(--accent-signal);
|
||||||
|
background: rgba(45, 212, 191, 0.25);
|
||||||
|
pointer-events: none;
|
||||||
|
animation: ripple 0.42s ease-out forwards;
|
||||||
|
}
|
||||||
|
@keyframes ripple {
|
||||||
|
from { transform: scale(0.5); opacity: 1; }
|
||||||
|
to { transform: scale(1.8); opacity: 0; }
|
||||||
|
}
|
||||||
|
|
||||||
|
.remote-bar {
|
||||||
|
margin-top: 10px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
.remote-lbl { font-size: 12px; color: var(--ink-muted); }
|
||||||
|
.remote-keys { display: flex; flex-wrap: wrap; gap: 5px; align-items: center; }
|
||||||
|
.sep { width: 1px; height: 18px; background: var(--border-subtle); margin: 0 4px; }
|
||||||
|
|
||||||
|
.pair-box { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.pair-tip { margin: 0; font-size: 12.5px; color: var(--ink-muted); line-height: 1.55; }
|
||||||
|
.pair-row { display: flex; gap: 8px; flex-wrap: wrap; }
|
||||||
|
.pair-row .input { flex: 1; min-width: 180px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
<script setup>
|
||||||
|
import { ref, watch } from 'vue'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
globalConfig: { type: Object, default: null },
|
||||||
|
ota: { type: Object, default: null },
|
||||||
|
events: { type: Array, default: () => [] },
|
||||||
|
audits: { type: Array, default: () => [] }
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['config-saved', 'refresh', 'toast'])
|
||||||
|
|
||||||
|
const dirty = ref(false)
|
||||||
|
const saving = ref(false)
|
||||||
|
const form = ref({
|
||||||
|
enabled: false,
|
||||||
|
base_url: 'https://api.openai.com/v1',
|
||||||
|
api_key: '',
|
||||||
|
model: 'gpt-4o-mini',
|
||||||
|
max_retries: 3,
|
||||||
|
runtime_cooldown_sec: 30,
|
||||||
|
timeout_sec: 30,
|
||||||
|
telemetry_interval_sec: 3,
|
||||||
|
max_tool_steps: 30,
|
||||||
|
lan_debug_enabled: false
|
||||||
|
})
|
||||||
|
|
||||||
|
function loadFromProps(force = false) {
|
||||||
|
if (!props.globalConfig || (!force && dirty.value)) return
|
||||||
|
const r = props.globalConfig.repair_ai || {}
|
||||||
|
const chatAi = props.globalConfig.hub_chat_ai || {}
|
||||||
|
form.value = {
|
||||||
|
enabled: !!r.enabled,
|
||||||
|
base_url: r.base_url || 'https://api.openai.com/v1',
|
||||||
|
api_key: r.api_key || '',
|
||||||
|
model: r.model || 'gpt-4o-mini',
|
||||||
|
max_retries: r.max_retries ?? 3,
|
||||||
|
runtime_cooldown_sec: r.runtime_cooldown_sec ?? 30,
|
||||||
|
timeout_sec: r.timeout_sec ?? 30,
|
||||||
|
telemetry_interval_sec: props.globalConfig.telemetry_interval_sec ?? 3,
|
||||||
|
max_tool_steps: chatAi.max_tool_steps ?? 30,
|
||||||
|
lan_debug_enabled: !!props.globalConfig.lan_debug_enabled
|
||||||
|
}
|
||||||
|
dirty.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
watch(() => props.globalConfig, () => loadFromProps(false), { immediate: true })
|
||||||
|
|
||||||
|
async function saveGlobal() {
|
||||||
|
saving.value = true
|
||||||
|
try {
|
||||||
|
const prevChatAi = props.globalConfig?.hub_chat_ai || {}
|
||||||
|
const body = {
|
||||||
|
repair_ai: {
|
||||||
|
enabled: form.value.enabled,
|
||||||
|
base_url: form.value.base_url.trim(),
|
||||||
|
api_key: form.value.api_key.trim(),
|
||||||
|
model: form.value.model.trim(),
|
||||||
|
max_retries: Number(form.value.max_retries) || 3,
|
||||||
|
runtime_cooldown_sec: Number(form.value.runtime_cooldown_sec) || 30,
|
||||||
|
timeout_sec: Number(form.value.timeout_sec) || 30
|
||||||
|
},
|
||||||
|
hub_chat_ai: {
|
||||||
|
...prevChatAi,
|
||||||
|
max_tool_steps: Math.min(100, Math.max(1, Number(form.value.max_tool_steps) || 30))
|
||||||
|
},
|
||||||
|
lan_debug_enabled: form.value.lan_debug_enabled,
|
||||||
|
telemetry_interval_sec: Math.min(120, Math.max(1, Number(form.value.telemetry_interval_sec) || 3)),
|
||||||
|
theme: props.globalConfig?.theme || 'dark-glass',
|
||||||
|
auth_token: props.globalConfig?.auth_token || ''
|
||||||
|
}
|
||||||
|
const r = await hubApi.saveGlobalConfig(body)
|
||||||
|
dirty.value = false
|
||||||
|
emit('config-saved')
|
||||||
|
emit('refresh')
|
||||||
|
emit('toast', `全局默认配置已保存,已同步 ${r.pushed_devices} 台在线设备`)
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `保存失败: ${e.message}`)
|
||||||
|
} finally {
|
||||||
|
saving.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function pushOtaAll() {
|
||||||
|
try {
|
||||||
|
const r = await hubApi.pushOta(null)
|
||||||
|
emit('toast', `已向 ${r.pushed_devices} 台在线设备推送 OTA 更新通知`)
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `OTA 推送失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="global-scroll">
|
||||||
|
<div class="global-inner">
|
||||||
|
<div class="global-grid">
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title">
|
||||||
|
<span>全局默认「端侧修复 AI」配置</span>
|
||||||
|
<span v-if="dirty" class="pill amber">有未保存修改</span>
|
||||||
|
</div>
|
||||||
|
<p class="sub-tip">未在「设备列表」中单独配置的 Android 设备会自动继承此处配置。</p>
|
||||||
|
|
||||||
|
<label class="check-line">
|
||||||
|
<input v-model="form.enabled" type="checkbox" @change="dirty = true" />
|
||||||
|
默认启用端侧自动修复哨兵
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label class="field-label">OpenAI Base URL</label>
|
||||||
|
<input v-model="form.base_url" class="input mono" @input="dirty = true" />
|
||||||
|
|
||||||
|
<label class="field-label">API Key</label>
|
||||||
|
<input v-model="form.api_key" class="input mono" type="password" placeholder="sk-..." @input="dirty = true" />
|
||||||
|
|
||||||
|
<label class="field-label">Model</label>
|
||||||
|
<input v-model="form.model" class="input mono" @input="dirty = true" />
|
||||||
|
|
||||||
|
<div class="row-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">最大重试次数</label>
|
||||||
|
<input v-model.number="form.max_retries" class="input" type="number" @input="dirty = true" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">运行报错冷却(秒)</label>
|
||||||
|
<input v-model.number="form.runtime_cooldown_sec" class="input" type="number" @input="dirty = true" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="row-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">设备遥测采集间隔(秒 · 留存 7 天)</label>
|
||||||
|
<input v-model.number="form.telemetry_interval_sec" class="input" type="number" min="1" max="120" @input="dirty = true" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">AI 对话最大 MCP 工具轮数(默认 30)</label>
|
||||||
|
<input v-model.number="form.max_tool_steps" class="input" type="number" min="1" max="100" @input="dirty = true" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<label class="check-line" style="margin-top:14px;">
|
||||||
|
<input v-model="form.lan_debug_enabled" type="checkbox" @change="dirty = true" />
|
||||||
|
启用全局「仅限局域网」ADB 开发者调试 API
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<div class="btn-row">
|
||||||
|
<button class="btn btn-primary" :disabled="saving" @click="saveGlobal">
|
||||||
|
{{ saving ? '保存中…' : '保存全局配置并同步在线设备' }}
|
||||||
|
</button>
|
||||||
|
<button class="btn" @click="loadFromProps(true)">重新读取</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="right-col">
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title"><span>App 自更新分发(OTA)</span></div>
|
||||||
|
<div v-if="ota?.available" class="ota-meta mono">
|
||||||
|
v{{ ota.version_name }} (build {{ ota.version_code }}) · {{ (ota.size_bytes / 1048576).toFixed(2) }} MB · SHA256 {{ ota.sha256.slice(0, 14) }}…
|
||||||
|
</div>
|
||||||
|
<div v-else class="sub-tip">尚未发布 APK(运行 ./android/build_apk.sh 自动发布)</div>
|
||||||
|
<div class="btn-row">
|
||||||
|
<button class="btn btn-primary btn-sm" @click="pushOtaAll">全量推送 OTA 至所有在线设备</button>
|
||||||
|
<a v-if="ota?.available" :href="ota.download_path" class="btn btn-sm" style="text-decoration:none;">下载最新 APK</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title"><span>待处理反向事件({{ events.length }})</span></div>
|
||||||
|
<div class="log-box">
|
||||||
|
<div v-if="!events.length" class="sub-tip">暂无待处理事件</div>
|
||||||
|
<div v-for="e in events" :key="e.event_id" class="log-line">
|
||||||
|
<span class="pill">{{ e.event_type }}</span>
|
||||||
|
<strong style="margin:0 6px;">{{ e.device_id }}</strong>
|
||||||
|
<span class="mono muted">{{ JSON.stringify(e.payload) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="panel-card">
|
||||||
|
<div class="panel-title"><span>交互与审计日志</span></div>
|
||||||
|
<div class="log-box tall">
|
||||||
|
<div v-if="!audits.length" class="sub-tip">暂无审计记录</div>
|
||||||
|
<div v-for="a in audits" :key="a.id" class="log-line">
|
||||||
|
<span class="pill">{{ a.category }}</span>
|
||||||
|
<strong style="margin:0 6px;">{{ a.device_id || 'hub' }}</strong>
|
||||||
|
<span>{{ a.summary }}</span>
|
||||||
|
<span class="mono muted" style="margin-left:8px;">{{ new Date(a.created_at_ms).toLocaleTimeString() }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.global-scroll {
|
||||||
|
flex: 1;
|
||||||
|
min-height: 0;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 20px 24px 36px;
|
||||||
|
}
|
||||||
|
.global-inner {
|
||||||
|
max-width: 1220px;
|
||||||
|
margin: 0 auto;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 16px;
|
||||||
|
}
|
||||||
|
.global-grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: 1.05fr 1fr;
|
||||||
|
gap: 16px;
|
||||||
|
align-items: start;
|
||||||
|
}
|
||||||
|
@media (max-width: 900px) {
|
||||||
|
.global-grid { grid-template-columns: 1fr; }
|
||||||
|
}
|
||||||
|
.right-col { display: flex; flex-direction: column; gap: 16px; }
|
||||||
|
.sub-tip { font-size: 12.5px; color: var(--ink-muted); margin: 0 0 10px; }
|
||||||
|
.check-line { display: flex; align-items: center; gap: 7px; font-size: 13px; cursor: pointer; }
|
||||||
|
.row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
|
||||||
|
.btn-row { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 14px; }
|
||||||
|
.ota-meta { font-size: 12.5px; color: var(--ink-secondary); }
|
||||||
|
.log-box { max-height: 220px; overflow-y: auto; }
|
||||||
|
.log-box.tall { max-height: 340px; }
|
||||||
|
.log-line {
|
||||||
|
padding: 7px 0;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
font-size: 12.5px;
|
||||||
|
word-break: break-all;
|
||||||
|
}
|
||||||
|
.muted { color: var(--ink-muted); }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,334 @@
|
|||||||
|
<script setup>
|
||||||
|
import { computed, ref, watch } from 'vue'
|
||||||
|
import { hubApi } from '../api'
|
||||||
|
|
||||||
|
const props = defineProps({
|
||||||
|
groups: { type: Array, default: () => [] }
|
||||||
|
})
|
||||||
|
const emit = defineEmits(['changed', 'send-prompt', 'toast'])
|
||||||
|
|
||||||
|
const selectedGroupId = ref(null)
|
||||||
|
|
||||||
|
// Group Modal
|
||||||
|
const showGroupModal = ref(false)
|
||||||
|
const editingGroupId = ref(null)
|
||||||
|
const groupForm = ref({ name: '', sort_order: 10 })
|
||||||
|
|
||||||
|
// Prompt Modal
|
||||||
|
const showPromptModal = ref(false)
|
||||||
|
const editingPromptId = ref(null)
|
||||||
|
const promptForm = ref({ group_id: '', title: '', content: '', sort_order: 10 })
|
||||||
|
|
||||||
|
watch(
|
||||||
|
() => props.groups,
|
||||||
|
(list) => {
|
||||||
|
if (!list.length) {
|
||||||
|
selectedGroupId.value = null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
if (!selectedGroupId.value || !list.some((g) => g.group_id === selectedGroupId.value)) {
|
||||||
|
selectedGroupId.value = list[0].group_id
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ immediate: true }
|
||||||
|
)
|
||||||
|
|
||||||
|
const activeGroup = computed(() => props.groups.find((g) => g.group_id === selectedGroupId.value) || null)
|
||||||
|
|
||||||
|
function openCreateGroup() {
|
||||||
|
editingGroupId.value = null
|
||||||
|
groupForm.value = { name: '', sort_order: (props.groups.length + 1) * 10 }
|
||||||
|
showGroupModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditGroup(g) {
|
||||||
|
editingGroupId.value = g.group_id
|
||||||
|
groupForm.value = { name: g.name, sort_order: g.sort_order ?? 0 }
|
||||||
|
showGroupModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveGroup() {
|
||||||
|
const name = groupForm.value.name.trim()
|
||||||
|
if (!name) {
|
||||||
|
emit('toast', '请输入分组名称')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
if (editingGroupId.value) {
|
||||||
|
await hubApi.updatePromptGroup(editingGroupId.value, name, Number(groupForm.value.sort_order) || 0)
|
||||||
|
emit('toast', '分组已更新')
|
||||||
|
} else {
|
||||||
|
const r = await hubApi.createPromptGroup(name, Number(groupForm.value.sort_order) || 0)
|
||||||
|
selectedGroupId.value = r.group.group_id
|
||||||
|
emit('toast', '分组已创建')
|
||||||
|
}
|
||||||
|
showGroupModal.value = false
|
||||||
|
emit('changed')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `保存分组失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeGroup(g) {
|
||||||
|
if (!confirm(`确定删除分组「${g.name}」及其下的 ${g.prompts?.length || 0} 条快捷指令吗?`)) return
|
||||||
|
try {
|
||||||
|
await hubApi.deletePromptGroup(g.group_id)
|
||||||
|
emit('toast', '分组已删除')
|
||||||
|
emit('changed')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `删除失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function openCreatePrompt() {
|
||||||
|
if (!props.groups.length) {
|
||||||
|
emit('toast', '请先新建至少一个分组')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
editingPromptId.value = null
|
||||||
|
const gid = selectedGroupId.value || props.groups[0].group_id
|
||||||
|
const curLen = activeGroup.value?.prompts?.length || 0
|
||||||
|
promptForm.value = { group_id: gid, title: '', content: '', sort_order: (curLen + 1) * 10 }
|
||||||
|
showPromptModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
function openEditPrompt(p) {
|
||||||
|
editingPromptId.value = p.prompt_id
|
||||||
|
promptForm.value = {
|
||||||
|
group_id: p.group_id,
|
||||||
|
title: p.title,
|
||||||
|
content: p.content,
|
||||||
|
sort_order: p.sort_order ?? 0
|
||||||
|
}
|
||||||
|
showPromptModal.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
async function savePrompt() {
|
||||||
|
const title = promptForm.value.title.trim()
|
||||||
|
const content = promptForm.value.content.trim()
|
||||||
|
if (!title || !content) {
|
||||||
|
emit('toast', '请填写指令标题与内容')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const body = {
|
||||||
|
group_id: promptForm.value.group_id,
|
||||||
|
title,
|
||||||
|
content,
|
||||||
|
sort_order: Number(promptForm.value.sort_order) || 0
|
||||||
|
}
|
||||||
|
if (editingPromptId.value) {
|
||||||
|
await hubApi.updatePrompt(editingPromptId.value, body)
|
||||||
|
emit('toast', '快捷指令已更新')
|
||||||
|
} else {
|
||||||
|
await hubApi.createPrompt(body)
|
||||||
|
emit('toast', '快捷指令已创建')
|
||||||
|
}
|
||||||
|
showPromptModal.value = false
|
||||||
|
selectedGroupId.value = body.group_id
|
||||||
|
emit('changed')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `保存指令失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removePrompt(p) {
|
||||||
|
if (!confirm(`确定删除快捷指令「${p.title}」吗?`)) return
|
||||||
|
try {
|
||||||
|
await hubApi.deletePrompt(p.prompt_id)
|
||||||
|
emit('toast', '快捷指令已删除')
|
||||||
|
emit('changed')
|
||||||
|
} catch (e) {
|
||||||
|
emit('toast', `删除失败: ${e.message}`)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<template>
|
||||||
|
<div class="pm-layout">
|
||||||
|
<aside class="pm-sidebar">
|
||||||
|
<div class="pm-head">
|
||||||
|
<span>指令分组({{ groups.length }})</span>
|
||||||
|
<button class="btn btn-primary btn-sm" @click="openCreateGroup">+ 新建分组</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="!groups.length" class="pm-empty">尚无分组,点击右上角新建。</div>
|
||||||
|
<div
|
||||||
|
v-for="g in groups"
|
||||||
|
:key="g.group_id"
|
||||||
|
class="grp-item"
|
||||||
|
:class="{ active: g.group_id === selectedGroupId }"
|
||||||
|
@click="selectedGroupId = g.group_id"
|
||||||
|
>
|
||||||
|
<div class="grp-top">
|
||||||
|
<strong>{{ g.name }}</strong>
|
||||||
|
<span class="pill">{{ g.prompts?.length || 0 }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="grp-ops" @click.stop>
|
||||||
|
<button class="btn btn-ghost btn-sm" @click="openEditGroup(g)">改名</button>
|
||||||
|
<button class="btn btn-ghost btn-sm danger-txt" @click="removeGroup(g)">删除</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<section class="pm-main">
|
||||||
|
<div class="pm-main-inner">
|
||||||
|
<div class="pm-toolbar">
|
||||||
|
<div>
|
||||||
|
<h2>{{ activeGroup ? activeGroup.name : '快捷指令管理' }}</h2>
|
||||||
|
<p class="sub">所有分组和指令持久化存储在中心桥 SQLite,AI 会话测试侧边栏实时同步。</p>
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" :disabled="!groups.length" @click="openCreatePrompt">
|
||||||
|
+ 新建快捷指令
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="activeGroup && !(activeGroup.prompts || []).length" class="panel-card empty-box">
|
||||||
|
当前分组暂无快捷指令,点击右上角「+ 新建快捷指令」添加常用测试语。
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="activeGroup" class="prompt-grid">
|
||||||
|
<div v-for="p in activeGroup.prompts" :key="p.prompt_id" class="panel-card prompt-card">
|
||||||
|
<div class="p-head">
|
||||||
|
<strong>{{ p.title }}</strong>
|
||||||
|
<span class="mono muted">排序 {{ p.sort_order }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="p-content">{{ p.content }}</div>
|
||||||
|
<div class="p-actions">
|
||||||
|
<button class="btn btn-primary btn-sm" @click="emit('send-prompt', p.content)">发送到 AI 会话</button>
|
||||||
|
<button class="btn btn-sm" @click="openEditPrompt(p)">编辑</button>
|
||||||
|
<button class="btn btn-ghost btn-sm danger-txt" @click="removePrompt(p)">删除</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- Group Modal -->
|
||||||
|
<Teleport to="body">
|
||||||
|
<div v-if="showGroupModal" class="modal-backdrop" @click.self="showGroupModal = false">
|
||||||
|
<div class="modal-box" style="max-width:440px;">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>{{ editingGroupId ? '编辑分组' : '新建指令分组' }}</h3>
|
||||||
|
<button class="btn btn-ghost btn-sm" @click="showGroupModal = false">关闭</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<label class="field-label">分组名称</label>
|
||||||
|
<input v-model="groupForm.name" class="input" placeholder="例如:机顶盒日常巡检 / 告警压测" />
|
||||||
|
<label class="field-label">排序权重(越小越靠前)</label>
|
||||||
|
<input v-model.number="groupForm.sort_order" class="input" type="number" />
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button class="btn" @click="showGroupModal = false">取消</button>
|
||||||
|
<button class="btn btn-primary" @click="saveGroup">保存</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
|
||||||
|
<!-- Prompt Modal -->
|
||||||
|
<Teleport to="body">
|
||||||
|
<div v-if="showPromptModal" class="modal-backdrop" @click.self="showPromptModal = false">
|
||||||
|
<div class="modal-box">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3>{{ editingPromptId ? '编辑快捷指令' : '新建快捷指令' }}</h3>
|
||||||
|
<button class="btn btn-ghost btn-sm" @click="showPromptModal = false">关闭</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<div class="row-2">
|
||||||
|
<div>
|
||||||
|
<label class="field-label">所属分组</label>
|
||||||
|
<select v-model="promptForm.group_id" class="select">
|
||||||
|
<option v-for="g in groups" :key="g.group_id" :value="g.group_id">{{ g.name }}</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="field-label">排序权重(越小越靠前)</label>
|
||||||
|
<input v-model.number="promptForm.sort_order" class="input" type="number" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<label class="field-label">指令标题(按钮显示名称)</label>
|
||||||
|
<input v-model="promptForm.title" class="input" placeholder="例如:巡检客厅机顶盒并画仪表盘" />
|
||||||
|
<label class="field-label">完整指令内容(发送给 AI 的话术)</label>
|
||||||
|
<textarea v-model="promptForm.content" class="textarea" rows="5" placeholder="输入发给 AI 的详细要求..."></textarea>
|
||||||
|
</div>
|
||||||
|
<div class="modal-footer">
|
||||||
|
<button class="btn" @click="showPromptModal = false">取消</button>
|
||||||
|
<button class="btn btn-primary" @click="savePrompt">保存指令</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Teleport>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.pm-layout { display: flex; flex: 1; min-height: 0; height: 100%; }
|
||||||
|
.pm-sidebar {
|
||||||
|
width: 270px;
|
||||||
|
flex-shrink: 0;
|
||||||
|
background: #11151e;
|
||||||
|
border-right: 1px solid var(--border-subtle);
|
||||||
|
padding: 14px;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
@media (max-width: 860px) {
|
||||||
|
.pm-layout { flex-direction: column; overflow-y: auto; }
|
||||||
|
.pm-sidebar { width: 100%; border-right: none; border-bottom: 1px solid var(--border-subtle); }
|
||||||
|
}
|
||||||
|
.pm-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
.pm-empty { font-size: 12.5px; color: var(--ink-muted); }
|
||||||
|
.grp-item {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
margin-bottom: 8px;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
.grp-item:hover { border-color: var(--border-strong); }
|
||||||
|
.grp-item.active { border-color: var(--accent-signal); background: #182230; }
|
||||||
|
.grp-top { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||||
|
.grp-ops { display: flex; gap: 4px; margin-top: 6px; }
|
||||||
|
|
||||||
|
.pm-main { flex: 1; min-width: 0; overflow-y: auto; padding: 22px 26px 36px; }
|
||||||
|
.pm-main-inner { width: 100%; max-width: 1680px; margin: 0 auto; }
|
||||||
|
.pm-toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 16px;
|
||||||
|
margin-bottom: 18px;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
.pm-toolbar h2 { margin: 0 0 4px; font-size: 18px; }
|
||||||
|
.sub { margin: 0; font-size: 12.5px; color: var(--ink-muted); }
|
||||||
|
|
||||||
|
.empty-box { color: var(--ink-muted); text-align: center; padding: 36px 20px; }
|
||||||
|
.prompt-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 14px; }
|
||||||
|
.prompt-card { display: flex; flex-direction: column; gap: 10px; }
|
||||||
|
.p-head { display: flex; justify-content: space-between; align-items: center; gap: 8px; }
|
||||||
|
.p-content {
|
||||||
|
font-size: 13px;
|
||||||
|
line-height: 1.6;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
background: var(--bg-input);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 10px 12px;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
flex: 1;
|
||||||
|
}
|
||||||
|
.p-actions { display: flex; gap: 8px; align-items: center; }
|
||||||
|
.muted { color: var(--ink-muted); font-size: 11.5px; }
|
||||||
|
.danger-txt { color: #fca5a5; }
|
||||||
|
.row-2 { display: grid; grid-template-columns: 1.4fr 1fr; gap: 12px; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import App from './App.vue'
|
||||||
|
import './styles/theme.css'
|
||||||
|
|
||||||
|
createApp(App).mount('#app')
|
||||||
@@ -0,0 +1,276 @@
|
|||||||
|
:root {
|
||||||
|
--bg-canvas: #0e1117;
|
||||||
|
--bg-panel: #151a23;
|
||||||
|
--bg-elevated: #1c2330;
|
||||||
|
--bg-input: #0c1017;
|
||||||
|
--border-subtle: #252e3f;
|
||||||
|
--border-strong: #33415c;
|
||||||
|
--ink-primary: #e8edf5;
|
||||||
|
--ink-secondary: #b6c2d6;
|
||||||
|
--ink-muted: #7f8da6;
|
||||||
|
--accent-signal: #2dd4bf;
|
||||||
|
--accent-signal-dim: rgba(45, 212, 191, 0.14);
|
||||||
|
--status-amber: #f59e0b;
|
||||||
|
--status-amber-dim: rgba(245, 158, 11, 0.16);
|
||||||
|
--status-crimson: #ef4444;
|
||||||
|
--status-crimson-dim: rgba(239, 68, 68, 0.16);
|
||||||
|
--font-sans: "Inter", "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", system-ui, -apple-system, sans-serif;
|
||||||
|
--font-mono: "JetBrains Mono", "Fira Code", ui-monospace, SFMono-Regular, Menlo, monospace;
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
html, body, #app {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
height: 100%;
|
||||||
|
background: var(--bg-canvas);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
font-family: var(--font-sans);
|
||||||
|
font-size: 14px;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 7px;
|
||||||
|
height: 7px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-track {
|
||||||
|
background: transparent;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
background: #2a3447;
|
||||||
|
border-radius: 99px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb:hover {
|
||||||
|
background: #3a4760;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mono {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
}
|
||||||
|
|
||||||
|
.pill {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
padding: 3px 9px;
|
||||||
|
border-radius: 999px;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
}
|
||||||
|
.pill.online {
|
||||||
|
background: var(--accent-signal-dim);
|
||||||
|
color: var(--accent-signal);
|
||||||
|
border-color: rgba(45, 212, 191, 0.3);
|
||||||
|
}
|
||||||
|
.pill.offline {
|
||||||
|
background: rgba(127, 141, 166, 0.12);
|
||||||
|
color: var(--ink-muted);
|
||||||
|
}
|
||||||
|
.pill.amber {
|
||||||
|
background: var(--status-amber-dim);
|
||||||
|
color: var(--status-amber);
|
||||||
|
border-color: rgba(245, 158, 11, 0.3);
|
||||||
|
}
|
||||||
|
.pill.danger {
|
||||||
|
background: var(--status-crimson-dim);
|
||||||
|
color: #fca5a5;
|
||||||
|
border-color: rgba(239, 68, 68, 0.35);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
gap: 6px;
|
||||||
|
padding: 8px 14px;
|
||||||
|
border-radius: 9px;
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
font-family: inherit;
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background 0.14s, border-color 0.14s, opacity 0.14s;
|
||||||
|
}
|
||||||
|
.btn:hover:not(:disabled) {
|
||||||
|
background: #242d3e;
|
||||||
|
border-color: #465775;
|
||||||
|
}
|
||||||
|
.btn:disabled {
|
||||||
|
opacity: 0.5;
|
||||||
|
cursor: not-allowed;
|
||||||
|
}
|
||||||
|
.btn-primary {
|
||||||
|
background: var(--accent-signal);
|
||||||
|
color: #06211e;
|
||||||
|
border-color: var(--accent-signal);
|
||||||
|
}
|
||||||
|
.btn-primary:hover:not(:disabled) {
|
||||||
|
background: #5eead4;
|
||||||
|
border-color: #5eead4;
|
||||||
|
}
|
||||||
|
.btn-danger {
|
||||||
|
background: var(--status-crimson);
|
||||||
|
color: #fff;
|
||||||
|
border-color: var(--status-crimson);
|
||||||
|
}
|
||||||
|
.btn-danger:hover:not(:disabled) {
|
||||||
|
background: #f87171;
|
||||||
|
border-color: #f87171;
|
||||||
|
}
|
||||||
|
.btn-ghost {
|
||||||
|
background: transparent;
|
||||||
|
border-color: transparent;
|
||||||
|
color: var(--ink-secondary);
|
||||||
|
}
|
||||||
|
.btn-ghost:hover:not(:disabled) {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
}
|
||||||
|
.btn-sm {
|
||||||
|
padding: 5px 10px;
|
||||||
|
font-size: 12px;
|
||||||
|
border-radius: 7px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.field-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--ink-muted);
|
||||||
|
margin: 10px 0 5px;
|
||||||
|
}
|
||||||
|
.input, .textarea, .select {
|
||||||
|
width: 100%;
|
||||||
|
background: var(--bg-input);
|
||||||
|
color: var(--ink-primary);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 8px;
|
||||||
|
padding: 9px 11px;
|
||||||
|
font-size: 13.5px;
|
||||||
|
font-family: inherit;
|
||||||
|
outline: none;
|
||||||
|
transition: border-color 0.15s;
|
||||||
|
}
|
||||||
|
.input:focus, .textarea:focus, .select:focus {
|
||||||
|
border-color: var(--accent-signal);
|
||||||
|
}
|
||||||
|
.textarea {
|
||||||
|
resize: vertical;
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.panel-card {
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 12px;
|
||||||
|
padding: 16px 18px;
|
||||||
|
}
|
||||||
|
.panel-title {
|
||||||
|
margin: 0 0 12px;
|
||||||
|
font-size: 14.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--ink-primary);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-backdrop {
|
||||||
|
position: fixed;
|
||||||
|
inset: 0;
|
||||||
|
background: rgba(5, 8, 14, 0.72);
|
||||||
|
backdrop-filter: blur(4px);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
z-index: 100;
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
.modal-box {
|
||||||
|
width: 100%;
|
||||||
|
max-width: 580px;
|
||||||
|
background: var(--bg-panel);
|
||||||
|
border: 1px solid var(--border-strong);
|
||||||
|
border-radius: 14px;
|
||||||
|
box-shadow: 0 24px 64px rgba(0, 0, 0, 0.55);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.modal-header {
|
||||||
|
padding: 16px 20px;
|
||||||
|
border-bottom: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
}
|
||||||
|
.modal-header h3 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 15.5px;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
.modal-body {
|
||||||
|
padding: 16px 20px;
|
||||||
|
max-height: 72vh;
|
||||||
|
overflow-y: auto;
|
||||||
|
}
|
||||||
|
.modal-footer {
|
||||||
|
padding: 12px 20px;
|
||||||
|
border-top: 1px solid var(--border-subtle);
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
gap: 8px;
|
||||||
|
background: #111620;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Markdown inside chat */
|
||||||
|
.md-body p { margin: 0 0 10px; line-height: 1.68; }
|
||||||
|
.md-body p:last-child { margin-bottom: 0; }
|
||||||
|
.md-body h1, .md-body h2, .md-body h3 { margin: 14px 0 8px; font-weight: 600; color: var(--ink-primary); }
|
||||||
|
.md-body h3 { font-size: 15px; }
|
||||||
|
.md-body ul, .md-body ol { margin: 6px 0 10px; padding-left: 20px; line-height: 1.65; }
|
||||||
|
.md-body code {
|
||||||
|
font-family: var(--font-mono);
|
||||||
|
font-size: 12.5px;
|
||||||
|
background: rgba(148, 163, 184, 0.14);
|
||||||
|
padding: 2px 5px;
|
||||||
|
border-radius: 5px;
|
||||||
|
color: #99f6e4;
|
||||||
|
}
|
||||||
|
.md-body pre {
|
||||||
|
background: #0a0d14;
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
border-radius: 9px;
|
||||||
|
padding: 12px 14px;
|
||||||
|
overflow-x: auto;
|
||||||
|
margin: 10px 0;
|
||||||
|
}
|
||||||
|
.md-body pre code {
|
||||||
|
background: transparent;
|
||||||
|
padding: 0;
|
||||||
|
color: #dbe6f7;
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.55;
|
||||||
|
}
|
||||||
|
.md-body table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
width: 100%;
|
||||||
|
margin: 10px 0;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.md-body th, .md-body td {
|
||||||
|
border: 1px solid var(--border-subtle);
|
||||||
|
padding: 6px 10px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
.md-body th {
|
||||||
|
background: var(--bg-elevated);
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
import path from 'path'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
base: '/admin/',
|
||||||
|
plugins: [vue()],
|
||||||
|
build: {
|
||||||
|
outDir: path.resolve(__dirname, '../app/admin/dist'),
|
||||||
|
emptyOutDir: true
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
host: '0.0.0.0',
|
||||||
|
port: 5173,
|
||||||
|
proxy: {
|
||||||
|
'/api': 'http://127.0.0.1:8765',
|
||||||
|
'/mcp': 'http://127.0.0.1:8765',
|
||||||
|
'/ws': {
|
||||||
|
target: 'ws://127.0.0.1:8765',
|
||||||
|
ws: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
# PulseWall System Architecture (v1.0)
|
||||||
|
|
||||||
|
PulseWall is an AI-driven live information wall, real-time device status monitor, and bidirectional interactive terminal consisting of:
|
||||||
|
|
||||||
|
1. **Upstream AI Clients**: Any standard MCP client (e.g., `dsh`, Claude, Cursor, custom agents) plus optional event-stream adapter plugins for real-time reverse callbacks.
|
||||||
|
2. **Python Hub (`hub/`)**: Central bridge exposing:
|
||||||
|
- Standard **MCP Server** (Streamable HTTP `/mcp` + REST/SSE event bridge)
|
||||||
|
- **WebSocket Device Gateway** (`/ws/device/{device_id}`) for multi-device Android connectivity (LAN first, WAN/WSS ready)
|
||||||
|
- **Config Center** pushing OpenAI-compatible repair model settings (`base_url`, `api_key`, `model`, limits) and global themes to connected devices
|
||||||
|
- **LAN-Only Developer Debug / ADB Controller** (`/api/lan-debug/...`, strictly restricted to RFC1918/loopback clients, disabled by default per device)
|
||||||
|
- **Audit Log, Page Snapshots & Web Admin Panel** (`/admin`) backed by SQLite
|
||||||
|
3. **Android 11 Native App (`android/`)**: Kotlin native client (`minSdk = 30`) featuring:
|
||||||
|
- **Layered Capability Providers**: `basic` (always), `root` (auto-detected), `accessibility` (reserved), `adb_lan` (Hub-side)
|
||||||
|
- **Native Unbreakable Layer**: Fullscreen red emergency alarm, wake-screen, sound/TTS/vibration, Preset-First quick-action dialogs
|
||||||
|
- **Dual-Stage WebView Renderer**: Pre-render static validator + offscreen sandbox trial -> smooth switch to main WebView + automatic healthy snapshot rollback
|
||||||
|
- **End-Side OpenAI Repair Sentinel**: Fixes syntax/CSS/responsive/WebView-compatibility issues locally using Hub-pushed OpenAI config, and escalates data/semantic questions back to the upstream AI via Hub
|
||||||
|
|
||||||
|
## Render & Self-Healing State Machine
|
||||||
|
|
||||||
|
```
|
||||||
|
Upstream AI calls render_page(device_id, html, ...)
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
Hub forwards WS `render.apply` (task_id) ──► Android Validator & Offscreen Sandbox
|
||||||
|
│ │
|
||||||
|
│ ┌────────┴────────┐
|
||||||
|
│ [PASS] [ERROR]
|
||||||
|
│ │ │
|
||||||
|
│ ▼ ▼
|
||||||
|
│ Mount to Main WebView End-Side Repair AI (OpenAI API)
|
||||||
|
│ Save Healthy Snapshot (up to max_retries, default 3)
|
||||||
|
│ │ │
|
||||||
|
│ │ ┌────────┴────────┐
|
||||||
|
│ │ [fix_locally] [ask_upstream]
|
||||||
|
│ │ │ │
|
||||||
|
│ │ Re-validate Return/Emit Clarification
|
||||||
|
│ │ & Hot-Swap Question to Upstream AI
|
||||||
|
│ ▼
|
||||||
|
│ Runtime Console Watchdog
|
||||||
|
│ (window.onerror / unhandledrejection / console.error / Vue)
|
||||||
|
│ │
|
||||||
|
│ [Runtime Error]
|
||||||
|
│ ▼
|
||||||
|
│ Debounce & Deduplicate ──► End-Side Repair AI
|
||||||
|
│ (Fallback: Auto-rollback to last Healthy Snapshot)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Boundaries
|
||||||
|
|
||||||
|
- **MCP & Device Gateway**: Protected by bearer/header API token (configurable in Hub; optional relaxed mode for local trusted LAN).
|
||||||
|
- **LAN Developer Debug / ADB API**:
|
||||||
|
1. Hard network guard rejecting any non-private IP (`127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `::1`) and rejecting requests with public `X-Forwarded-For` headers.
|
||||||
|
2. Requires both global `lan_debug_enabled=true` and per-device authorization.
|
||||||
|
3. Every command is recorded in SQLite audit logs; destructive commands require confirmation or are blocked.
|
||||||
@@ -0,0 +1,75 @@
|
|||||||
|
# PulseWall MCP & Event Bridge Specification (v1.0)
|
||||||
|
|
||||||
|
Endpoint:
|
||||||
|
- **MCP Streamable HTTP**: `POST/GET/DELETE /mcp`
|
||||||
|
- **Event Stream (for dsh / custom upstream plugins)**: `GET /api/events/stream` (SSE) & `POST /api/webhooks`
|
||||||
|
- **LAN-Only ADB Debug REST** (mirrored to MCP when LAN-authorized): `/api/lan-debug/*`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. MCP Resources
|
||||||
|
|
||||||
|
| URI | Description |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `pulsewall://devices` | List of all registered/online Android devices with basic status & capabilities |
|
||||||
|
| `pulsewall://device/{device_id}/profile` | Full `DisplayProfile` (CSS viewport w/h, DPR, safe area, orientation, `webview_version`), hardware telemetry, and local UI framework hints |
|
||||||
|
| `pulsewall://device/{device_id}/layout` | Current active HTML/Vue layout source, snapshot version, and recent render health |
|
||||||
|
| `pulsewall://events/pending` | Pending reverse events (user interaction replies & end-side AI data clarification questions) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. MCP Tools
|
||||||
|
|
||||||
|
### 2.1 Device Inspection
|
||||||
|
- **`list_devices()`**
|
||||||
|
- Returns connected/offline devices, `device_type` (`phone`/`tablet`), capabilities (`basic`, `root`, `accessibility`, `adb_lan`), and last heartbeat.
|
||||||
|
- **`get_device_status(device_id: str)`**
|
||||||
|
- Returns live telemetry (battery, current/voltage, CPU, RAM, thermal zones, screen on/off, Wi-Fi RSSI) + exact `DisplayProfile` + `webview_version` + UI framework constraints.
|
||||||
|
|
||||||
|
### 2.2 Live Feed & Alerts (Unbreakable Native + WebView)
|
||||||
|
- **`push_feed_item(device_id, title, body, level="info", source="ai", html_snippet=None, sound="ding", tags=[])`**
|
||||||
|
- Appends an item to the device's live feed without replacing the whole page.
|
||||||
|
- `level`: `info` | `notice` | `warning` | `error` | `critical`
|
||||||
|
- **`trigger_alert(device_id, title, message, level="warning", presentation="modal", sound="warning", vibrate=True, wake_screen=False, tts_text=None, details_code=None, custom_html=None, interaction=None)`**
|
||||||
|
- Triggers native alert overlay (independent of WebView health).
|
||||||
|
- `presentation`: `toast` | `modal` | `fullscreen_alarm`
|
||||||
|
- `sound`: `none` | `ding` | `warning` | `siren` | `tts`
|
||||||
|
- `interaction` (optional Preset-First object):
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"interaction_id": "int_001",
|
||||||
|
"mode": "ack_required | action_required",
|
||||||
|
"presets": [
|
||||||
|
{ "id": "ack", "label": "确认收到", "style": "primary" },
|
||||||
|
{ "id": "restart", "label": "立即重启服务", "style": "danger" },
|
||||||
|
{ "id": "snooze_1h", "label": "暂缓 1 小时", "style": "secondary" }
|
||||||
|
],
|
||||||
|
"allow_custom_input": true,
|
||||||
|
"custom_input_placeholder": "其他说明或指令..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- **`dismiss_alert(device_id, alert_id=None)`**
|
||||||
|
- Dismisses an active alert or all active alerts on the target device.
|
||||||
|
|
||||||
|
### 2.3 Dynamic UI Rendering & Snapshots
|
||||||
|
- **`render_page(device_id, html, mode="full", title=None, data_context=None, wait_validation_sec=15)`**
|
||||||
|
- Sends HTML/Vue/CSS/JS code to Android for pre-render validation, offscreen sandbox check, optional end-side Repair AI self-healing, and live mount.
|
||||||
|
- `mode`: `full` (full canvas replacement) | `widget` (upsert named widget slot)
|
||||||
|
- Returns:
|
||||||
|
- `status`: `rendered` | `rendered_after_local_fix` | `needs_clarification` | `failed_rolled_back` | `queued_offline`
|
||||||
|
- `snapshot_id`, `local_fixes_applied`, `clarification_questions` (if end-side AI needs upstream data), `console_errors`.
|
||||||
|
- **`rollback_page(device_id, snapshot_id=None)`**
|
||||||
|
- Rolls the device back to the previous healthy snapshot or a specific `snapshot_id`.
|
||||||
|
- **`reply_clarification(task_id, answers, updated_html=None, updated_data=None)`**
|
||||||
|
- Answers a data clarification question raised by the device's Repair AI (either during initial render or runtime console monitoring).
|
||||||
|
|
||||||
|
### 2.4 Bidirectional Event Polling (for pure MCP clients without SSE plugin)
|
||||||
|
- **`get_pending_events(device_id=None, limit=20)`**
|
||||||
|
- Returns unacknowledged reverse events: `user_interaction_reply` and `repair_data_clarification`.
|
||||||
|
- **`ack_events(event_ids: list[str])`**
|
||||||
|
- Marks events as processed by the upstream AI.
|
||||||
|
|
||||||
|
### 2.5 LAN-Only Developer Debug / ADB Control (Strictly LAN)
|
||||||
|
- **`lan_adb_action(device_id, action, params={})`**
|
||||||
|
- Only succeeds if request originates from a private LAN IP AND Hub global + device LAN debug flags are enabled.
|
||||||
|
- Supported `action`: `status`, `tap`, `swipe`, `text`, `keyevent`, `launch_app`, `screencap`, `screen_wake`, `screen_sleep`, `dumpsys_summary`.
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
# PulseWall WebSocket Protocol (Hub <-> Android Device) v1.0
|
||||||
|
|
||||||
|
Transport: `ws://<hub-host>:<port>/ws/device/{device_id}` (or `wss://` behind TLS reverse proxy).
|
||||||
|
Optional auth header: `Authorization: Bearer <token>` or query `?token=<token>`.
|
||||||
|
|
||||||
|
Every frame is a JSON envelope:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "namespace.action",
|
||||||
|
"msg_id": "uuid-v4",
|
||||||
|
"ts": 1732880000000,
|
||||||
|
"payload": {}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Android -> Hub Messages
|
||||||
|
|
||||||
|
### `device.hello` (sent immediately on connect)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"device_id": "pixel-wall-01",
|
||||||
|
"device_name": "客厅监控机",
|
||||||
|
"model": "Xiaomi Mi 10",
|
||||||
|
"android_sdk": 30,
|
||||||
|
"android_release": "11",
|
||||||
|
"app_version": "0.1.0",
|
||||||
|
"capabilities": ["basic", "root"],
|
||||||
|
"display_profile": {
|
||||||
|
"device_type": "phone",
|
||||||
|
"orientation": "portrait",
|
||||||
|
"width_px": 1080,
|
||||||
|
"height_px": 2340,
|
||||||
|
"viewport_css_w": 392,
|
||||||
|
"viewport_css_h": 850,
|
||||||
|
"dpr": 2.75,
|
||||||
|
"safe_area_top_dp": 32,
|
||||||
|
"safe_area_bottom_dp": 20,
|
||||||
|
"font_scale": 1.0,
|
||||||
|
"webview_version": "114.0.5735.196"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `device.telemetry` (periodic heartbeat, default every 10s or on change)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"battery_pct": 82,
|
||||||
|
"is_charging": true,
|
||||||
|
"battery_temp_c": 31.4,
|
||||||
|
"battery_current_ma": 420,
|
||||||
|
"cpu_usage_pct": 14.2,
|
||||||
|
"mem_used_mb": 2910,
|
||||||
|
"mem_total_mb": 7800,
|
||||||
|
"thermal_zones": { "cpu": 39.5, "gpu": 37.0 },
|
||||||
|
"wifi_rssi_dbm": -52,
|
||||||
|
"screen_on": true,
|
||||||
|
"display_profile": { "...": "updated if rotated" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `render.result` (response to `render.apply` or runtime self-heal)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"task_id": "task_abc123",
|
||||||
|
"trigger": "initial_render | runtime_watchdog",
|
||||||
|
"status": "rendered | rendered_after_local_fix | needs_clarification | failed_rolled_back",
|
||||||
|
"snapshot_id": "snap_005",
|
||||||
|
"attempts": 1,
|
||||||
|
"final_html": "...",
|
||||||
|
"local_fix_summary": "Fixed overflow width on 392px viewport",
|
||||||
|
"clarification_questions": [
|
||||||
|
{
|
||||||
|
"field": "server.gpu_temp",
|
||||||
|
"question": "模板引用了 server.gpu_temp 但数据上下文中未提供,请问实际字段名或数值是什么?"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"errors": []
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `interaction.reply` (user tapped a preset button or submitted custom text)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"interaction_id": "int_001",
|
||||||
|
"alert_id": "alert_001",
|
||||||
|
"selected_preset_id": "restart",
|
||||||
|
"selected_label": "立即重启服务",
|
||||||
|
"custom_text": null,
|
||||||
|
"responded_at": 1732880012345
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `console.error_report` (runtime errors observed by WebView watchdog)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"snapshot_id": "snap_005",
|
||||||
|
"source": "window.onerror | unhandledrejection | console.error | vue",
|
||||||
|
"message": "TypeError: Cannot read properties of undefined (reading 'temp')",
|
||||||
|
"stack": "...",
|
||||||
|
"repair_status": "repairing | fixed | needs_clarification | rolled_back"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Hub -> Android Messages
|
||||||
|
|
||||||
|
### `config.push` (sent on connect & whenever updated in Hub Admin)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"repair_ai": {
|
||||||
|
"enabled": true,
|
||||||
|
"base_url": "https://api.openai.com/v1",
|
||||||
|
"api_key": "sk-...",
|
||||||
|
"model": "gpt-4o-mini",
|
||||||
|
"timeout_sec": 30,
|
||||||
|
"max_retries": 3,
|
||||||
|
"runtime_cooldown_sec": 30
|
||||||
|
},
|
||||||
|
"telemetry_interval_sec": 10,
|
||||||
|
"theme": "dark-glass"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `feed.push`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"item_id": "feed_001",
|
||||||
|
"title": "备份完成",
|
||||||
|
"body": "数据库夜间快照已完成 (1.4 GB)",
|
||||||
|
"level": "info",
|
||||||
|
"source": "backup-agent",
|
||||||
|
"sound": "ding",
|
||||||
|
"html_snippet": null,
|
||||||
|
"tags": ["db", "cron"],
|
||||||
|
"ts": 1732880000000
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `alert.trigger` / `alert.dismiss`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"alert_id": "alert_001",
|
||||||
|
"title": "核心服务宕机",
|
||||||
|
"message": "prod-api-01 连续 3 次健康检查失败 (HTTP 502)",
|
||||||
|
"level": "critical",
|
||||||
|
"presentation": "fullscreen_alarm",
|
||||||
|
"sound": "siren",
|
||||||
|
"vibrate": true,
|
||||||
|
"wake_screen": true,
|
||||||
|
"tts_text": "紧急警报,生产接口服务宕机,请立即处理",
|
||||||
|
"details_code": "upstream connect error or disconnect/reset before headers",
|
||||||
|
"custom_html": null,
|
||||||
|
"interaction": {
|
||||||
|
"interaction_id": "int_001",
|
||||||
|
"mode": "action_required",
|
||||||
|
"presets": [
|
||||||
|
{ "id": "ack", "label": "确认收到", "style": "primary" },
|
||||||
|
{ "id": "restart", "label": "立即重启服务", "style": "danger" },
|
||||||
|
{ "id": "mute_30m", "label": "静音 30 分钟", "style": "secondary" }
|
||||||
|
],
|
||||||
|
"allow_custom_input": true,
|
||||||
|
"custom_input_placeholder": "输入自定义处理指示..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `render.apply`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"task_id": "task_abc123",
|
||||||
|
"mode": "full",
|
||||||
|
"title": "机房监控看板",
|
||||||
|
"html": "<div id='app'>...</div>",
|
||||||
|
"data_context": {},
|
||||||
|
"snapshot_id": "snap_005"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `render.rollback`
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"snapshot_id": "snap_004",
|
||||||
|
"html": "..."
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `clarification.answer` (upstream AI replied to end-side Repair AI's data question)
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"task_id": "task_abc123",
|
||||||
|
"answers": { "server.gpu_temp": "该机器无独显,请改为展示 cpu_temp 并隐藏 GPU 卡片" },
|
||||||
|
"updated_data": {},
|
||||||
|
"updated_html": null
|
||||||
|
}
|
||||||
|
```
|
||||||
Reference in new issue
Block a user