const root = document.querySelector('[data-cloud-agent-settings]'); const byId = id => document.getElementById(id); const canManage = root?.dataset.canManage === '1'; const state = { csrf: window.ADMIN_CSRF_TOKEN || '', agents: [], regions: [], summary: {}, selected: null, busy: false, expandedRegions: new Set(), regionsInitialized: false, drawerOpener: null, drawerScroll: null, secretDraft: '', secretDraftHostId: null, secretVisible: false, rotationConfirmed: false, }; const requestRuntime = window.VenixAdminRequestRuntime.create({ csrfToken: () => state.csrf }); function notice(message, error = false) { const box = byId('agent-settings-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; } async function api(path, options = {}) { const method = String(options.method || 'GET').toUpperCase(); if (['GET', 'HEAD'].includes(method)) return requestRuntime.read(path, { method }); return requestRuntime.mutate(path, { method, body: options.body, response: 'json' }); } function text(tag, className, value) { const node = document.createElement(tag); node.className = className; node.textContent = value; return node; } function selectedAgent() { return state.agents.find(agent => String(agent.host_id) === String(state.selected)) || null; } function refreshSummaryFromAgents() { const summary = { regions_total: Number(state.summary?.regions_total || 0), agents_total: 0, ready_agents: 0, pending_agents: 0, failed_agents: 0, unconfigured_agents: 0, disabled_agents: 0, attention_agents: 0, }; for (const agent of state.agents) { summary.agents_total++; const key = `${agent.status || 'unconfigured'}_agents`; if (Object.prototype.hasOwnProperty.call(summary, key)) summary[key]++; if (agent.needs_attention) summary.attention_agents++; } state.summary = summary; } function replaceAgent(agent) { const current = state.agents.find(item => String(item.host_id) === String(agent.host_id)) || {}; const merged = { ...current, ...agent, placement: agent.placement || current.placement || {}, location: agent.location || current.location || {}, }; const replace = items => { const index = items.findIndex(item => String(item.host_id) === String(merged.host_id)); if (index >= 0) items[index] = merged; }; replace(state.agents); for (const region of state.regions) { if (Array.isArray(region.agents)) replace(region.agents); } refreshSummaryFromAgents(); return merged; } function statusLabel(value) { return ({ ready: '已就绪', pending: '等待测试', failed: '测试失败', unconfigured: '未配置', disabled: '已停用' })[value] || '状态异常'; } function statusTone(value) { return value === 'ready' ? 'success' : ['pending', 'failed', 'unconfigured'].includes(value) ? 'warning' : 'muted'; } function badge(label, tone) { return text('span', `cloud-admin-host-badge is-${tone}`, label); } function regionKey(region) { return region?.id === null || region?.id === undefined ? 'unclassified' : `region:${region.id}`; } function renderSummary() { const summary = byId('agent-settings-summary'); const data = state.summary || {}; const items = [ ['server-network', 'Agent 节点', data.agents_total || 0], ['check-decagram-outline', '已就绪', data.ready_agents || 0], ['timer-sand', '等待测试', data.pending_agents || 0], ['alert-circle-outline', '测试失败', data.failed_agents || 0], ['key-alert-outline', '未配置', data.unconfigured_agents || 0], ]; summary.replaceChildren(...items.map(([icon, label, value]) => { const card = text('article', 'cloud-admin-host-summary-card', ''); const copy = text('div', '', ''); copy.append(text('span', '', label), text('strong', '', value)); const mark = text('span', 'cloud-admin-host-summary-icon', ''); mark.innerHTML = ``; card.append(mark, copy); return card; })); } function syncRegionFilter() { const select = byId('agent-settings-region-filter'); const selected = select.value; select.replaceChildren(new Option('全部地区', '')); for (const region of state.regions) { const value = region.id === null || region.id === undefined ? 'unclassified' : String(region.id); select.append(new Option(`${region.country_flag || '🌐'} ${region.name || '未分类节点'}(${region.agents?.length || 0})`, value)); } select.value = Array.from(select.options).some(option => option.value === selected) ? selected : ''; } function matchesFilter(agent, search, regionValue, statusValue) { const placement = agent?.placement || {}; const regionId = placement.region_id === null || placement.region_id === undefined ? 'unclassified' : String(placement.region_id); if (regionValue && regionId !== regionValue) return false; if (statusValue && agent.status !== statusValue) return false; if (!search) return true; return [agent.host_name, agent.agent_id, agent.region, placement.region_name, placement.line_name, placement.pool_name, agent.last_agent_version] .some(value => String(value || '').toLocaleLowerCase().includes(search)); } function lastTestText(agent) { const timestamp = Number(agent.last_tested_at || 0); if (!timestamp) return '尚未测试'; return new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hour12: false, }).format(new Date(timestamp * 1000)); } function renderAgent(agent) { const button = text('button', 'cloud-admin-host cloud-admin-agent-row', ''); button.type = 'button'; button.dataset.hostId = String(agent.host_id); button.setAttribute('aria-controls', 'agent-settings-drawer'); button.setAttribute('aria-haspopup', 'dialog'); button.setAttribute('aria-expanded', 'false'); button.setAttribute('aria-label', `配置 Agent ${agent.host_name || agent.agent_id}`); if (String(agent.host_id) === String(state.selected)) button.setAttribute('aria-current', 'true'); const heading = text('span', 'cloud-admin-host-heading', ''); heading.append(text('strong', '', agent.host_name || `计算节点 #${agent.host_id}`), text('small', '', `Agent ID ${agent.agent_id || agent.host_id} · ${agent?.location?.physical_label || agent.region || '物理位置未设置'}`)); const statuses = text('span', 'cloud-admin-host-statuses', ''); statuses.append(badge(statusLabel(agent.status), statusTone(agent.status)), badge(agent.secret_configured ? '密钥已配置' : '缺少密钥', agent.secret_configured ? 'success' : 'warning')); const path = text('span', 'cloud-admin-host-path', [agent?.placement?.region_name, agent?.placement?.line_name, agent?.placement?.pool_name].filter(Boolean).join(' · ') || '尚未加入资源池'); const metrics = text('span', 'cloud-admin-host-metrics', ''); metrics.append(text('span', '', `版本 ${agent.last_agent_version || '--'}`), text('span', '', `最近测试 ${lastTestText(agent)}`)); button.append(heading, statuses, path, metrics); button.addEventListener('click', () => { state.selected = String(agent.host_id); fill(agent); renderList(); const opener = byId('agent-settings-list').querySelector(`[data-host-id="${agent.host_id}"]`); openDrawer(opener); }); return button; } function renderList() { renderSummary(); syncRegionFilter(); const list = byId('agent-settings-list'); list.replaceChildren(); if (!state.agents.length) { list.append(text('p', 'cloud-admin-host-empty', '请先添加计算节点。')); return; } const search = String(byId('agent-settings-search').value || '').trim().toLocaleLowerCase(); const regionValue = String(byId('agent-settings-region-filter').value || ''); const statusValue = String(byId('agent-settings-state-filter').value || ''); let visible = 0; for (const region of state.regions) { const agents = (Array.isArray(region.agents) ? region.agents : []).filter(agent => matchesFilter(agent, search, regionValue, statusValue)); if (!agents.length) continue; visible += agents.length; const key = regionKey(region); const group = text('details', 'cloud-admin-host-region cloud-admin-agent-region', ''); group.open = search !== '' || regionValue !== '' || statusValue !== '' || state.expandedRegions.has(key); group.addEventListener('toggle', () => group.open ? state.expandedRegions.add(key) : state.expandedRegions.delete(key)); const header = text('summary', 'cloud-admin-host-region-head', ''); const identity = text('span', 'cloud-admin-host-region-identity', ''); identity.append(text('span', 'cloud-admin-host-region-flag', region.country_flag || '🌐'), text('span', '', region.name || '未分类节点')); const meta = text('span', 'cloud-admin-host-region-meta', ''); meta.append(text('span', '', `${agents.length} 台节点`), text('span', '', `${agents.filter(agent => agent.status === 'ready').length} 台就绪`)); const attention = agents.filter(agent => agent.needs_attention).length; if (attention) meta.append(badge(`${attention} 项需处理`, 'warning')); header.append(identity, meta); const nodes = text('div', 'cloud-admin-host-region-nodes', ''); nodes.append(...agents.map(renderAgent)); group.append(header, nodes); list.append(group); } if (!visible) list.append(text('p', 'cloud-admin-host-empty', '没有符合当前筛选条件的 Agent。')); if (byId('agent-settings-drawer')?.open) { state.drawerOpener = list.querySelector(`[data-host-id="${state.selected}"]`); state.drawerOpener?.setAttribute('aria-expanded', 'true'); } } function renderHealth(agent) { const health = byId('agent-settings-health'); health.replaceChildren(); const rows = [ ['配置版本', String(agent.revision || 0)], ['就绪状态', agent.ready === true ? '已通过当前版本测试' : '未就绪,不参与调度'], ['密钥状态', agent.secret_configured ? '已安全保存' : '未配置'], ['最近测试', agent.last_test_status === 'healthy' ? '正常' : agent.last_test_status === 'unhealthy' ? '失败' : '尚未测试'], ['Agent 版本', agent.last_agent_version || '--'], ['错误代码', agent.last_error_code || '--'], ]; for (const [label, value] of rows) { health.append(text('dt', '', label), text('dd', '', value)); } } function renderChecklist(agent) { const checklist = byId('agent-settings-checklist'); checklist.replaceChildren(); const steps = [ ['保存连接身份', agent.secret_configured === true], ['更新宿主机配置并重启 Agent', agent.ready === true], ['完成宿主机存储注册', agent.storage_configured === true], ['通过健康与必要能力测试', agent.ready === true], ]; const firstIncomplete = steps.findIndex(([, done]) => !done); for (const [index, [label, done]] of steps.entries()) { const item = text('li', 'cloud-agent-checklist-step', ''); if (done) item.classList.add('is-done'); else if (index === firstIncomplete) item.classList.add('is-current'); const mark = text('span', 'cloud-agent-checklist-mark', done ? '✓' : String(index + 1)); item.append(mark, text('span', '', label)); checklist.append(item); } } function generateAgentSecret() { if (!window.crypto?.getRandomValues) throw new Error('当前浏览器不支持安全随机数,请更换现代浏览器。'); const bytes = new Uint8Array(32); window.crypto.getRandomValues(bytes); return btoa(String.fromCharCode(...bytes)).replaceAll('+', '-').replaceAll('/', '_').replace(/=+$/u, ''); } function configFragment(agent, secret, redact = false) { return JSON.stringify({ panel_url: location.origin, agent_id: String(agent?.agent_id || agent?.host_id || ''), agent_secret: redact ? '••••••••••••••••••••••••••••••••' : secret, }, null, 2); } function clearSecretDraft(update = true) { state.secretDraft = ''; state.secretDraftHostId = null; state.secretVisible = false; state.rotationConfirmed = false; if (update) renderSecretDraft(selectedAgent()); } function renderSecretDraft(agent) { const secret = String(state.secretDraftHostId) === String(agent?.host_id) ? state.secretDraft : ''; const input = byId('agent-settings-secret'); input.value = secret; input.type = state.secretVisible ? 'text' : 'password'; const hasDraft = secret !== ''; const reveal = byId('agent-settings-reveal'); reveal.disabled = !canManage || !hasDraft; reveal.setAttribute('aria-pressed', state.secretVisible ? 'true' : 'false'); reveal.querySelector('span').textContent = state.secretVisible ? '隐藏' : '显示'; reveal.querySelector('i').className = `mdi ${state.secretVisible ? 'mdi-eye-off-outline' : 'mdi-eye-outline'} me-1`; byId('agent-settings-copy-secret').disabled = !canManage || !hasDraft; byId('agent-settings-clear-secret').disabled = !canManage || !hasDraft; byId('agent-settings-copy-config').disabled = !canManage || !hasDraft; const rotating = hasDraft && agent?.secret_configured === true; const confirmation = byId('agent-settings-rotation-confirm-box'); confirmation.hidden = !rotating; byId('agent-settings-rotation-confirm').checked = rotating && state.rotationConfirmed; byId('agent-settings-save').disabled = !canManage || !agent || state.busy || (rotating && !state.rotationConfirmed); const box = byId('agent-settings-config-box'); box.hidden = !hasDraft; byId('agent-settings-config-preview').textContent = hasDraft ? configFragment(agent, secret, !state.secretVisible) : ''; const generateLabel = byId('agent-settings-generate').querySelector('span'); generateLabel.textContent = agent?.secret_configured ? '生成新密钥(轮换)' : '生成安全密钥'; byId('agent-settings-secret-help').textContent = hasDraft && agent?.secret_configured ? '这是尚未保存的新密钥。保存后旧密钥立即失效,请同步更新该宿主机并重新测试。' : agent?.secret_configured ? '已配置密钥;留空保存不会覆盖。密钥永不回显。' : '尚未配置密钥;可安全生成或手动填写 32 至 256 位无空格字符。'; } async function copyDraft(value, label) { if (!value) return; if (!navigator.clipboard?.writeText) throw new Error('当前浏览器不支持安全剪贴板,请手动复制。'); await navigator.clipboard.writeText(value); notice(`${label}已复制。请写入目标宿主机后及时清理剪贴板。`); } function lockDrawerScroll() { state.drawerScroll = { x: window.scrollX, y: window.scrollY }; document.body.style.setProperty('--admin-instance-scroll-top', `${-state.drawerScroll.y}px`); document.documentElement.classList.add('admin-instance-detail-open'); } function finishDrawerClose() { document.documentElement.classList.remove('admin-instance-detail-open'); document.body.style.removeProperty('--admin-instance-scroll-top'); if (state.drawerScroll) window.scrollTo({ left: state.drawerScroll.x, top: state.drawerScroll.y, behavior: 'instant' }); state.drawerScroll = null; if (state.drawerOpener?.isConnected) state.drawerOpener.focus({ preventScroll: true }); state.drawerOpener = null; } function openDrawer(opener) { const drawer = byId('agent-settings-drawer'); state.drawerOpener = opener || null; if (drawer.open) return; lockDrawerScroll(); window.VenixDrawerMotion.openDrawerWithMotion(drawer); opener?.setAttribute('aria-expanded', 'true'); } function closeDrawer() { const drawer = byId('agent-settings-drawer'); if (!drawer?.open) return; state.drawerOpener?.setAttribute('aria-expanded', 'false'); clearSecretDraft(); void window.VenixDrawerMotion.closeDrawerWithMotion(drawer).then(closed => { if (closed) finishDrawerClose(); }); } function fill(agent, { preserveDraft = false } = {}) { if (!preserveDraft || String(state.secretDraftHostId) !== String(agent?.host_id)) clearSecretDraft(false); byId('agent-settings-host-id').value = agent?.host_id || ''; byId('agent-settings-revision').value = String(agent?.revision || 0); byId('agent-settings-title').textContent = agent ? `Agent 上行连接 · ${agent.host_name}` : '选择计算节点'; byId('agent-settings-panel-url').value = location.origin; byId('agent-settings-agent-id').value = agent?.agent_id || agent?.host_id || ''; byId('agent-settings-secret').placeholder = agent?.secret_configured ? '已配置,留空保留现有密钥' : '首次配置必须填写至少 32 位密钥'; byId('agent-settings-enabled').checked = agent?.enabled === true; byId('agent-settings-generate').disabled = !canManage || !agent || state.busy; byId('agent-settings-save').disabled = !canManage || !agent || state.busy; byId('agent-settings-test').disabled = !canManage || !agent?.enabled || !agent?.secret_configured || state.busy; renderHealth(agent || {}); renderChecklist(agent || {}); renderSecretDraft(agent || {}); } async function load() { notice('正在读取 Agent API 配置…'); const session = await api('/api/v1/session'); if (!session.admin) throw new Error('需要管理员权限。'); state.csrf = session.csrf_token || state.csrf; if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。'); const payload = await api('/api/v1/admin/agents'); state.agents = Array.isArray(payload.agents) ? payload.agents : []; state.regions = Array.isArray(payload.regions) ? payload.regions : []; state.summary = payload?.summary && typeof payload.summary === 'object' ? payload.summary : {}; if (!state.regionsInitialized) { const first = state.regions[0]; if (first) state.expandedRegions.add(regionKey(first)); for (const region of state.regions) if (Number(region?.summary?.attention_agents || 0) > 0) state.expandedRegions.add(regionKey(region)); state.regionsInitialized = true; } if (!selectedAgent() && state.agents.length) state.selected = String(state.agents[0].host_id); renderList(); fill(selectedAgent()); notice(canManage ? '请选择计算节点配置 Agent API。' : '当前管理员仅可查看 Agent API 配置与状态。'); } async function save(event) { event.preventDefault(); if (!canManage || state.busy) return; const hostId = byId('agent-settings-host-id').value; if (!hostId) return; const body = { enabled: byId('agent-settings-enabled').checked, api_secret: byId('agent-settings-secret').value, expected_revision: Number(byId('agent-settings-revision').value), }; if (!Number.isSafeInteger(body.expected_revision) || body.expected_revision < 0) return notice('配置版本无效,请刷新页面。', true); if (body.api_secret && (body.api_secret.length < 32 || body.api_secret.length > 256 || /\s/.test(body.api_secret))) return notice('API 密钥需为 32 至 256 位无空格字符。', true); if (body.api_secret && selectedAgent()?.secret_configured && !state.rotationConfirmed) return notice('请先确认密钥轮换会立即使旧密钥失效。', true); state.busy = true; fill(selectedAgent(), { preserveDraft: true }); notice('正在保存 Agent API 配置…'); let savedSuccessfully = false; try { const saved = await api(`/api/v1/admin/agents/${encodeURIComponent(hostId)}`, { method: 'PUT', body }); const current = replaceAgent(saved); savedSuccessfully = true; clearSecretDraft(false); renderList(); fill(current); notice(saved.enabled ? 'Agent API 配置已加密保存;请测试当前版本,通过前不参与调度。' : 'Agent API 配置已加密保存,当前为停用状态。'); } catch (error) { notice(error.message, true); } finally { state.busy = false; fill(selectedAgent(), { preserveDraft: !savedSuccessfully }); } } async function testConnection() { if (!canManage || state.busy) return; const agent = selectedAgent(); if (!agent) return; state.busy = true; fill(agent, { preserveDraft: true }); notice('正在通过上行 WSS 验证 Agent 连接…'); try { const tested = await api(`/api/v1/admin/agents/${encodeURIComponent(agent.host_id)}/test`, { method: 'POST', body: { expected_revision: agent.revision } }); const current = replaceAgent(tested); renderList(); fill(current, { preserveDraft: true }); const capabilityCount = Number(tested.capabilities?.required_feature_count || 0); const firmware = tested.capabilities?.uefi === true && tested.capabilities?.secure_boot === false ? ',UEFI 已启用且安全启动已关闭' : ''; notice(`Agent 连接正常,当前配置版本已就绪${tested.health?.version ? `,Agent 版本 ${tested.health.version}` : ''}${capabilityCount > 0 ? `,${capabilityCount} 项必要能力已验证` : ''}${firmware}。`); } catch (error) { try { const refreshed = await api(`/api/v1/admin/agents/${encodeURIComponent(agent.host_id)}`); const current = replaceAgent(refreshed); renderList(); fill(current, { preserveDraft: true }); } catch {} notice(error.message, true); } finally { state.busy = false; fill(selectedAgent(), { preserveDraft: true }); } } if (root) { byId('agent-settings-form').addEventListener('submit', save); byId('agent-settings-test').addEventListener('click', testConnection); byId('agent-settings-secret').addEventListener('input', event => { state.secretDraft = event.currentTarget.value; state.secretDraftHostId = state.selected; state.rotationConfirmed = false; renderSecretDraft(selectedAgent()); }); byId('agent-settings-generate').addEventListener('click', () => { try { state.secretDraft = generateAgentSecret(); state.secretDraftHostId = state.selected; state.secretVisible = true; state.rotationConfirmed = false; renderSecretDraft(selectedAgent()); notice('已在本页生成一次性安全密钥;请复制到宿主机并保存面板配置。'); } catch (error) { notice(error.message, true); } }); byId('agent-settings-reveal').addEventListener('click', () => { state.secretVisible = !state.secretVisible; renderSecretDraft(selectedAgent()); }); byId('agent-settings-rotation-confirm').addEventListener('change', event => { state.rotationConfirmed = event.currentTarget.checked; renderSecretDraft(selectedAgent()); }); byId('agent-settings-clear-secret').addEventListener('click', () => clearSecretDraft()); byId('agent-settings-copy-secret').addEventListener('click', () => { void copyDraft(state.secretDraft, '密钥').catch(error => notice(error.message, true)); }); byId('agent-settings-copy-config').addEventListener('click', () => { void copyDraft(configFragment(selectedAgent(), state.secretDraft), '配置片段').catch(error => notice(error.message, true)); }); byId('agent-settings-close').addEventListener('click', closeDrawer); byId('agent-settings-drawer').addEventListener('cancel', event => { event.preventDefault(); closeDrawer(); }); byId('agent-settings-drawer').addEventListener('click', event => { if (event.target === event.currentTarget) closeDrawer(); }); byId('agent-settings-search').addEventListener('input', renderList); byId('agent-settings-region-filter').addEventListener('change', renderList); byId('agent-settings-state-filter').addEventListener('change', renderList); window.addEventListener('pagehide', () => clearSecretDraft(false)); void load().catch(error => notice(error.message, true)); }