feat: fix dashboard real-time data sync, stabilize node order and eliminate UI jitter
Release / Build & Release (push) Canceled after 0s

This commit is contained in:
kory
2026-09-30 13:17:19 +08:00
parent bd44465eaa
commit af63e3a120
20 changed files with 2133 additions and 90 deletions
+40
View File
@@ -53,6 +53,10 @@ func (p *Panel) Handler() http.Handler {
mux.HandleFunc("/panel/api/mcp/test", p.protected(p.testMCP))
mux.HandleFunc("/panel/api/security/settings", p.protected(p.securitySettings))
mux.HandleFunc("/panel/api/security/settings/update", p.protected(p.updateSecuritySettings))
mux.HandleFunc("/panel/api/notifications/webhooks", p.protected(p.webhookTargets))
mux.HandleFunc("/panel/api/notifications/webhook/update", p.protected(p.updateWebhookTarget))
mux.HandleFunc("/panel/api/notifications/webhook/delete", p.protected(p.deleteWebhookTarget))
mux.HandleFunc("/panel/api/notifications/webhook/test", p.protected(p.testWebhook))
mux.HandleFunc("/", p.probe)
return mux
}
@@ -121,6 +125,42 @@ func (p *Panel) testMCP(w http.ResponseWriter, r *http.Request) {
http.Error(w, "MCP API unavailable", 501)
}
type notificationPanelRunner interface {
WebhookTargetsJSON(http.ResponseWriter, *http.Request)
UpdateWebhookTargetJSON(http.ResponseWriter, *http.Request)
DeleteWebhookTargetJSON(http.ResponseWriter, *http.Request)
TestWebhookJSON(http.ResponseWriter, *http.Request)
}
func (p *Panel) webhookTargets(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.WebhookTargetsJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) updateWebhookTarget(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.UpdateWebhookTargetJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) deleteWebhookTarget(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.DeleteWebhookTargetJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) testWebhook(w http.ResponseWriter, r *http.Request) {
if v, ok := p.Runner.(notificationPanelRunner); ok {
v.TestWebhookJSON(w, r)
return
}
http.Error(w, "notification API unavailable", 501)
}
func (p *Panel) handleDevices(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodDelete {
p.Runner.DeleteDevice(w, r)
+6 -4
View File
@@ -1,6 +1,6 @@
*{box-sizing:border-box}
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2)}
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08)}
:root{color-scheme:dark;--bg-body:#0b1020;--bg-card:#111a2d;--bg-sub:#0d1526;--border:#24304a;--border-strong:#34415d;--text-main:#e7ebf3;--text-muted:#7f8ba3;--text-status:#9aabc5;--pre-text:#b9c5da;--thead:#91a0bb;--dot-online:#4ade80;--dot-offline:#f87171;--shadow:0 8px 30px rgba(0,0,0,.2);--card:var(--bg-sub);--line:var(--border)}
:root[data-theme="light"]{color-scheme:light;--bg-body:#f4f6fa;--bg-card:#fff;--bg-sub:#eef2f7;--border:#d1d9e4;--border-strong:#b8c3d3;--text-main:#172033;--text-muted:#647089;--text-status:#58657a;--pre-text:#26344b;--thead:#53627a;--dot-online:#16833d;--dot-offline:#c62828;--shadow:0 8px 26px rgba(28,45,72,.08);--card:var(--bg-sub);--line:var(--border)}
html,body{min-height:100%}body{margin:0;background:var(--bg-body);color:var(--text-main);font:14px/1.5 system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif}header{min-height:64px;padding:0 24px;display:flex;align-items:center;justify-content:space-between;gap:14px;border-bottom:1px solid var(--border);background:var(--bg-card);position:sticky;top:0;z-index:2}
.brand-wrap{display:flex;align-items:center;gap:12px;min-width:0}
.brand-logo{width:36px;height:36px;border-radius:8px;object-fit:cover;flex:none;box-shadow:0 2px 8px rgba(0,0,0,.15)}
@@ -41,7 +41,9 @@ header strong{font-size:18px}header span{margin-left:12px;color:var(--text-muted
.device-card.offline{opacity:.62;filter:saturate(.45)}
.device-card.offline .btn-revoke{opacity:1}
.mcp-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.mcp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.mcp-item{border:1px solid var(--line,#30343b);border-radius:10px;padding:14px;background:var(--card,#11151a)}.mcp-item h3{margin:0 0 6px;font-size:15px}.mcp-meta{font-size:12px;opacity:.72;line-height:1.7}.mcp-actions{display:flex;gap:8px;margin-top:10px}.mcp-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mcp-form .full{grid-column:1/-1}.mcp-form label{display:flex;flex-direction:column;gap:5px;font-size:12px;opacity:.9}.mcp-form input,.mcp-form select,.mcp-form textarea{width:100%;box-sizing:border-box}.mcp-form textarea{min-height:72px;font-family:monospace}.mcp-nodes{display:flex;flex-wrap:wrap;gap:8px}.mcp-nodes label{flex-direction:row;align-items:center}.mcp-status{font-size:12px;margin-top:8px;min-height:18px}.mcp-field-error{border-color:#e05252!important;outline:1px solid #e05252}.mcp-test-result{margin-top:12px;padding:12px;border:1px solid var(--line,#30343b);border-radius:10px;white-space:normal}.mcp-test-result.ok{border-color:#3a9b68}.mcp-test-result.fail{border-color:#c44}.mcp-test-tools{margin:8px 0 0;padding-left:18px}.mcp-test-detail{margin-top:8px;white-space:pre-wrap;overflow:auto;max-height:220px;font-family:monospace;font-size:12px}
.mcp-toolbar{display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:14px}.mcp-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:12px}.mcp-item{border:1px solid var(--border);border-radius:10px;padding:14px;background:var(--bg-sub)}.mcp-item h3{margin:0 0 6px;font-size:15px}.mcp-meta{font-size:12px;opacity:.72;line-height:1.7}.mcp-actions{display:flex;gap:8px;margin-top:10px}.mcp-form{display:grid;grid-template-columns:1fr 1fr;gap:10px}.mcp-form .full{grid-column:1/-1}.mcp-form label{display:flex;flex-direction:column;gap:5px;font-size:12px;opacity:.9}.mcp-form input,.mcp-form select,.mcp-form textarea{width:100%;box-sizing:border-box}.mcp-form textarea{min-height:72px;font-family:monospace}.mcp-nodes{display:flex;flex-wrap:wrap;gap:8px}.mcp-nodes label{flex-direction:row;align-items:center}.mcp-status{font-size:12px;margin-top:8px;min-height:18px}.mcp-field-error{border-color:#e05252!important;outline:1px solid #e05252}.mcp-test-result{margin-top:12px;padding:12px;border:1px solid var(--border);border-radius:10px;white-space:normal}.mcp-test-result.ok{border-color:#3a9b68}.mcp-test-result.fail{border-color:#c44}.mcp-test-tools{margin:8px 0 0;padding-left:18px}.mcp-test-detail{margin-top:8px;white-space:pre-wrap;overflow:auto;max-height:220px;font-family:monospace;font-size:12px}
@media(max-width:700px){.mcp-form{grid-template-columns:1fr}.mcp-form .full{grid-column:auto}.mcp-toolbar{align-items:flex-start;flex-direction:column}}
.security-grid{display:flex;gap:12px;align-items:end;flex-wrap:wrap;margin-bottom:16px}.security-grid label{display:flex;flex-direction:column;gap:6px}.security-grid select,.tablewrap select{padding:7px 9px;border:1px solid var(--line,#30343b);border-radius:6px;background:var(--card,#11151a);color:inherit}.security-grid button{height:34px}
.security-grid{display:flex;gap:12px;align-items:end;flex-wrap:wrap;margin-bottom:16px}.security-grid label{display:flex;flex-direction:column;gap:6px}.security-grid select,.tablewrap select{padding:7px 9px;border:1px solid var(--border);border-radius:6px;background:var(--bg-sub);color:inherit}.security-grid button{height:34px}
.notification-form{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin:12px 0}.notification-form label{display:flex;flex-direction:column;gap:6px;font-size:12px}.notification-form .full{grid-column:1/-1}.notification-form input,.notification-form select,.notification-form textarea{width:100%;box-sizing:border-box}.notification-form textarea{min-height:72px}@media(max-width:700px){.notification-form{grid-template-columns:1fr}.notification-form .full{grid-column:auto}}
+255 -41
View File
@@ -11,7 +11,8 @@ const $=s=>document.querySelector(s);
})();
async function api(path,opt={}){
let r=await fetch("/panel/api"+path,opt);
const fetchOpt = Object.assign({ cache: "no-store" }, opt);
let r=await fetch("/panel/api"+path, fetchOpt);
if(r.status===401){location.href="/panel/login";throw Error("unauthorized")}
if(!r.ok)throw Error(await r.text());
return r.json()
@@ -31,49 +32,76 @@ async function removeDevice(name){
}
}
async function loadDevices(){
let all=await api("/devices");
let ds=all.filter(d=>!d.is_local);
$("#devices").innerHTML=ds.map(d=>{
const p = d.profile || {};
const role = p.role || "APPLICATION";
const isOnline = d.status === "online";
const statusText = isOnline ? "在线" : "离线";
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
const dockerVal = p.docker ? 'YES' : 'NO';
const dockerClass = p.docker ? 'yes' : 'no';
function renderSingleCard(d) {
const p = d.profile || {};
const isOnline = d.status === "online";
const statusText = isOnline ? "在线" : "离线";
const lastText = d.last_heartbeat ? new Date(d.last_heartbeat*1000).toLocaleString() : "";
const archOs = (d.arch || d.os) ? `${esc(d.arch||"")}/${esc(d.os||"")} · ` : "";
const cpuStr = p.cpu_cores ? `${p.cpu_cores}C · ${p.cpu_usage_percent ?? 0}%` : '-';
const loadStr = p.load_1m !== undefined ? p.load_1m.toFixed(2) : '-';
const memStr = p.mem_available ? `${p.mem_available} (${p.mem_percent}%)` : (p.mem_percent !== undefined ? `${p.mem_percent}%` : '-');
const diskStr = p.disk_free ? `${p.disk_free} (${p.disk_percent}%)` : (p.disk_percent !== undefined ? `${p.disk_percent}%` : '-');
const psiStr = p.io_psi !== undefined ? p.io_psi.toFixed(2) : '-';
const dockerVal = p.docker ? 'YES' : 'NO';
const dockerClass = p.docker ? 'yes' : 'no';
return `
<div class="device-card ${isOnline ? "online" : "offline"}">
<div class="v1-head">
<div class="v1-row1">
<div class="v1-title">
<span class="dot"></span>
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
</div>
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
</div>
<div class="v1-row2">${archOs}${statusText}${isOnline ? "" : (lastText ? " · 最后活跃: "+lastText : "")}</div>
</div>
<div class="profile-grid">
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</span></div>
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
return `
<div class="v1-head">
<div class="v1-row1">
<div class="v1-title">
<span class="dot"></span>
<strong class="v1-name" title="${esc(d.name)}">${esc(d.name)}</strong>
</div>
<button class="btn-revoke" onclick="removeDevice('${esc(d.name)}')">注销</button>
</div>
`;
}).join("");
<div class="v1-row2">${archOs}${statusText}${isOnline ? "" : (lastText ? " · 最后活跃: "+lastText : "")}</div>
</div>
<div class="profile-grid">
<div class="p-item"><span class="p-label">CPU</span><span class="p-val">${cpuStr}</span></div>
<div class="p-item"><span class="p-label">LOAD</span><span class="p-val">${loadStr}</span></div>
<div class="p-item"><span class="p-label">MEM</span><span class="p-val">${memStr}</span></div>
<div class="p-item"><span class="p-label">DISK</span><span class="p-val">${diskStr}</span></div>
<div class="p-item"><span class="p-label">IO PSI</span><span class="p-val">${psiStr}</span></div>
<div class="p-item"><span class="p-label">DOCKER</span><span class="p-val badge-docker-text ${dockerClass}">${dockerVal}</span></div>
</div>
`;
}
$("#device").innerHTML=ds.map(d=>`<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join("");
async function loadDevices(){
let all = await api("/devices");
let ds = all.filter(d => !d.is_local);
// 严格固定名称字典序排列,杜绝乱跳
ds.sort((a, b) => String(a.name || "").localeCompare(String(b.name || "")));
const container = $("#devices");
const currentCardElements = container.querySelectorAll(".device-card[data-node]");
const currentNodes = Array.from(currentCardElements).map(el => el.getAttribute("data-node"));
const newNodes = ds.map(d => d.name);
// 如果节点列表结构未变,采用就地局部更新,卡片物理位置丝毫不动
const sameOrder = currentNodes.length === newNodes.length && currentNodes.every((n, i) => n === newNodes[i]);
if (sameOrder) {
ds.forEach(d => {
const card = container.querySelector(`.device-card[data-node="${CSS.escape(d.name)}"]`);
if (card) {
const isOnline = d.status === "online";
card.className = `device-card ${isOnline ? "online" : "offline"}`;
card.innerHTML = renderSingleCard(d);
}
});
} else {
// 首次渲染或增删节点时渲染
container.innerHTML = ds.map(d => {
const isOnline = d.status === "online";
return `<div class="device-card ${isOnline ? "online" : "offline"}" data-node="${esc(d.name)}">${renderSingleCard(d)}</div>`;
}).join("");
}
// 保持控制台 select 选项
const select = $("#device");
const selectedVal = select.value;
select.innerHTML = ds.map(d => `<option value="${esc(d.name)}" ${d.status==="offline" ? "disabled" : ""} ${d.name===selectedVal ? "selected" : ""}>${esc(d.name)}${d.status==="offline" ? " [离线]" : ""}</option>`).join("");
}
async function loadAudits(){
@@ -128,7 +156,7 @@ function parseMCPField(id,label,kind){
return value;
}
function showMCPToast(message){
let t=$("#mcpToast"); if(!t){t=document.createElement("div");t.id="mcpToast";t.style.cssText="position:fixed;right:18px;top:18px;z-index:9999;padding:10px 14px;border:1px solid var(--line,#30343b);border-radius:8px;background:var(--card,#11151a);box-shadow:0 8px 30px rgba(0,0,0,.25)";document.body.appendChild(t)}
let t=$("#mcpToast"); if(!t){t=document.createElement("div");t.id="mcpToast";t.style.cssText="position:fixed;right:18px;top:18px;z-index:9999;padding:10px 14px;border:1px solid var(--border);border-radius:8px;background:var(--bg-sub);box-shadow:0 8px 30px rgba(0,0,0,.25)";document.body.appendChild(t)}
t.textContent=message; t.hidden=false; clearTimeout(t._timer); t._timer=setTimeout(()=>t.hidden=true,2600);
}
async function loadMCPServices(){
@@ -188,3 +216,189 @@ loadMCPServices().catch(console.error);
async function loadSecuritySettings(){const x=await api("/security/settings"),nodes=x.nodes||[],effective=x.effective||{},configured=new Map(nodes.map(n=>[n.node,n.mode])),devices=await api("/devices");$("#globalSecurity").value=x.global||"medium";$("#securityNodes").innerHTML=devices.map(d=>{const mode=configured.get(d.name)||"inherit",eff=effective[d.name]||x.global||"medium";return `<tr><td>${esc(d.name)}</td><td><select data-security-node="${esc(d.name)}"><option value="inherit" ${mode==='inherit'?'selected':''}>跟随全局</option><option value="low" ${mode==='low'?'selected':''}>低 · Low</option><option value="medium" ${mode==='medium'?'selected':''}>中 · Medium</option><option value="high" ${mode==='high'?'selected':''}>高 · High</option></select></td><td>${esc(eff)}</td><td><button type="button" onclick="saveNodeSecurity('${esc(d.name)}')">保存</button></td></tr>`}).join("")}
async function saveNodeSecurity(node){const el=document.querySelector(`[data-security-node="${CSS.escape(node)}"]`);if(!el)return;try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({node,mode:el.value})});$("#securityStatus").textContent=`${node} 策略已保存。`;await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}}
$("#saveGlobalSecurity").onclick=async()=>{try{await api("/security/settings/update",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({global:$("#globalSecurity").value})});$("#securityStatus").textContent="全局安全策略已保存。";await loadSecuritySettings()}catch(e){$("#securityStatus").textContent="保存失败: "+e.message}};$("#securityRefresh").onclick=()=>loadSecuritySettings().catch(console.error);loadSecuritySettings().catch(console.error);
let webhookEditingId = "";
async function loadWebhooks() {
const list = await api("/notifications/webhooks");
const el = $("#webhookList");
if (!el) return;
if (!list || list.length === 0) {
el.innerHTML = '<div class="mcp-meta">暂无 Webhook 配置。</div>';
return;
}
el.innerHTML = list.map(x => `
<div class="mcp-item">
<h3>${esc(x.name)} <small>${esc(x.id)}</small></h3>
<div class="mcp-meta">
${esc(x.type)} · ${x.enabled ? '<span style="color:var(--dot-online)">启用</span>' : '<span style="color:var(--text-muted)">停用</span>'}<br>
<code>${esc(x.url)}</code>
</div>
<div class="mcp-actions">
<button type="button" onclick="editWebhook('${esc(x.id)}')">编辑</button>
<button type="button" onclick="deleteWebhook('${esc(x.id)}')">删除</button>
</div>
</div>
`).join("");
}
function resetWebhookForm() {
webhookEditingId = "";
const editor = $("#webhookEditor");
if (!editor) return;
editor.hidden = false;
$("#webhookId").disabled = false;
$("#webhookId").value = "";
$("#webhookName").value = "";
$("#webhookType").value = "wecom";
$("#webhookEnabled").value = "1";
$("#webhookUrl").value = "";
$("#webhookConfig").value = "{}";
$("#webhookStatus").textContent = "";
}
async function editWebhook(id) {
const list = await api("/notifications/webhooks");
const item = list.find(x => x.id === id);
if (!item) return;
resetWebhookForm();
webhookEditingId = id;
$("#webhookId").value = item.id;
$("#webhookId").disabled = true;
$("#webhookName").value = item.name || "";
$("#webhookType").value = item.type || "wecom";
$("#webhookEnabled").value = item.enabled ? "1" : "0";
$("#webhookUrl").value = item.url || "";
$("#webhookConfig").value = item.config_json || "{}";
}
async function deleteWebhook(id) {
if (!confirm(`确认删除 Webhook [${id}]?`)) return;
try {
await api("/notifications/webhook/delete?id=" + encodeURIComponent(id), { method: "DELETE" });
await loadWebhooks();
} catch (e) {
alert("删除失败: " + e.message);
}
}
if ($("#webhookNew")) $("#webhookNew").onclick = resetWebhookForm;
if ($("#webhookCancel")) $("#webhookCancel").onclick = () => {
const editor = $("#webhookEditor");
if (editor) editor.hidden = true;
};
if ($("#webhookSave")) $("#webhookSave").onclick = async () => {
try {
const id = $("#webhookId").value.trim();
const name = $("#webhookName").value.trim();
const url = $("#webhookUrl").value.trim();
if (!id) throw Error("标识 (ID) 不能为空");
if (!name) throw Error("名称不能为空");
if (!url) throw Error("Webhook URL 不能为空");
let cfg = {};
try {
cfg = JSON.parse($("#webhookConfig").value || "{}");
} catch (e) {
throw Error("配置 JSON 格式不正确");
}
const body = {
id: id,
name: name,
type: $("#webhookType").value,
url: url,
config_json: JSON.stringify(cfg),
enabled: $("#webhookEnabled").value === "1"
};
await api("/notifications/webhook/update", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
$("#webhookStatus").textContent = "Webhook [" + id + "] 已保存。";
const editor = $("#webhookEditor");
if (editor) editor.hidden = true;
await loadWebhooks();
} catch (e) {
$("#webhookStatus").textContent = "保存失败: " + e.message;
}
};
if ($("#webhookTest")) $("#webhookTest").onclick = async () => {
try {
const id = $("#webhookId").value.trim();
const name = $("#webhookName").value.trim();
const url = $("#webhookUrl").value.trim();
if (!url) throw Error("Webhook URL 不能为空");
let cfg = {};
try {
cfg = JSON.parse($("#webhookConfig").value || "{}");
} catch (e) {
throw Error("配置 JSON 格式不正确");
}
const body = {
id: id || "test",
name: name || "测试目标",
type: $("#webhookType").value,
url: url,
config_json: JSON.stringify(cfg),
enabled: true
};
$("#webhookStatus").textContent = "正在发送测试消息...";
await api("/notifications/webhook/test", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body)
});
$("#webhookStatus").textContent = "✓ 测试消息发送成功!";
} catch (e) {
$("#webhookStatus").textContent = "✗ 测试失败: " + e.message;
}
};
if ($("#notificationRefresh")) $("#notificationRefresh").onclick = () => loadWebhooks().catch(console.error);
// 开启 5 秒平滑实时自动轮询
let devicePollTimer = null;
function startDevicePolling() {
if (devicePollTimer) clearInterval(devicePollTimer);
devicePollTimer = setInterval(() => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
}, 5000);
}
startDevicePolling();
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
});
loadWebhooks().catch(console.error);
// 开启 5 秒平滑实时自动轮询
let devicePollTimer = null;
function startDevicePolling() {
if (devicePollTimer) clearInterval(devicePollTimer);
devicePollTimer = setInterval(() => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
}, 5000);
}
startDevicePolling();
document.addEventListener("visibilitychange", () => {
if (!document.hidden) {
loadDevices().catch(console.error);
}
});
+38 -2
View File
@@ -1,2 +1,38 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP 挂载</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div><label>测试节点<select id="mcpTestNode"><option value="local">Hub 本机</option></select></label></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpTest" type="button">测试连通性</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div><div id="mcpTestResult" class="mcp-test-result" hidden></div></div></article>
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>安全设置</h2><button id="securityRefresh" type="button">刷新</button></div><div class="security-grid"><label>全局安全等级<select id="globalSecurity"><option value="low">低 · Low</option><option value="medium">中 · Medium</option><option value="high">高 · High</option></select></label><button id="saveGlobalSecurity" type="button">保存全局策略</button></div><div class="tablewrap"><table><thead><tr><th>节点</th><th>单机策略</th><th>有效策略</th><th>操作</th></tr></thead><tbody id="securityNodes"></tbody></table></div><p id="securityStatus"></p></article><article class="card wide"><div class="cardhead"><h2>审计日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander</title><link rel="stylesheet" href="/static/app.css"></head><body><header><div class="brand-wrap"><img src="/static/icon.png" alt="logo" class="brand-logo"><div><strong>VPS-Commander</strong><span>Private Infrastructure Console</span></div></div><div class="header-actions"><button id="themeToggle" type="button" class="btn-icon" title="切换主题" aria-label="切换主题"><svg class="theme-svg svg-sun" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="5"></circle><line x1="12" y1="1" x2="12" y2="3"></line><line x1="12" y1="21" x2="12" y2="23"></line><line x1="4.22" y1="4.22" x2="5.64" y2="5.64"></line><line x1="18.36" y1="18.36" x2="19.78" y2="19.78"></line><line x1="1" y1="12" x2="3" y2="12"></line><line x1="21" y1="12" x2="23" y2="12"></line><line x1="4.22" y1="19.78" x2="5.64" y2="18.36"></line><line x1="18.36" y1="5.64" x2="19.78" y2="4.22"></line></svg><svg class="theme-svg svg-moon" viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z"></path></svg></button><button id="logout" type="button">退出</button></div></header><main><section class="grid"><article class="card wide"><div class="cardhead"><h2>设备看板</h2><button id="refresh" type="button">刷新</button></div><div id="devices" class="devices"></div></article><article class="card"><h2>Actions 向导</h2><p>当前 Hub 的 OpenAPI Schema:</p><div class="actions"><button id="copySchema" type="button">复制 Schema 地址</button><button id="copyPrompt" type="button">复制 System Prompt</button><button id="rotateKey" type="button">轮换 API Key</button></div><pre id="schemaHint">/openapi.json</pre><pre id="newKey"></pre></article><article class="card wide"><div class="mcp-toolbar"><h2>MCP</h2><button id="mcpNew" type="button">新增 MCP</button></div><div id="mcpList" class="mcp-grid"></div><div id="mcpEditor" hidden><div class="mcp-form"><label>服务标识<input id="mcpId" placeholder="docker"></label><label>显示名称<input id="mcpName" placeholder="Docker 容器管理"></label><label>传输类型<select id="mcpTransport"><option value="stdio">命令行 / stdio</option><option value="http">HTTP / Streamable HTTP</option><option value="sse">SSE</option></select></label><label>启用<select id="mcpEnabled"><option value="1">启用</option><option value="0">停用</option></select></label><label class="full">Command<input id="mcpCommand" placeholder="docker-mcp"></label><label class="full">Arguments(JSON 数组)<textarea id="mcpArgs">[]</textarea></label><label class="full">URL<input id="mcpUrl" placeholder="http://127.0.0.1:8080/mcp"></label><label class="full">Headers(JSON 对象,可选)<textarea id="mcpHeaders">{}</textarea></label><label class="full">环境变量(JSON 对象,可选)<textarea id="mcpEnv">{}</textarea></label><label>生效范围<select id="mcpScope"><option value="all">全部节点</option><option value="custom">指定节点</option></select></label><div><span>指定节点</span><div id="mcpNodes" class="mcp-nodes"></div></div><label>测试节点<select id="mcpTestNode"><option value="local">Hub 本机</option></select></label></div><div class="mcp-actions"><button id="mcpSave" type="button">保存并热更新</button><button id="mcpTest" type="button">测试连通性</button><button id="mcpCancel" type="button">取消</button></div><div id="mcpStatus" class="mcp-status"></div><div id="mcpTestResult" class="mcp-test-result" hidden></div></div></article>
<article class="card wide"><div class="cardhead"><h2>快速控制台</h2><select id="device"></select></div><textarea id="command" placeholder="输入 Shell 命令,例如 uname -a"></textarea><div><button id="run" type="button">执行</button></div><pre id="output"></pre></article><article class="card wide"><div class="cardhead"><h2>安全</h2><button id="securityRefresh" type="button">刷新</button></div><div class="security-grid"><label>全局安全等级<select id="globalSecurity"><option value="low">低 · Low</option><option value="medium">中 · Medium</option><option value="high">高 · High</option></select></label><button id="saveGlobalSecurity" type="button">保存全局策略</button></div><div class="tablewrap"><table><thead><tr><th>节点</th><th>单机策略</th><th>有效策略</th><th>操作</th></tr></thead><tbody id="securityNodes"></tbody></table></div><p id="securityStatus"></p></article><article class="card wide">
<div class="mcp-toolbar">
<h2>通知</h2>
<div style="display:flex;gap:8px">
<button id="webhookNew" type="button">新增 Webhook</button>
<button id="notificationRefresh" type="button">刷新</button>
</div>
</div>
<div id="webhookList" class="mcp-grid"></div>
<div id="webhookEditor" hidden style="margin-top:14px;border-top:1px solid var(--border);padding-top:14px">
<div class="mcp-form">
<label>标识 (ID)<input id="webhookId" placeholder="如 openclaw-wecom"></label>
<label>名称<input id="webhookName" placeholder="如 运维告警群"></label>
<label>类型
<select id="webhookType">
<option value="wecom">企业微信 (WeCom)</option>
<option value="telegram">Telegram</option>
<option value="generic">通用 JSON Webhook</option>
</select>
</label>
<label>状态
<select id="webhookEnabled">
<option value="1">启用</option>
<option value="0">停用</option>
</select>
</label>
<label class="full">Webhook URL<input id="webhookUrl" placeholder="https://qyapi.weixin.qq.com/..."></label>
<label class="full">配置 JSON (Telegram 需填 {"chat_id":"-100..."})<textarea id="webhookConfig">{}</textarea></label>
</div>
<div class="mcp-actions">
<button id="webhookSave" type="button">保存 Webhook</button>
<button id="webhookTest" type="button">测试连通性</button>
<button id="webhookCancel" type="button">取消</button>
</div>
<div id="webhookStatus" class="mcp-status"></div>
</div>
</article><article class="card wide"><div class="cardhead"><h2>日志</h2><button id="auditRefresh" type="button">刷新</button></div><div class="tablewrap"><table><thead><tr><th>时间</th><th>设备</th><th>动作</th><th>命令/路径</th><th>退出码</th><th>耗时</th><th>来源</th></tr></thead><tbody id="audits"></tbody></table></div></article></section></main><script src="/static/app.js"></script></body></html>
+1 -1
View File
@@ -1 +1 @@
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
<!doctype html><html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><script>(function(){try{var t=localStorage.getItem("vpc_theme");if(t!=="light"&&t!=="dark")t=matchMedia("(prefers-color-scheme:light)").matches?"light":"dark";document.documentElement.dataset.theme=t}catch(e){document.documentElement.dataset.theme="dark"}})();</script><title>VPS-Commander Login</title><link rel="stylesheet" href="/static/app.css"></head><body class="login"><form id="login"><h1>VPS-Commander</h1><p>Private Infrastructure Console</p><input id="password" type="password" placeholder="面板密码" autocomplete="current-password"><button type="submit">登录</button><div id="error"></div></form><script>document.querySelector("#login").onsubmit=async e=>{e.preventDefault();let r=await fetch("/panel/login",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({password:document.querySelector("#password").value})});if(r.ok)location.href="/panel";else document.querySelector("#error").textContent="密码错误或未配置面板密码"};</script></body></html>
+506 -1
View File
@@ -1 +1,506 @@
*{box-sizing:border-box}body{margin:0;background:#0b0d10;color:#e8edf2;font:14px system-ui,-apple-system,sans-serif}main{max-width:1400px;margin:auto;padding:28px 20px}header{display:flex;justify-content:space-between;align-items:center;margin-bottom:22px}h1{margin:0;font-size:24px}header p{margin:4px 0;color:#7f8b98}.switch{display:flex;gap:4px}.switch button{border:1px solid #2a3139;background:#11161b;color:#aeb8c2;padding:7px 12px;border-radius:7px;cursor:pointer}.switch button.active{color:#fff;border-color:#647180}.card{display:grid;grid-template-columns:1.4fr repeat(7,1fr);gap:12px;align-items:center;border:1px solid #20262d;background:#11161b;border-radius:10px;padding:14px;margin-bottom:10px}.name{display:flex;gap:8px;align-items:center}.on,.off{font-size:12px;padding:2px 6px;border-radius:10px;border:1px solid #303840}.on{color:#9bd6ad}.off{color:#e2a1a1}.card>span,.tr>span{color:#9ca8b4;font-size:13px}.table{border:1px solid #20262d;border-radius:9px;overflow:auto}.tr{min-width:1050px;display:grid;grid-template-columns:1.2fr .8fr 1.2fr .7fr .7fr 1.3fr 1.5fr 1fr;gap:12px;padding:11px 13px;border-bottom:1px solid #1e242a;align-items:center}.tr:last-child{border-bottom:0}.error{color:#e2a1a1}@media(max-width:900px){.card{grid-template-columns:1fr 1fr}.card .name{grid-column:1/-1}}
:root {
--bg-main: #0c0e14;
--bg-card: rgba(22, 27, 34, 0.7);
--bg-card-hover: rgba(28, 35, 45, 0.85);
--border: rgba(255, 255, 255, 0.08);
--border-hover: rgba(255, 255, 255, 0.16);
--text-main: #f0f6fc;
--text-muted: #8b949e;
--text-dim: #6e7681;
--accent: #58a6ff;
--online: #3fb950;
--online-bg: rgba(63, 185, 80, 0.12);
--offline: #f85149;
--offline-bg: rgba(248, 81, 73, 0.12);
--warn: #d29922;
--warn-bg: rgba(210, 153, 34, 0.12);
--font-mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, "Liberation Mono", monospace;
--radius-lg: 14px;
--radius-md: 8px;
--radius-sm: 6px;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
background-color: var(--bg-main);
background-image:
radial-gradient(at 15% 15%, rgba(56, 139, 253, 0.05) 0px, transparent 50%),
radial-gradient(at 85% 85%, rgba(63, 185, 80, 0.04) 0px, transparent 50%);
background-attachment: fixed;
color: var(--text-main);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
min-height: 100vh;
-webkit-font-smoothing: antialiased;
}
.layout {
max-width: 1440px;
margin: 0 auto;
padding: 24px 20px 40px;
display: flex;
flex-direction: column;
min-height: 100vh;
}
/* 导航栏 */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 24px;
flex-wrap: wrap;
gap: 16px;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
}
.logo-dot {
width: 14px;
height: 14px;
background: linear-gradient(135deg, #58a6ff, #1f6feb);
border-radius: 4px;
box-shadow: 0 0 12px rgba(88, 166, 255, 0.5);
}
.brand-text h1 {
font-size: 20px;
font-weight: 700;
letter-spacing: -0.02em;
color: #fff;
display: inline-block;
margin-right: 8px;
}
.brand-text .sub {
font-size: 13px;
color: var(--text-muted);
}
.controls {
display: flex;
align-items: center;
gap: 12px;
}
.summary-badge {
display: flex;
align-items: center;
gap: 8px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid var(--border);
padding: 5px 12px;
border-radius: 20px;
font-size: 12px;
color: var(--text-muted);
}
.dot-online {
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--online);
box-shadow: 0 0 8px rgba(63, 185, 80, 0.6);
animation: pulse 2.5s infinite;
}
@keyframes pulse {
0% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(63, 185, 80, 0.7); }
70% { transform: scale(1); box-shadow: 0 0 0 6px rgba(63, 185, 80, 0); }
100% { transform: scale(0.95); box-shadow: 0 0 0 0 rgba(63, 185, 80, 0); }
}
.view-switch {
display: flex;
background: rgba(22, 27, 34, 0.8);
border: 1px solid var(--border);
border-radius: var(--radius-md);
padding: 3px;
gap: 2px;
}
.view-switch .btn {
display: flex;
align-items: center;
gap: 6px;
background: transparent;
border: none;
color: var(--text-muted);
padding: 5px 12px;
border-radius: var(--radius-sm);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s ease;
}
.view-switch .btn:hover {
color: var(--text-main);
}
.view-switch .btn.active {
background: rgba(255, 255, 255, 0.1);
color: #fff;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);
}
/* 卡片视图 */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(330px, 1fr));
gap: 16px;
}
.node-card {
background: var(--bg-card);
backdrop-filter: blur(12px);
-webkit-backdrop-filter: blur(12px);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
padding: 18px;
display: flex;
flex-direction: column;
gap: 16px;
transition: all 0.2s cubic-bezier(0.16, 1, 0.3, 1);
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}
.node-card:hover {
border-color: var(--border-hover);
background: var(--bg-card-hover);
transform: translateY(-2px);
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.35);
}
.card-top {
display: flex;
justify-content: space-between;
align-items: flex-start;
}
.node-title {
display: flex;
flex-direction: column;
gap: 4px;
}
.node-name-wrap {
display: flex;
align-items: center;
gap: 8px;
}
.node-name {
font-size: 16px;
font-weight: 700;
color: #fff;
letter-spacing: -0.01em;
}
.local-badge {
font-size: 10px;
padding: 1px 6px;
border-radius: 4px;
background: rgba(88, 166, 255, 0.15);
color: var(--accent);
border: 1px solid rgba(88, 166, 255, 0.25);
font-weight: 600;
}
.node-meta {
font-size: 12px;
color: var(--text-dim);
display: flex;
align-items: center;
gap: 8px;
}
.meta-pill {
background: rgba(255, 255, 255, 0.04);
padding: 2px 6px;
border-radius: 4px;
}
.status-badge {
font-size: 11px;
font-weight: 600;
padding: 3px 8px;
border-radius: 12px;
display: flex;
align-items: center;
gap: 5px;
}
.status-badge.online {
background: var(--online-bg);
color: var(--online);
border: 1px solid rgba(63, 185, 80, 0.2);
}
.status-badge.offline {
background: var(--offline-bg);
color: var(--offline);
border: 1px solid rgba(248, 81, 73, 0.2);
}
.status-badge .dot {
width: 6px;
height: 6px;
border-radius: 50%;
background: currentColor;
}
/* 进度条指标区域 */
.metrics-bars {
display: flex;
flex-direction: column;
gap: 12px;
}
.metric-item {
display: flex;
flex-direction: column;
gap: 4px;
}
.metric-header {
display: flex;
justify-content: space-between;
font-size: 12px;
}
.metric-label {
color: var(--text-muted);
font-weight: 500;
}
.metric-value {
color: var(--text-main);
font-family: var(--font-mono);
font-weight: 600;
}
.progress-track {
height: 6px;
background: rgba(255, 255, 255, 0.06);
border-radius: 3px;
overflow: hidden;
position: relative;
}
.progress-fill {
height: 100%;
border-radius: 3px;
transition: width 0.4s ease, background 0.3s ease;
}
.progress-fill.normal {
background: linear-gradient(90deg, #238636, #3fb950);
}
.progress-fill.warn {
background: linear-gradient(90deg, #9e6a03, #d29922);
}
.progress-fill.danger {
background: linear-gradient(90deg, #da3633, #f85149);
}
/* 统计卡片底部小部件 */
.card-stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 8px;
background: rgba(0, 0, 0, 0.2);
border-radius: var(--radius-md);
padding: 10px;
border: 1px solid rgba(255, 255, 255, 0.03);
}
.stat-box {
display: flex;
flex-direction: column;
gap: 2px;
}
.stat-title {
font-size: 11px;
color: var(--text-dim);
}
.stat-desc {
font-size: 12px;
color: var(--text-muted);
font-family: var(--font-mono);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.stat-desc b {
color: var(--text-main);
font-weight: 500;
}
.traffic-in { color: #58a6ff !important; }
.traffic-out { color: #bc8cff !important; }
/* 表格视图 */
.table-wrapper {
background: var(--bg-card);
backdrop-filter: blur(12px);
border: 1px solid var(--border);
border-radius: var(--radius-lg);
overflow-x: auto;
box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}
.probe-table {
width: 100%;
min-width: 960px;
border-collapse: collapse;
text-align: left;
}
.probe-table th {
background: rgba(0, 0, 0, 0.25);
padding: 12px 16px;
font-size: 12px;
font-weight: 600;
color: var(--text-muted);
border-bottom: 1px solid var(--border);
white-space: nowrap;
}
.probe-table td {
padding: 14px 16px;
border-bottom: 1px solid rgba(255, 255, 255, 0.04);
font-size: 13px;
vertical-align: middle;
}
.probe-table tr:last-child td {
border-bottom: none;
}
.probe-table tr:hover td {
background: rgba(255, 255, 255, 0.02);
}
.col-mono {
font-family: var(--font-mono);
font-size: 12px;
}
.mini-bar-wrap {
display: flex;
align-items: center;
gap: 8px;
min-width: 110px;
}
.mini-bar {
flex: 1;
height: 5px;
background: rgba(255, 255, 255, 0.08);
border-radius: 3px;
overflow: hidden;
}
.mini-bar-fill {
height: 100%;
border-radius: 3px;
}
.table-node {
display: flex;
flex-direction: column;
}
.table-node .name {
font-weight: 600;
color: #fff;
}
.table-node .sub {
font-size: 11px;
color: var(--text-dim);
}
/* 页脚 */
.footer {
margin-top: auto;
padding-top: 36px;
display: flex;
justify-content: space-between;
align-items: center;
font-size: 12px;
color: var(--text-dim);
border-top: 1px solid var(--border);
}
.update-time {
font-family: var(--font-mono);
}
/* 错误提示 */
.error-msg {
text-align: center;
padding: 40px;
color: var(--offline);
background: var(--bg-card);
border: 1px dashed rgba(248, 81, 73, 0.3);
border-radius: var(--radius-lg);
}
/* 响应式调整 (Mobile) */
@media (max-width: 768px) {
.layout {
padding: 16px 12px 28px;
}
.navbar {
margin-bottom: 16px;
}
.brand-text h1 {
font-size: 18px;
}
.controls {
width: 100%;
justify-content: space-between;
}
.card-grid {
grid-template-columns: 1fr;
gap: 12px;
}
.node-card {
padding: 14px;
gap: 12px;
}
.card-stats-grid {
grid-template-columns: 1fr;
gap: 6px;
}
.footer {
flex-direction: column;
gap: 8px;
text-align: center;
padding-top: 24px;
}
}
+45 -3
View File
@@ -1,4 +1,46 @@
<!doctype html>
<html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>VPS Probe</title><link rel="stylesheet" href="/static/probe.css"></head>
<body><main><header><div><h1>VPS Probe</h1><p>Infrastructure status</p></div><div class="switch"><button id="cardBtn">卡片</button><button id="compactBtn">表格</button></div></header><section id="content"></section></main><script src="/static/probe.js"></script></body></html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<title>VPS Probe - 节点监控探针</title>
<link rel="stylesheet" href="/static/probe.css?v=20260929">
</head>
<body>
<div class="layout">
<header class="navbar">
<div class="brand">
<div class="logo-dot"></div>
<div class="brand-text">
<h1>VPS Probe</h1>
<span class="sub">服务器集群实时监控</span>
</div>
</div>
<div class="controls">
<div class="summary-badge" id="clusterSummary">
<span class="dot-online"></span>
<span id="summaryText">检测中...</span>
</div>
<div class="view-switch">
<button id="cardBtn" class="btn active" title="卡片视图">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><rect x="3" y="3" width="7" height="7"></rect><rect x="14" y="3" width="7" height="7"></rect><rect x="14" y="14" width="7" height="7"></rect><rect x="3" y="14" width="7" height="7"></rect></svg>
卡片
</button>
<button id="compactBtn" class="btn" title="表格视图">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="3" y1="6" x2="21" y2="6"></line><line x1="3" y1="12" x2="21" y2="12"></line><line x1="3" y1="18" x2="21" y2="18"></line></svg>
表格
</button>
</div>
</div>
</header>
<main id="content" class="card-view"></main>
<footer class="footer">
<span>VPS-Commander Cluster Monitor</span>
<span id="lastUpdated" class="update-time">自动刷新中...</span>
</footer>
</div>
<script src="/static/probe.js?v=20260929"></script>
</body>
</html>
+285 -10
View File
@@ -1,14 +1,289 @@
(() => {
const root = document.querySelector('#content');
const fmtBytes = n => { if (!Number.isFinite(n)) return '-'; const u=['B','KB','MB','GB','TB']; let i=0,v=n; while(v>=1024&&i<u.length-1){v/=1024;i++;} return `${v.toFixed(i?1:0)} ${u[i]}`; };
const summaryEl = document.querySelector('#summaryText');
const lastUpdatedEl = document.querySelector('#lastUpdated');
const fmtBytes = n => {
if (!Number.isFinite(n) || n <= 0) return '0 B';
const u = ['B', 'KB', 'MB', 'GB', 'TB'];
let i = 0, v = n;
while (v >= 1024 && i < u.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
};
const fmtRate = n => `${fmtBytes(n)}/s`;
const fmtUp = n => { let s=Math.max(0,Math.floor(n||0)); const d=Math.floor(s/86400); s%=86400; const h=Math.floor(s/3600); s%=3600; const m=Math.floor(s/60); return d?`${d}天${h}小时`:h?`${h}小时${m}分`:`${m}分`; };
const esc = s => String(s??'-').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));
let mode=localStorage.getItem('vpc_probe_view')||'card';
const setMode=m=>{mode=m;localStorage.setItem('vpc_probe_view',m);render(window.__data||[]);};
document.querySelector('#cardBtn').onclick=()=>setMode('card'); document.querySelector('#compactBtn').onclick=()=>setMode('compact');
const row=(d,card)=>{const p=d.profile||{}; return `<div class="${card?'card':'tr'}"><div class="name"><b>${esc(d.name)}</b><span class="${d.status==='online'?'on':'off'}">${d.status==='online'?'在线':'离线'}</span></div><span>Uptime ${fmtUp(p.uptime_seconds)}</span><span>Load ${[p.load_1m,p.load_5m,p.load_15m].map(x=>Number(x||0).toFixed(2)).join(' / ')}</span><span>CPU ${p.cpu_usage_percent??'-'}%</span><span>MEM ${p.mem_percent??'-'}%</span><span>↓ ${fmtRate(p.net_rx_rate)} ↑ ${fmtRate(p.net_tx_rate)}</span><span>流量 ↓ ${fmtBytes(p.net_rx_total)} ↑ ${fmtBytes(p.net_tx_total)}</span><span>Disk ${p.disk_free||'-'} ${p.disk_percent??'-'}%</span></div>`;};
function render(data){document.querySelector('#cardBtn').classList.toggle('active',mode==='card');document.querySelector('#compactBtn').classList.toggle('active',mode==='compact');root.className=mode;root.innerHTML=mode==='card'?data.map(d=>row(d,true)).join(''):`<div class="table">${data.map(d=>row(d,false)).join('')}</div>`;}
async function load(){try{const r=await fetch('/probe/summary',{cache:'no-store'});if(!r.ok)throw Error();window.__data=await r.json();render(window.__data);}catch(e){root.innerHTML='<p class="error">探针数据暂时不可用</p>';}}
load();setInterval(load,5000);
const fmtUp = n => {
let s = Math.max(0, Math.floor(n || 0));
if (s <= 0) return '--';
const d = Math.floor(s / 86400);
s %= 86400;
const h = Math.floor(s / 3600);
s %= 3600;
const m = Math.floor(s / 60);
if (d > 0) return `${d}天 ${h}时`;
if (h > 0) return `${h}小时 ${m}分`;
return `${m} 分钟`;
};
const esc = s => String(s ?? '-').replace(/[&<>"']/g, c => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;'
}[c]));
const getFlag = (cc, country) => {
if (!cc || typeof cc !== 'string' || cc.length !== 2) return '';
const code = cc.toUpperCase();
const flag = String.fromCodePoint(...[...code].map(c => 0x1F1E6 - 65 + c.charCodeAt(0)));
const title = country ? `${country} (${code})` : code;
return `<span class="flag-icon" title="${esc(title)}">${flag}</span>`;
};
const getStatusLevel = pct => {
const val = Number(pct || 0);
if (val >= 85) return 'danger';
if (val >= 65) return 'warn';
return 'normal';
};
let mode = localStorage.getItem('vpc_probe_view') || 'card';
const setMode = m => {
mode = m;
localStorage.setItem('vpc_probe_view', m);
render(window.__data || []);
};
document.querySelector('#cardBtn').onclick = () => setMode('card');
document.querySelector('#compactBtn').onclick = () => setMode('compact');
const renderCard = d => {
const p = d.profile || {};
const isOnline = d.status === 'online';
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(', ');
return `
<div class="node-card">
<div class="card-top">
<div class="node-title">
<div class="node-name-wrap">
${getFlag(d.country_code, d.country)}
<span class="node-name">${esc(d.name)}</span>
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
</div>
<div class="node-meta">
<span class="meta-pill">${p.cpu_cores || 1} 核</span>
<span class="meta-pill">${esc(d.os || 'Linux')}</span>
<span>${fmtUp(p.uptime_seconds)}</span>
</div>
</div>
<div class="status-badge ${isOnline ? 'online' : 'offline'}">
<span class="dot"></span>
${isOnline ? '在线' : '离线'}
</div>
</div>
<div class="metrics-bars">
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">CPU 负载</span>
<span class="metric-value">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
</div>
</div>
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">内存 (空闲 ${esc(p.mem_available || '--')})</span>
<span class="metric-value">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
</div>
</div>
<div class="metric-item">
<div class="metric-header">
<span class="metric-label">磁盘 (空闲 ${esc(p.disk_free || '--')})</span>
<span class="metric-value">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
</div>
<div class="progress-track">
<div class="progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
</div>
</div>
</div>
<div class="card-stats-grid">
<div class="stat-box">
<span class="stat-title">实时网络 (↓ / ↑)</span>
<span class="stat-desc">
<b class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</b> /
<b class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</b>
</span>
</div>
<div class="stat-box">
<span class="stat-title">总流量 (↓ / ↑)</span>
<span class="stat-desc">
↓ ${fmtBytes(p.net_rx_total)} / ↑ ${fmtBytes(p.net_tx_total)}
</span>
</div>
<div class="stat-box">
<span class="stat-title">系统平均负载 (1/5/15m)</span>
<span class="stat-desc">${loadStr}</span>
</div>
<div class="stat-box">
<span class="stat-title">IO PSI / Docker</span>
<span class="stat-desc">${p.io_psi != null ? Number(p.io_psi).toFixed(2) : '0.00'} / ${p.docker ? '有' : '无'}</span>
</div>
</div>
</div>
`;
};
const renderTable = list => {
const rows = list.map(d => {
const p = d.profile || {};
const isOnline = d.status === 'online';
const cpuPct = p.cpu_usage_percent != null ? Number(p.cpu_usage_percent) : 0;
const memPct = p.mem_percent != null ? Number(p.mem_percent) : 0;
const diskPct = p.disk_percent != null ? Number(p.disk_percent) : 0;
const loadStr = [p.load_1m, p.load_5m, p.load_15m].map(x => Number(x || 0).toFixed(2)).join(' / ');
return `
<tr>
<td>
<div class="table-node">
<span class="name">
${getFlag(d.country_code, d.country)}
${esc(d.name)}
${d.is_local ? '<span class="local-badge">本机</span>' : ''}
</span>
<span class="sub">${p.cpu_cores || 1}核 | ${esc(d.os || 'Linux')}</span>
</div>
</td>
<td>
<span class="status-badge ${isOnline ? 'online' : 'offline'}">
<span class="dot"></span>
${isOnline ? '在线' : '离线'}
</span>
</td>
<td class="col-mono">${fmtUp(p.uptime_seconds)}</td>
<td class="col-mono">${loadStr}</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(cpuPct)}" style="width: ${Math.min(100, Math.max(0, cpuPct))}%"></div>
</div>
<span class="col-mono">${p.cpu_usage_percent != null ? `${cpuPct}%` : '--'}</span>
</div>
</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(memPct)}" style="width: ${Math.min(100, Math.max(0, memPct))}%"></div>
</div>
<span class="col-mono">${p.mem_percent != null ? `${memPct}%` : '--'}</span>
</div>
</td>
<td class="col-mono">
<span class="traffic-in">↓ ${fmtRate(p.net_rx_rate)}</span><br>
<span class="traffic-out">↑ ${fmtRate(p.net_tx_rate)}</span>
</td>
<td class="col-mono">
↓ ${fmtBytes(p.net_rx_total)}<br>
↑ ${fmtBytes(p.net_tx_total)}
</td>
<td>
<div class="mini-bar-wrap">
<div class="mini-bar">
<div class="mini-bar-fill progress-fill ${getStatusLevel(diskPct)}" style="width: ${Math.min(100, Math.max(0, diskPct))}%"></div>
</div>
<span class="col-mono">${p.disk_percent != null ? `${diskPct}%` : '--'}</span>
</div>
</td>
</tr>
`;
}).join('');
return `
<div class="table-wrapper">
<table class="probe-table">
<thead>
<tr>
<th>节点名称</th>
<th>状态</th>
<th>运行时间</th>
<th>负载 (1/5/15m)</th>
<th>CPU</th>
<th>内存</th>
<th>实时网速</th>
<th>累计流量</th>
<th>磁盘</th>
</tr>
</thead>
<tbody>
${rows}
</tbody>
</table>
</div>
`;
};
function render(data) {
document.querySelector('#cardBtn').classList.toggle('active', mode === 'card');
document.querySelector('#compactBtn').classList.toggle('active', mode === 'compact');
const total = data.length;
const onlineCount = data.filter(x => x.status === 'online').length;
if (summaryEl) {
summaryEl.textContent = `${onlineCount} / ${total} 节点在线`;
}
if (!data || data.length === 0) {
root.innerHTML = '<div class="error-msg">暂无节点数据</div>';
return;
}
if (mode === 'card') {
root.className = 'card-view';
root.innerHTML = `<div class="card-grid">${data.map(renderCard).join('')}</div>`;
} else {
root.className = 'table-view';
root.innerHTML = renderTable(data);
}
}
async function load() {
try {
const r = await fetch('/probe/summary', { cache: 'no-store' });
if (!r.ok) throw Error();
let rawData = await r.json();
if (Array.isArray(rawData)) {
rawData.sort((a, b) => {
if (a.is_local && !b.is_local) return -1;
if (!a.is_local && b.is_local) return 1;
return String(a.name || "").localeCompare(String(b.name || ""));
});
}
window.__data = rawData;
render(window.__data);
if (lastUpdatedEl) {
const now = new Date();
const timeStr = `${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}:${String(now.getSeconds()).padStart(2, '0')}`;
lastUpdatedEl.textContent = `更新于 ${timeStr}`;
}
} catch (e) {
root.innerHTML = '<div class="error-msg">探针数据暂时不可用,正在重试...</div>';
}
}
load();
setInterval(load, 5000);
})();