Files
pulsewall/hub/app/admin/ui.py
T
jmj 3889b6d910 feat(repair): add toggle for offscreen sandbox precheck
The offscreen WebView validation runs once per page and is the heaviest
part of the render pipeline on low-end TV boxes: it wakes an invisible
WebView, loads the sandbox page, injects the full DOM and waits ~550ms
before mounting the real page.

Add RepairAiConfig.precheckEnabled (default true) so it can be disabled:

- Android: skip validateInOffscreenSandbox and mount directly, reporting
  status "rendered_precheck_skipped" so the outcome stays distinguishable
  in render results. Exposed in the terminal settings dialog and accepted
  from hub config pushes.
- Hub: add precheck_enabled to RepairAIConfig, the admin form and the
  config payload so the switch can be toggled remotely.

Trade-off: with precheck off, malformed pages surface on screen instead
of being caught and repaired before mounting.
2026-11-30 11:06:17 +08:00

653 lines
34 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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')">⚙️ 全局配置 &amp; 日志</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><input type="checkbox" id="g_ai_precheck" 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) &amp; 待处理反向事件</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;">📬 待处理反向事件(用户操作 &amp; 修复 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,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
}
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_precheck','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_precheck').checked = r.precheck_enabled !== false;
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,
precheck_enabled: document.getElementById('g_ai_precheck').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://&lt;HubIP&gt;: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) &amp; 页面快照回滚</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>
"""