astrbot_plugin_route_gateway/pages/routes/index.html

281 行
11 KiB
HTML

<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Codex 线路管理</title>
<style>
:root {
--bg: #f7f8fa; --card: #fff; --line: #e4e6eb; --fg: #1f2329; --muted: #6b7280;
--accent: #2f6feb; --ok: #16a34a; --bad: #dc2626; --warn: #b45309;
}
@media (prefers-color-scheme: dark) {
:root { --bg:#16181d; --card:#1e2127; --line:#31343b; --fg:#e6e8ec; --muted:#9aa1ac; --accent:#5b8cff; }
}
* { box-sizing: border-box; }
body { margin:0; padding:16px; background:var(--bg); color:var(--fg);
font:14px/1.6 -apple-system,BlinkMacSystemFont,"Segoe UI","Noto Sans CJK SC",sans-serif; }
.card { background:var(--card); border:1px solid var(--line); border-radius:10px;
padding:16px; margin-bottom:16px; }
h2 { margin:0 0 4px; font-size:16px; }
.sub { color:var(--muted); font-size:12px; margin-bottom:12px; }
table { width:100%; border-collapse:collapse; }
th,td { text-align:left; padding:8px 6px; border-bottom:1px solid var(--line); vertical-align:middle; }
th { color:var(--muted); font-weight:600; font-size:12px; }
code { background:rgba(127,127,127,.14); padding:1px 5px; border-radius:4px; font-size:12px; }
button { font:inherit; padding:5px 12px; border-radius:6px; border:1px solid var(--line);
background:var(--card); color:var(--fg); cursor:pointer; }
button:hover:not(:disabled) { border-color:var(--accent); color:var(--accent); }
button:disabled { opacity:.45; cursor:not-allowed; }
button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
button.danger:hover:not(:disabled) { border-color:var(--bad); color:var(--bad); }
.row { display:flex; gap:8px; flex-wrap:wrap; align-items:flex-end; }
.field { display:flex; flex-direction:column; gap:4px; }
.field label { font-size:12px; color:var(--muted); }
input, select { font:inherit; padding:6px 8px; border:1px solid var(--line);
border-radius:6px; background:var(--bg); color:var(--fg); min-width:150px; }
.pill { font-size:11px; padding:1px 7px; border-radius:999px; border:1px solid var(--line); }
.pill.active { color:var(--ok); border-color:var(--ok); }
.note { font-size:12px; color:var(--warn); margin-top:8px; }
#toast { position:fixed; right:16px; bottom:16px; max-width:min(460px,80vw);
background:var(--card); border:1px solid var(--line); border-left-width:4px;
border-radius:8px; padding:10px 14px; box-shadow:0 6px 20px rgba(0,0,0,.14);
opacity:0; transform:translateY(8px); transition:.18s; pointer-events:none; }
#toast.show { opacity:1; transform:none; }
#toast.ok { border-left-color:var(--ok); } #toast.bad { border-left-color:var(--bad); }
</style>
</head>
<body>
<div class="card">
<h2>线路</h2>
<div class="sub">切换会先跑连通性检查,失败自动回滚。删除是软删除,可用 <code>/route rollback</code> 找回。</div>
<table id="routes"><thead>
<tr><th>ID</th><th>模型</th><th>端点</th><th style="width:210px">操作</th></tr>
</thead><tbody><tr><td colspan="4">加载中…</td></tr></tbody></table>
</div>
<div class="card">
<h2>新增线路</h2>
<div class="sub">密钥引用必须先在下方导入。</div>
<div class="row">
<div class="field"><label>线路 ID</label><input id="c_id" placeholder="2X" /></div>
<div class="field"><label>密钥引用</label><select id="c_secret"></select></div>
<div class="field" style="flex:1"><label>Base URL</label>
<input id="c_url" placeholder="https://example.com/v1" style="width:100%" /></div>
<div class="field"><label>模型</label><input id="c_model" placeholder="gpt-5.6-sol" /></div>
<div class="field"><label>显示名(可选)</label><input id="c_name" placeholder="2X" /></div>
<button class="primary" id="c_go">创建</button>
</div>
</div>
<div class="card">
<h2>密钥引用</h2>
<div class="sub">
密钥写入后<strong>无法再读出</strong>——本页面和所有接口都只返回引用名。仍被线路引用的密钥不可删除。
</div>
<table id="secrets"><thead>
<tr><th>引用名</th><th>被引用线路数</th><th style="width:110px">操作</th></tr>
</thead><tbody><tr><td colspan="3">加载中…</td></tr></tbody></table>
<div class="row" style="margin-top:12px">
<div class="field"><label>引用名</label><input id="s_ref" placeholder="relay_2x" /></div>
<div class="field" style="flex:1"><label>密钥值</label>
<input id="s_val" type="password" autocomplete="new-password" placeholder="sk-…" style="width:100%" /></div>
<button class="primary" id="s_go">导入</button>
</div>
<div class="note">
面板当前未启用 TLS,密钥会以明文经过局域网。这是已知并被接受的取舍。
</div>
</div>
<div id="toast"></div>
<script>
let B = null;
const PAGE_ENDPOINT_PREFIX = "page";
const $ = (id) => document.getElementById(id);
let busy = false;
function toast(msg, ok = true) {
const t = $("toast");
t.textContent = msg;
t.className = "show " + (ok ? "ok" : "bad");
clearTimeout(t._h);
t._h = setTimeout(() => (t.className = ""), 4200);
}
function setBusy(v) {
busy = v;
document.querySelectorAll("button").forEach((b) => (b.disabled = v));
}
async function call(method, endpoint, body) {
if (!B) throw new Error("页面桥接尚未就绪,请稍后重试");
const url = new URL(endpoint, "https://astrbot-plugin-page.local/");
const routePath = url.pathname
.replace(/^\/route-gateway\/?/, "")
.replace(/^\/+/, "");
const pageEndpoint = `${PAGE_ENDPOINT_PREFIX}/${routePath}`.replace(/\/+/g, "/");
const params = Object.fromEntries(url.searchParams.entries());
const res = method === "GET"
? await B.apiGet(pageEndpoint, Object.keys(params).length ? params : undefined)
: await B.apiPost(pageEndpoint, body || {});
// The dashboard forwards the plugin's payload verbatim.
if (res && res.status === "error") throw new Error(res.message || "请求失败");
return res && res.data ? res.data : {};
}
async function guard(label, fn) {
if (busy) return;
setBusy(true);
try {
const msg = await fn();
toast(msg || (label + "完成"), true);
await refresh();
} catch (e) {
toast(label + "失败:" + (e && e.message ? e.message : e), false);
} finally {
setBusy(false);
}
}
function renderRoutes(routes) {
const tb = $("routes").querySelector("tbody");
if (!routes.length) { tb.innerHTML = '<tr><td colspan="4">暂无线路</td></tr>'; return; }
tb.innerHTML = "";
for (const r of routes) {
const id = r.route_id || r.id || "-";
const active = r.active === true || r.is_active === true;
const tr = document.createElement("tr");
const name = r.display_name && r.display_name !== id ? ` <span class="pill">${esc(r.display_name)}</span>` : "";
tr.innerHTML =
`<td><code>${esc(id)}</code>${active ? ' <span class="pill active">当前</span>' : ""}${name}</td>` +
`<td>${esc(r.model || "-")}</td><td>${esc(r.endpoint || "-")}</td><td></td>`;
const cell = tr.lastElementChild;
cell.append(
btn("检测", () => guard("检测", async () => (await call("POST", "/route-gateway/routes/test", { route_id: id })).message || "检测通过")),
);
if (!active) {
cell.append(
btn("切换", () => guard("切换", async () => (await call("POST", "/route-gateway/routes/use", { route_id: id })).message || "已切换"), "primary"),
btn("删除", () => {
if (!confirm(`软删除线路 ${id}?可用 /route rollback 找回。`)) return;
guard("删除", async () => (await call("POST", "/route-gateway/routes/delete", { route_id: id })).message || "已删除");
}, "danger"),
);
}
tb.append(tr);
}
}
function renderSecrets(secrets) {
const tb = $("secrets").querySelector("tbody");
const sel = $("c_secret");
sel.innerHTML = "";
if (!secrets.length) {
tb.innerHTML = '<tr><td colspan="3">还没有密钥引用,请先在下方导入</td></tr>';
return;
}
tb.innerHTML = "";
for (const s of secrets) {
const used = Number(s.used_by_routes || 0);
const tr = document.createElement("tr");
tr.innerHTML = `<td><code>${esc(s.secret_ref)}</code></td><td>${used}</td><td></td>`;
const del = btn("删除", () => {
if (!confirm(`删除密钥引用 ${s.secret_ref}?此操作不可恢复。`)) return;
guard("删除密钥", async () => (await call("POST", "/route-gateway/secrets/delete", { secret_ref: s.secret_ref })).message || "已删除");
}, "danger");
if (used > 0) { del.disabled = true; del.title = "仍被线路引用"; }
tr.lastElementChild.append(del);
tb.append(tr);
sel.append(new Option(s.secret_ref, s.secret_ref));
}
}
function btn(label, onClick, cls) {
const b = document.createElement("button");
b.textContent = label;
if (cls) b.className = cls;
b.style.marginRight = "6px";
b.onclick = onClick;
return b;
}
const esc = (s) => String(s == null ? "" : s).replace(/[&<>"']/g, (c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" }[c]));
async function refresh() {
try {
const [routes, secrets] = await Promise.all([
call("GET", "/route-gateway/routes"),
call("GET", "/route-gateway/secrets"),
]);
renderRoutes(routes.routes || []);
renderSecrets(secrets.secrets || []);
} catch (e) {
toast("加载失败:" + (e && e.message ? e.message : e), false);
}
}
$("c_go").onclick = () =>
guard("创建线路", async () => {
const payload = {
route_id: $("c_id").value.trim(),
secret_ref: $("c_secret").value,
base_url: $("c_url").value.trim(),
model: $("c_model").value.trim(),
display_name: $("c_name").value.trim(),
};
const r = await call("POST", "/route-gateway/routes/create", payload);
["c_id", "c_url", "c_model", "c_name"].forEach((i) => ($(i).value = ""));
return r.message || "线路已创建";
});
$("s_go").onclick = () =>
guard("导入密钥", async () => {
const ref = $("s_ref").value.trim().toLowerCase();
const val = $("s_val").value;
const r = await call("POST", "/route-gateway/secrets/import", { secret_ref: ref, value: val });
// Clear immediately — the value must not linger in the DOM.
$("s_val").value = "";
$("s_ref").value = "";
return r.message || "密钥已导入";
});
function getBridge() {
if (window.AstrBotPluginPage) return window.AstrBotPluginPage;
try {
if (window.parent && window.parent !== window && window.parent.AstrBotPluginPage) {
return window.parent.AstrBotPluginPage;
}
} catch (error) {
return null;
}
return null;
}
async function waitForBridge(timeoutMs = 5000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const candidate = getBridge();
if (
candidate &&
typeof candidate.ready === "function" &&
typeof candidate.apiGet === "function" &&
typeof candidate.apiPost === "function"
) {
B = candidate;
return candidate;
}
await new Promise((resolve) => setTimeout(resolve, 25));
}
throw new Error("未能初始化 AstrBot 页面桥接");
}
waitForBridge()
.then((bridge) => bridge.ready())
.then(refresh)
.catch((error) => toast(`页面初始化失败:${error.message}`, false));
</script>
</body>
</html>