Files
codex_auto/maintain/templates/dashboard.html
T
2026-03-23 21:42:02 +08:00

633 lines
34 KiB
HTML
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.
<!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: #0f1419;
--panel: #161b22;
--border: #30363d;
--text: #e6edf3;
--muted: #8b949e;
--accent: #1f6feb;
--ok: #238636;
--warn: #d29922;
--bad: #f85149;
}
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); min-height: 100vh; }
header { display: flex; align-items: center; justify-content: space-between; padding: 12px 24px; border-bottom: 1px solid var(--border); background: var(--panel); }
header h1 { margin: 0; font-size: 1.15rem; font-weight: 600; }
.tabs { display: flex; gap: 4px; padding: 0 24px; background: var(--panel); border-bottom: 1px solid var(--border); }
.tabs button { background: transparent; border: 0; color: var(--muted); padding: 12px 16px; cursor: pointer; border-bottom: 2px solid transparent; font-size: 0.9rem; }
.tabs button.active { color: var(--text); border-bottom-color: var(--accent); }
main { padding: 20px 24px; max-width: 1200px; margin: 0 auto; }
.section { display: none; }
.section.visible { display: block; }
.banner { background: rgba(31, 111, 235, 0.15); border: 1px solid var(--accent); border-radius: 8px; padding: 12px 16px; margin-bottom: 20px; font-size: 0.9rem; }
.banner.idle { display: none; }
.cards { display: grid; grid-template-columns: repeat(4, 1fr); gap: 16px; margin-bottom: 24px; }
@media (max-width: 900px) { .cards { grid-template-columns: repeat(2, 1fr); } }
.card { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 16px; }
.card .label { color: var(--muted); font-size: 0.8rem; margin-bottom: 6px; }
.card .value { font-size: 1.5rem; font-weight: 700; }
.card .sub { font-size: 0.8rem; color: var(--muted); margin-top: 4px; }
table { width: 100%; border-collapse: collapse; background: var(--panel); border: 1px solid var(--border); border-radius: 10px; overflow: hidden; }
th, td { text-align: left; padding: 12px 14px; border-bottom: 1px solid var(--border); font-size: 0.875rem; }
th { color: var(--muted); font-weight: 500; }
tr:last-child td { border-bottom: 0; }
.tag { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 0.75rem; }
.tag.ok { background: rgba(35, 134, 54, 0.2); color: #3fb950; }
.tag.warn { background: rgba(210, 153, 34, 0.2); color: #e3b341; }
.tag.bad { background: rgba(248, 81, 73, 0.15); color: var(--bad); }
.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 24px; }
@media (max-width: 800px) { .grid2 { grid-template-columns: 1fr; } }
.panel { background: var(--panel); border: 1px solid var(--border); border-radius: 10px; padding: 18px; }
.panel h3 { margin: 0 0 14px; font-size: 1rem; }
label { display: block; font-size: 0.8rem; color: var(--muted); margin-bottom: 4px; }
input, select { width: 100%; padding: 8px 10px; border-radius: 6px; border: 1px solid var(--border); background: #0d1117; color: var(--text); margin-bottom: 12px; }
.row { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
.row input { width: auto; margin: 0; }
button.primary { background: var(--accent); color: #fff; border: 0; padding: 10px 16px; border-radius: 8px; font-weight: 600; cursor: pointer; }
button.primary:hover { filter: brightness(1.1); }
button.ghost { background: transparent; border: 1px solid var(--border); color: var(--text); padding: 8px 12px; border-radius: 8px; cursor: pointer; }
.proxy-list { max-height: 220px; overflow: auto; margin-bottom: 12px; }
.proxy-item { display: flex; justify-content: space-between; align-items: center; padding: 8px 0; border-bottom: 1px solid var(--border); font-size: 0.85rem; }
.toast { position: fixed; bottom: 20px; right: 20px; background: var(--panel); border: 1px solid var(--border); padding: 12px 16px; border-radius: 8px; display: none; z-index: 99; }
.task-log { width: 100%; border-collapse: collapse; font-size: 0.8rem; }
.task-log th { padding: 8px 10px; color: var(--muted); font-weight: 500; text-align: left; border-bottom: 1px solid var(--border); }
.task-log td { padding: 8px 10px; border-bottom: 1px solid var(--border); vertical-align: top; }
.task-log tr:last-child td { border-bottom: 0; }
.task-log .st-err { color: var(--bad); }
.task-log .st-run { color: #58a6ff; }
.task-log .st-done { color: #3fb950; }
.task-msg { max-width: min(48vw, 520px); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.log-pre { margin: 0; max-height: 65vh; overflow: auto; background: #0d1117; border: 1px solid var(--border); border-radius: 8px; padding: 12px; font-size: 0.78rem; line-height: 1.45; white-space: pre-wrap; word-break: break-all; font-family: ui-monospace, monospace; }
</style>
</head>
<body>
<header>
<h1>Codex 自动维护</h1>
<div style="display:flex;gap:8px;flex-wrap:wrap;align-items:center">
<button class="ghost" type="button" id="btnRefreshData">刷新数据</button>
<button class="ghost" type="button" id="btnSyncForms">同步表单</button>
<button class="ghost" type="button" id="btnLogout">退出登录</button>
</div>
</header>
<nav class="tabs">
<button type="button" class="active" data-tab="task">任务中心</button>
<button type="button" data-tab="pipeline">流水线</button>
<button type="button" data-tab="proxy">代理池</button>
<button type="button" data-tab="config">配置编辑</button>
<button type="button" data-tab="logs">运行日志</button>
<button type="button" data-tab="sec">安全设置</button>
</nav>
<main>
<div id="section-task" class="section visible">
<div class="banner idle" id="taskBanner"></div>
<div class="panel" style="margin-bottom:16px;padding:12px 16px">
<span style="color:var(--muted)">子进程流水线</span> — <span id="pipeHint">—</span>
</div>
<div class="panel" style="margin-bottom:16px">
<div style="display:flex;justify-content:space-between;align-items:flex-start;gap:12px;flex-wrap:wrap;margin-bottom:10px">
<h3 style="margin:0;font-size:0.95rem">任务进度与历史</h3>
<span style="color:var(--muted);font-size:0.75rem;max-width:420px;line-height:1.4">自动轮询只更新此处与统计、账号表、流水线摘要,<strong>不会</strong>改写各页配置表单。填表前可先点「同步表单」拉服务端当前值。</span>
</div>
<div style="overflow-x:auto">
<table class="task-log">
<thead><tr><th>#</th><th>类型</th><th>状态</th><th>进度</th><th>说明</th><th>更新</th></tr></thead>
<tbody id="recentTasksBody"></tbody>
</table>
</div>
</div>
<div class="cards">
<div class="card"><div class="label">账号总数</div><div class="value" id="stTotal">—</div></div>
<div class="card"><div class="label">有效账号</div><div class="value" id="stCand">—</div><div class="sub" id="stCandSub"></div></div>
<div class="card"><div class="label">目标阈值</div><div class="value" id="stTarget">—</div></div>
<div class="card"><div class="label">健康度</div><div class="value" id="stHealth">—</div><div class="sub" id="stHealthLbl"></div></div>
</div>
<p id="oauthStatsDirHint" style="margin:0 0 16px;font-size:0.78rem;color:var(--muted);line-height:1.45;word-break:break-all"></p>
<h2 style="font-size:1rem;margin:0 0 12px;color:var(--muted)">账号池</h2>
<table>
<thead><tr><th>名称</th><th>有效 / 本地文件</th><th>目标</th><th>健康度</th><th>缺口</th><th>状态</th><th>操作</th></tr></thead>
<tbody id="cpaBody"></tbody>
</table>
<div class="grid2">
<div class="panel">
<h3>自动巡检 → 批量补号</h3>
<p style="color:var(--muted);font-size:0.8rem;margin:0 0 12px;line-height:1.5">按间隔 <strong>Cliproxy 管理 API</strong> 全量探测;<strong>失败条目删本地 JSON</strong>(预检密钥;超时/5xx/401 不删)。再按有效数算缺口,<strong>仍不足则自动进程内批量注册</strong>,每批不超过配置里的 <strong>单次自动注册上限</strong>(与手动补号共锁,勿并行)。</p>
<div class="row"><input type="checkbox" id="autoEn" /><label for="autoEn" style="margin:0">启用自动巡检</label></div>
<label>巡检间隔(分钟)</label>
<input type="number" id="intervalMin" min="5" value="60" />
<button class="primary" type="button" id="saveInspect">保存巡检设置</button>
</div>
<div class="panel">
<h3>手动巡检</h3>
<button class="primary" type="button" id="btnInspectNow" style="width:100%;margin-bottom:14px">立即巡检(探测删失效 → 不足则批量注册)</button>
<button class="ghost" type="button" id="btnSweepFailedNow" style="width:100%;margin-bottom:14px">立即按失败阈值清理(/usage → /auth-files)</button>
<label>单次批量注册数量</label>
<input type="number" id="manualCount" min="1" max="500" value="20" />
<div id="manualCpaWrap">
<label>账号池</label>
<select id="manualCpa"></select>
</div>
<p id="manualCpaSingle" style="display:none;color:var(--muted);font-size:0.85rem;margin:0 0 12px"></p>
<div class="row"><input type="checkbox" id="manualS5" checked /><label for="manualS5" style="margin:0">本次任务启用代理池随机注册</label></div>
<button class="primary" type="button" id="btnManual">开始批量注册</button>
</div>
</div>
</div>
<div id="section-pipeline" class="section">
<div class="panel" style="margin-bottom:16px">
<h3>当前状态</h3>
<pre id="pipeStatus" style="margin:0;font-size:0.8rem;color:var(--muted);white-space:pre-wrap;word-break:break-all"></pre>
</div>
<div class="grid2">
<div class="panel">
<h3>定时:run.py → 迁出 JSON</h3>
<div class="row"><input type="checkbox" id="pipeAuto" /><label for="pipeAuto" style="margin:0">启用定时流水线</label></div>
<label>间隔(分钟)</label>
<input type="number" id="pipeInterval" min="1" value="10" />
<label>Python 可执行文件</label>
<input type="text" id="pipePy" placeholder="python3" />
<label>子进程超时(秒)</label>
<input type="number" id="pipeTimeout" min="60" value="480" />
<div class="row"><input type="checkbox" id="pipeExit0" /><label for="pipeExit0" style="margin:0">迁出 0 个时仍发钉钉告警</label></div>
<button class="primary" type="button" id="savePipe">保存流水线设置</button>
</div>
<div class="panel">
<h3>路径与钉钉</h3>
<label>run.py 绝对路径</label>
<input type="text" id="pipeRunScript" />
<label>OAuth 目录(源)</label>
<input type="text" id="pipeOauth" />
<label>迁出目标目录</label>
<input type="text" id="pipeTarget" />
<label>钉钉 Webhook(可选)</label>
<input type="text" id="pipeDing" />
<label>钉钉 Secret(可选)</label>
<input type="text" id="pipeDingSec" />
<button class="primary" type="button" id="btnPipeOnce" style="width:100%">立即执行一次(run.py + 迁出)</button>
</div>
</div>
<p style="color:var(--muted);font-size:0.8rem;margin-top:14px">定时流水线按维护台当前统计的<strong>有效账号缺口</strong>(已配置管理端且跑过巡检后,与探测结果一致;否则按本地文件数)。充足则跳过。勿与 <code>scripts/cpa_runner.py</code> 双开。</p>
</div>
<div id="section-proxy" class="section">
<div class="panel">
<h3>代理池(HTTP / HTTPS / SOCKS5 URL 每行一条)</h3>
<div class="proxy-list" id="proxyList"></div>
<label>新增代理 URL</label>
<input type="text" id="newProxyUrl" placeholder="socks5://127.0.0.1:1080 或 http://127.0.0.1:7890" />
<label>备注</label>
<input type="text" id="newProxyLabel" placeholder="可选" />
<button class="primary" type="button" id="btnAddProxy">添加</button>
</div>
</div>
<div id="section-config" class="section">
<div class="panel">
<h3>Cliproxy 管理端(巡检必填)</h3>
<p style="color:var(--muted);font-size:0.8rem;margin:0 0 12px;line-height:1.5">与 <a href="https://help.router-for.me/cn/management/api" target="_blank" rel="noopener">管理 API</a> 一致。若<strong>注册成功后的 JSON 已迁入 Cliproxy 的 auth 目录</strong>,须填写下方「统计目录」为该目录绝对路径,否则维护台仍只扫项目内 <code>accounts/oauth</code>,账号数会显示 0。巡检按该目录下的文件名调用 <code>auth-files/models</code>;删除失效 JSON 也在该目录内。密钥存 SQLite。</p>
<label>统计 / 巡检用 Codex JSON 目录(留空 = 项目内 accounts/oauth)</label>
<input type="text" id="cfgStatsOauthDir" placeholder="/root/.cli-proxy-api 或你的 CPA auth 绝对路径" />
<label>管理 Base(如 http://127.0.0.1:8317,勿带 /v0/management)</label>
<input type="text" id="cfgClipBase" placeholder="http://127.0.0.1:8317" />
<label>Management Key(Bearer)</label>
<input type="password" id="cfgClipKey" autocomplete="new-password" placeholder="留空表示不修改已保存的密钥" />
<label>探测超时(秒)</label>
<input type="number" id="cfgClipTimeout" min="5" max="120" value="30" />
<label>失效清理阈值(连续失败次数)</label>
<input type="number" id="cfgSweepThreshold" min="1" max="20" value="3" />
<label>失效清理模式</label>
<select id="cfgSweepMode">
<option value="delete">delete(实际删除)</option>
<option value="observe">observe(仅观察)</option>
</select>
<div class="row"><input type="checkbox" id="cfgSweepNameFallback" checked /><label for="cfgSweepNameFallback" style="margin:0">启用 name 回退匹配</label></div>
<button class="primary" type="button" id="saveCliproxy">保存 Cliproxy 设置</button>
</div>
<div class="panel">
<h3>运行参数</h3>
<label>巡检后自动补号:每批最多注册个数(≤500,受缺口裁剪)</label>
<input type="number" id="cfgMaxAutoReg" min="1" max="500" value="30" />
<label>默认并行线程数(注册)</label>
<input type="number" id="cfgThreads" min="1" max="16" value="1" />
<div class="row"><input type="checkbox" id="cfgSkipOauth" /><label for="cfgSkipOauth" style="margin:0">仅注册、跳过 OAuth(unoauth)</label></div>
<label>无代理池时的默认代理(可选)</label>
<input type="text" id="cfgDefaultProxy" placeholder="留空则直连" />
<button class="primary" type="button" id="saveConfig">保存配置</button>
</div>
</div>
<div id="section-logs" class="section">
<div class="panel">
<h3>运行日志(文件尾部)</h3>
<p style="color:var(--muted);font-size:0.8rem;line-height:1.55;margin:0 0 14px">
<strong>维护台</strong>:巡检 / 批量补号排队与异常写入 <code>maintain/data/maintain_runtime.log</code>。<br />
<strong>流水线</strong>:<code>run.py</code> 的 stdout/stderr 及迁出记录写入 SQLite 里的 <code>pipeline_log_file</code>(默认 <code>maintain/data/pipeline.log</code>)。<br />
服务器上也可 <code>tail -f maintain/data/maintain_runtime.log</code> 实时看。
</p>
<div class="row" style="flex-wrap:wrap;margin-bottom:10px">
<label style="margin:0;display:flex;align-items:center;gap:8px;width:auto">
来源
<select id="logSource" style="width:auto;min-width:220px;margin:0">
<option value="runtime">维护台 runtime</option>
<option value="pipeline">流水线 pipeline</option>
</select>
</label>
<label style="margin:0;display:flex;align-items:center;gap:8px;width:auto">
行数
<input type="number" id="logLines" min="50" max="2000" value="400" style="width:90px;margin:0" />
</label>
<button class="primary" type="button" id="btnLogReload" style="margin:0">加载日志</button>
<div class="row" style="margin:0"><input type="checkbox" id="logAuto" /><label for="logAuto" style="margin:0">本页打开时每 15 秒自动加载</label></div>
</div>
<div id="logPath" style="font-size:0.75rem;color:var(--muted);margin-bottom:8px"></div>
<pre class="log-pre" id="logPre">(点「加载日志」)</pre>
</div>
</div>
<div id="section-sec" class="section">
<div class="panel">
<h3>安全</h3>
<p style="color:var(--muted);font-size:0.9rem;line-height:1.6">
登录密码由环境变量 <code>CODEX_MAINTAIN_PASSWORD</code> 控制(默认 <code>admin</code>)。<br />
生产环境请同时设置 <code>CODEX_MAINTAIN_SECRET</code> 作为会话密钥。
</p>
</div>
</div>
</main>
<div class="toast" id="toast"></div>
<script>
const $ = (id) => document.getElementById(id);
let lastOverview = null;
function toast(msg) {
const t = $('toast');
t.textContent = msg;
t.style.display = 'block';
clearTimeout(t._h);
t._h = setTimeout(() => { t.style.display = 'none'; }, 3200);
}
function esc(s) {
return String(s ?? '').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/"/g, '&quot;');
}
async function api(path, opt) {
const r = await fetch(path, { credentials: 'same-origin', ...opt, headers: { 'Content-Type': 'application/json', ...(opt && opt.headers || {}) } });
if (r.status === 401) { location.href = '/'; return null; }
return r;
}
/** 仅写表单:首次进入、点「同步表单」、或某块保存后按区块更新 */
function applySettingsToForms(st, sections) {
const all = sections === 'all';
if (all || sections.includes('inspect')) {
$('autoEn').checked = st.auto_inspect_enabled === '1';
$('intervalMin').value = st.inspect_interval_min;
}
if (all || sections.includes('run')) {
$('cfgMaxAutoReg').value = st.max_auto_register_per_tick || '30';
$('cfgThreads').value = st.default_threads;
$('cfgSkipOauth').checked = st.skip_oauth === '1';
$('cfgDefaultProxy').value = st.manual_default_proxy || '';
}
if (all || sections.includes('pipe')) {
$('pipeAuto').checked = st.pipeline_auto_enabled === '1';
$('pipeInterval').value = st.pipeline_interval_min || '10';
$('pipePy').value = st.pipeline_python_bin || 'python3';
$('pipeTimeout').value = st.run_subprocess_timeout_sec || '480';
$('pipeExit0').checked = st.cpa_exit_on_empty === '1';
$('pipeRunScript').value = st.pipeline_run_script || '';
$('pipeOauth').value = st.pipeline_oauth_dir || '';
$('pipeTarget').value = st.cpa_target_dir || '';
$('pipeDing').value = st.dingtalk_webhook || '';
$('pipeDingSec').value = st.dingtalk_secret || '';
}
if (all || sections.includes('clip')) {
$('cfgStatsOauthDir').value = st.codex_stats_oauth_dir || '';
$('cfgClipBase').value = st.cliproxy_management_base || '';
$('cfgClipTimeout').value = st.cliproxy_probe_timeout_sec || '30';
$('cfgSweepThreshold').value = st.cliproxy_sweeper_threshold || '3';
$('cfgSweepMode').value = st.cliproxy_sweeper_run_mode || 'delete';
$('cfgSweepNameFallback').checked = (st.cliproxy_sweeper_allow_name_fallback || '1') === '1';
$('cfgClipKey').value = '';
$('cfgClipKey').placeholder = st.cliproxy_management_key_set ? '已保存密钥(留空不改)' : '必填';
}
}
function renderDataOnly(j) {
const s = j.stats;
$('stTotal').textContent = s.total_accounts;
$('stCand').textContent = s.total_candidates;
const sub = $('stCandSub');
if (s.inspect_probe_mode) {
sub.textContent = '管理端探测 · 本地文件 ' + (s.total_accounts_raw ?? '') + (s.inspect_last_at ? ' · ' + new Date(s.inspect_last_at).toLocaleString() : '');
} else if (s.inspect_probe_pending) {
sub.textContent = '已配置管理端,尚未完成探测 — 请点「立即巡检」';
} else {
sub.textContent = '';
}
$('stTarget').textContent = s.total_target;
$('stHealth').textContent = s.global_health_pct + '%';
$('stHealthLbl').textContent = s.global_status;
const dh = $('oauthStatsDirHint');
if (dh && s.oauth_stats_dir) {
dh.textContent = s.oauth_stats_dir_is_default
? `统计/巡检目录(默认): ${s.oauth_stats_dir}`
: `统计/巡检目录(自定义,应与 Cliproxy auth 一致): ${s.oauth_stats_dir}`;
} else if (dh) {
dh.textContent = '';
}
const tb = $('cpaBody');
tb.innerHTML = '';
const sel = $('manualCpa');
const keep = sel.value;
sel.innerHTML = '';
for (const c of s.cpas) {
const tr = document.createElement('tr');
const tag = c.status === '健康' ? 'ok' : (c.status === '偏低' ? 'warn' : 'bad');
const candCell = (c.raw_candidates != null && c.raw_candidates !== c.candidates)
? `${c.candidates} <span style="color:var(--muted)">/ 文件 ${c.raw_candidates}</span>`
: `${c.candidates}`;
tr.innerHTML = `<td>${esc(c.name)}${c.api_base_url ? `<div style="color:var(--muted);font-size:0.75rem">${esc(c.api_base_url)}</div>` : ''}</td><td>${candCell}</td><td>${c.target_count}</td><td>${c.health_pct}%</td><td>${c.gap}</td><td><span class="tag ${tag}">${c.status}</span></td><td><button class="ghost" data-edit="${c.id}">改目标</button></td>`;
tb.appendChild(tr);
const o = document.createElement('option');
o.value = c.id;
o.textContent = `${c.name} (${c.code})`;
sel.appendChild(o);
}
if (keep && [...sel.options].some(o => o.value === keep)) sel.value = keep;
if (s.cpas.length <= 1) {
$('manualCpaWrap').style.display = 'none';
$('manualCpaSingle').style.display = 'block';
$('manualCpaSingle').textContent = s.cpas.length === 1
? `补号计入:${s.cpas[0].name}`
: '请先在数据库中配置账号池';
} else {
$('manualCpaWrap').style.display = 'block';
$('manualCpaSingle').style.display = 'none';
}
$('btnManual').disabled = !s.cpas.length;
document.querySelectorAll('#cpaBody [data-edit]').forEach(btn => {
btn.onclick = async () => {
const id = +btn.dataset.edit;
const row = lastOverview.stats.cpas.find(x => x.id === id);
const v = prompt('新目标阈值', row.target_count);
if (v == null) return;
const rr = await api(`/api/cpas/${id}`, { method: 'PUT', body: JSON.stringify({ target_count: parseInt(v, 10) }) });
if (rr && rr.ok) { toast('已保存'); await refreshData(); }
};
});
if (j.pipeline) {
const p = j.pipeline;
const pst = p.state || {};
const ts = pst.last_run_at ? new Date(pst.last_run_at * 1000).toLocaleString() : '-';
const rb = p.register_busy ? '补号中' : '';
const pb = p.lock_busy ? '流水线中' : '';
const ib = p.inspect_busy ? '巡检中' : '';
const busy = [rb, pb, ib].filter(Boolean).join(' ') || '空闲';
$('pipeHint').textContent = `上次 ${ts} | 迁出 ${pst.last_run_moved ?? 0} | 码 ${pst.last_run_return_code ?? '-'} | ${busy}`;
$('pipeStatus').textContent = [
`上次运行: ${ts}`,
`迁出 JSON: ${pst.last_run_moved ?? 0}`,
`返回码: ${pst.last_run_return_code ?? '-'}`,
`错误: ${pst.last_error || '-'}`,
`锁: ${p.lock_busy ? '占用' : '空闲'}`,
`定时: ${p.auto_enabled ? '开' : '关'} / 间隔 ${p.interval_min} 分`,
`run.py → ${p.paths.run_script}`,
`OAuth → ${p.paths.oauth_dir}`,
`目标 → ${p.paths.target_dir}`,
`钉钉: ${p.dingtalk_configured ? '已配置' : '未配置'}`,
].join('\n');
}
const ban = $('taskBanner');
const at = j.active_task;
if (at && (at.status === 'running' || at.status === 'queued')) {
ban.classList.remove('idle');
const name = at.cpa_name ? `池: ${at.cpa_name}` : '';
const prog = (at.total > 0) ? ` ${at.done ?? 0}/${at.total}` : '';
ban.textContent = `进行中 #${at.id} ${at.task_type} ${name}${prog} — ${at.message || ''}`;
} else {
ban.classList.add('idle');
ban.textContent = '';
}
const rtb = $('recentTasksBody');
rtb.innerHTML = '';
const list = j.recent_tasks || [];
if (!list.length) {
const tr = document.createElement('tr');
tr.innerHTML = '<td colspan="6" style="color:var(--muted)">暂无任务记录</td>';
rtb.appendChild(tr);
} else {
for (const t of list) {
const tr = document.createElement('tr');
const stCls = t.status === 'error' ? 'st-err' : (t.status === 'running' || t.status === 'queued' ? 'st-run' : 'st-done');
const ts = t.updated_at ? new Date(t.updated_at).toLocaleString() : '—';
const prog = (t.total > 0) ? `${t.done ?? 0} / ${t.total}` : '—';
tr.innerHTML = `<td>${t.id}</td><td>${esc(t.task_type)}</td><td class="${stCls}">${esc(t.status)}</td><td>${prog}</td><td class="task-msg" title="${esc(t.message)}">${esc(t.message)}</td><td style="color:var(--muted);white-space:nowrap">${ts}</td>`;
rtb.appendChild(tr);
}
}
}
async function refreshData() {
const r = await api('/api/overview');
if (!r || !r.ok) return;
lastOverview = await r.json();
renderDataOnly(lastOverview);
}
document.querySelectorAll('.tabs button').forEach(b => {
b.onclick = () => {
document.querySelectorAll('.tabs button').forEach(x => x.classList.remove('active'));
b.classList.add('active');
document.querySelectorAll('.section').forEach(s => s.classList.remove('visible'));
$('section-' + b.dataset.tab).classList.add('visible');
};
});
$('btnRefreshData').onclick = () => refreshData();
$('btnSyncForms').onclick = async () => {
await refreshData();
if (lastOverview && lastOverview.settings) {
applySettingsToForms(lastOverview.settings, 'all');
toast('表单已与服务器同步');
}
};
$('btnLogout').onclick = async () => { await api('/api/logout', { method: 'POST', body: '{}' }); location.href = '/'; };
$('saveInspect').onclick = async () => {
await api('/api/settings', { method: 'POST', body: JSON.stringify({
auto_inspect_enabled: $('autoEn').checked ? '1' : '0',
inspect_interval_min: $('intervalMin').value,
}) });
toast('巡检设置已保存');
await refreshData();
if (lastOverview) applySettingsToForms(lastOverview.settings, ['inspect']);
};
$('saveConfig').onclick = async () => {
await api('/api/settings', { method: 'POST', body: JSON.stringify({
max_auto_register_per_tick: $('cfgMaxAutoReg').value,
default_threads: $('cfgThreads').value,
skip_oauth: $('cfgSkipOauth').checked ? '1' : '0',
manual_default_proxy: $('cfgDefaultProxy').value.trim(),
}) });
toast('配置已保存');
await refreshData();
if (lastOverview) applySettingsToForms(lastOverview.settings, ['run']);
};
$('saveCliproxy').onclick = async () => {
const body = {
codex_stats_oauth_dir: $('cfgStatsOauthDir').value.trim(),
cliproxy_management_base: $('cfgClipBase').value.trim(),
cliproxy_probe_timeout_sec: $('cfgClipTimeout').value,
cliproxy_sweeper_threshold: $('cfgSweepThreshold').value,
cliproxy_sweeper_run_mode: $('cfgSweepMode').value,
cliproxy_sweeper_allow_name_fallback: $('cfgSweepNameFallback').checked ? '1' : '0',
};
const k = $('cfgClipKey').value;
if (k) body.cliproxy_management_key = k;
await api('/api/settings', { method: 'POST', body: JSON.stringify(body) });
toast('Cliproxy 设置已保存');
await refreshData();
if (lastOverview) applySettingsToForms(lastOverview.settings, ['clip']);
};
$('btnInspectNow').onclick = async () => {
const r = await api('/api/tasks/inspect-now', { method: 'POST', body: '{}' });
if (!r) return;
const j = await r.json();
if (r.status === 400) { toast(j.error || '配置不全'); return; }
if (r.status === 409) { toast(j.error || '忙'); return; }
toast(j.message || '已排队');
refreshData();
};
$('btnSweepFailedNow').onclick = async () => {
const r = await api('/api/tasks/sweep-failed-now', { method: 'POST', body: '{}' });
if (!r) return;
const j = await r.json().catch(() => ({}));
if (r.status === 400) { toast(j.error || '配置不全'); return; }
if (r.status === 409) { toast(j.error || '忙'); return; }
if (!r.ok) { toast(j.error || '失败'); return; }
toast(j.message || '清理任务已排队');
refreshData();
};
$('btnManual').onclick = async () => {
const r = await api('/api/tasks/manual', { method: 'POST', body: JSON.stringify({
cpa_id: parseInt($('manualCpa').value, 10),
count: parseInt($('manualCount').value, 10),
use_proxy_pool: $('manualS5').checked,
}) });
if (!r) return;
const j = await r.json().catch(() => ({}));
if (r.status === 409) { toast(j.error || '忙'); return; }
if (!r.ok) { toast(j.error || '失败'); return; }
toast('任务已启动');
refreshData();
};
$('savePipe').onclick = async () => {
await api('/api/settings', { method: 'POST', body: JSON.stringify({
pipeline_auto_enabled: $('pipeAuto').checked ? '1' : '0',
pipeline_interval_min: $('pipeInterval').value,
pipeline_python_bin: $('pipePy').value.trim(),
run_subprocess_timeout_sec: $('pipeTimeout').value,
cpa_exit_on_empty: $('pipeExit0').checked ? '1' : '0',
pipeline_run_script: $('pipeRunScript').value.trim(),
pipeline_oauth_dir: $('pipeOauth').value.trim(),
cpa_target_dir: $('pipeTarget').value.trim(),
dingtalk_webhook: $('pipeDing').value.trim(),
dingtalk_secret: $('pipeDingSec').value.trim(),
}) });
toast('流水线设置已保存');
await refreshData();
if (lastOverview) applySettingsToForms(lastOverview.settings, ['pipe']);
};
$('btnPipeOnce').onclick = async () => {
const r = await api('/api/pipeline/run-once', { method: 'POST', body: '{}' });
if (!r) return;
const j = await r.json().catch(() => ({}));
if (r.status === 409) { toast(j.error || '忙'); return; }
if (!r.ok) { toast(j.error || '失败'); return; }
toast('流水线任务已启动');
refreshData();
};
async function loadProxies() {
const r = await api('/api/proxies');
if (!r || !r.ok) return;
const j = await r.json();
const el = $('proxyList');
el.innerHTML = '';
for (const p of j.proxies) {
const div = document.createElement('div');
div.className = 'proxy-item';
div.innerHTML = `<span>${esc(p.url)} <span style="color:var(--muted)">${esc(p.label)}</span></span><button class="ghost" data-del="${p.id}">删除</button>`;
el.appendChild(div);
}
el.querySelectorAll('[data-del]').forEach(b => {
b.onclick = async () => {
await fetch('/api/proxies/' + b.dataset.del, { method: 'DELETE', credentials: 'same-origin' });
loadProxies();
};
});
}
$('btnAddProxy').onclick = async () => {
const url = $('newProxyUrl').value.trim();
if (!url) return;
await api('/api/proxies', { method: 'POST', body: JSON.stringify({ url, label: $('newProxyLabel').value.trim() }) });
$('newProxyUrl').value = '';
$('newProxyLabel').value = '';
toast('已添加');
loadProxies();
};
document.querySelector('[data-tab="proxy"]').addEventListener('click', loadProxies);
let logAutoTimer = null;
async function loadLogTail() {
const name = $('logSource').value;
const lines = $('logLines').value || '400';
const r = await api(
`/api/logs/tail?name=${encodeURIComponent(name)}&lines=${encodeURIComponent(lines)}`
);
if (!r || !r.ok) {
$('logPre').textContent = r ? ('加载失败 HTTP ' + r.status) : '未登录或网络错误';
return;
}
const j = await r.json();
if (j.error) {
$('logPre').textContent = j.error;
$('logPath').textContent = '';
return;
}
$('logPath').textContent = j.path || '';
$('logPre').textContent = j.content || '';
}
$('btnLogReload').onclick = () => loadLogTail();
function syncLogAutoTimer() {
clearInterval(logAutoTimer);
logAutoTimer = null;
if ($('logAuto').checked) {
logAutoTimer = setInterval(() => {
if ($('section-logs').classList.contains('visible')) loadLogTail();
}, 15000);
}
}
$('logAuto').onchange = syncLogAutoTimer;
document.querySelector('[data-tab="logs"]').addEventListener('click', () => {
loadLogTail();
syncLogAutoTimer();
});
(async () => {
await refreshData();
if (lastOverview && lastOverview.settings) {
applySettingsToForms(lastOverview.settings, 'all');
}
})();
setInterval(refreshData, 8000);
</script>
</body>
</html>