You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-operations.js

696 lines
37 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

import {
announceTaskAccepted, observeTask, recoveryTaskFailureNotice, taskUrl,
taskSucceededWithoutRecovery,
} from './task-observer.js?v=2026102102';
const root = document.querySelector('[data-admin-operations]');
const byId = id => document.getElementById(id);
const filterNames = ['q', 'status', 'kind', 'host_id', 'per_page'];
const columns = ['任务', '关联实例', '用户', '宿主机', '状态', '执行信息', '更新与异常', '操作'];
const terminalStates = new Set(['succeeded', 'failed']);
const state = {
page: null, loadedUrl: null, request: null, serial: 0, loading: false,
healthRequest: null, health: null,
detailRequest: null, detailId: null, detailJob: null, detailClosing: false,
opener: null, scroll: null, actionRequest: null, forceDeleteAccepted: false,
forceDeleteBlocked: false, forceDeleteAcceptedIds: new Set(), forceDeleteBlockedIds: new Set(),
forceDeleteObservers: new Map(),
inspection: null, effectResolved: false,
};
function el(tag, className = '', content) {
const node = document.createElement(tag);
node.className = className;
if (content !== undefined) node.textContent = String(content);
return node;
}
function text(value, fallback = '未记录') {
return value === null || value === undefined || String(value).trim() === '' ? fallback : String(value);
}
function date(value) {
if (!value) return '时间未记录';
const numeric = Number(value);
const parsed = Number.isFinite(numeric)
? new Date(numeric * (numeric < 1e12 ? 1000 : 1)) : new Date(String(value));
if (!Number.isFinite(parsed.getTime())) return '时间未记录';
return parsed.toLocaleString('zh-CN', { hour12: false });
}
function stack(primary, ...secondary) {
const node = el('span', 'admin-checkout-user');
node.append(primary instanceof Node ? primary : el('strong', '', primary));
for (const value of secondary.filter(Boolean)) node.append(value instanceof Node ? value : el('span', '', value));
return node;
}
function taskView(task) {
if (!task || typeof task !== 'object' || Array.isArray(task) || !String(task.id || '').trim()) {
return { terminal: true, status: 'failed', label: '协议错误', tone: 'text-danger', protocolError: true };
}
if (task.completed === false && task.status === 'active') {
return { terminal: false, status: 'running', label: '执行中', tone: 'text-primary', protocolError: false };
}
if (task.completed === true && typeof task.status === 'string' && terminalStates.has(task.status)) {
if (task.recovery?.pending === true) {
const code = String(task.recovery?.code || task.finalization_error_code || '');
const label = code === 'recovery_dispatch_ledger_conflict'
|| task.dispatch_state === 'invalid' ? '派发账本异常 · 待修复'
: task.dispatch_state === 'not_dispatched' ? 'PHP 本地账本收尾中'
: task.status === 'failed' ? '已失败 · 持续恢复中' : '安全恢复中';
return {
terminal: true,
status: task.status,
label,
tone: 'text-warning',
protocolError: false,
};
}
return {
terminal: true,
status: task.status,
label: { succeeded: '已成功', failed: '已失败' }[task.status],
tone: { succeeded: 'text-success', failed: 'text-danger' }[task.status],
protocolError: false,
};
}
return { terminal: true, status: 'failed', label: '协议错误', tone: 'text-danger', protocolError: true };
}
function notice(message, error = false) {
const node = byId('operations-notice');
node.textContent = message;
node.className = `admin-config-status ${error ? 'is-error' : 'is-success'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
function historyData(changes = {}) {
return { ...(history.state && typeof history.state === 'object' ? history.state : {}), ...changes };
}
async function api(path, controller, timeoutMs = 15000, options = {}) {
const timer = setTimeout(() => controller.abort('timeout'), timeoutMs);
try {
const method = String(options.method || 'GET').toUpperCase();
const headers = { Accept: 'application/json', ...(options.headers || {}) };
const request = { method, headers, credentials: 'same-origin', cache: 'no-store', signal: controller.signal };
if (!['GET', 'HEAD'].includes(method)) {
if (!window.ADMIN_CSRF_TOKEN) throw new Error('页面安全令牌缺失,请刷新页面。');
headers['X-CSRF-Token'] = window.ADMIN_CSRF_TOKEN;
headers['Content-Type'] = 'application/json';
request.body = options.body === undefined ? '{}' : options.body;
}
const response = await fetch(path, request);
if (response.status === 401) throw new Error('登录已过期,请重新登录。');
let payload;
try { payload = await response.json(); }
catch { throw new Error('服务器返回了无效数据。'); }
if (!response.ok || payload?.ret === 0) {
throw new Error(typeof payload?.detail === 'string' ? payload.detail
: (payload?.message || payload?.error || `请求失败 (${response.status})`));
}
if (options.expectedStatus !== undefined && response.status !== options.expectedStatus) {
throw new Error(`服务未返回预期的 HTTP ${options.expectedStatus} 任务回执;为避免重复执行,请勿再次提交并联系管理员。`);
}
return payload;
} catch (error) {
if (controller.signal.reason === 'timeout') throw new Error('请求超时,请稍后刷新。');
throw error;
} finally { clearTimeout(timer); }
}
async function acceptedTask(path, controller, timeoutMs, options = {}) {
const payload = await api(path, controller, timeoutMs, { ...options, expectedStatus: 202 });
if (!taskUrl(payload)) throw new Error('服务未返回严格的任务回执;为避免重复执行,请勿再次提交并联系管理员。');
return payload;
}
function listUrl(input = new URL(location.href)) {
const url = new URL('/admin/operations', location.origin);
for (const key of [...filterNames, 'page']) {
const value = input.searchParams.get(key);
if (value && !(key === 'status' && value === 'all') && !(key === 'page' && value === '1')) url.searchParams.set(key, value);
}
return url;
}
function formUrl() {
const url = new URL('/admin/operations', location.origin);
for (const key of filterNames) {
const value = byId('operations-filter').elements.namedItem(key).value.trim();
if (value && !(key === 'status' && value === 'all')) url.searchParams.set(key, value);
}
return url;
}
function readForm(url) {
const form = byId('operations-filter');
for (const key of filterNames) {
const control = form.elements.namedItem(key);
const value = url.searchParams.get(key) || ({ status: 'all', per_page: '20' })[key] || '';
if (control instanceof HTMLSelectElement && value
&& !Array.from(control.options).some(option => option.value === value)) {
control.add(new Option(value, value));
}
control.value = value;
}
}
function syncOptions(page) {
const kind = byId('operations-kind');
kind.replaceChildren(new Option('全部类型', ''));
for (const item of page.kinds || []) kind.add(new Option(item.label, item.value));
const host = byId('operations-host');
host.replaceChildren(new Option('全部宿主机', ''));
for (const item of page.hosts || []) host.add(new Option(`${item.name}${item.region ? ` · ${item.region}` : ''}`, item.id));
}
function payloadUrl(page) {
const url = new URL('/admin/operations', location.origin);
for (const key of [...filterNames, 'page']) {
const value = key === 'page' || key === 'per_page' ? page.pagination[key] : page.filters?.[key];
if (value !== null && value !== undefined && value !== '') url.searchParams.set(key, String(value));
}
return listUrl(url);
}
function shownFilters() {
if (!state.page) return '尚未读取任务数据。';
const filters = state.page.filters || {};
const labels = [({ all: '全部状态', active: '执行中', failed: '已失败', succeeded: '已成功' })[filters.status] || filters.status];
if (filters.kind) labels.push((state.page.kinds || []).find(item => item.value === filters.kind)?.label || filters.kind);
if (filters.host_id) labels.push((state.page.hosts || []).find(item => String(item.id) === String(filters.host_id))?.name || `宿主机 #${filters.host_id}`);
if (filters.q) labels.push(`关键词「${filters.q}」`);
return `已显示:${labels.filter(Boolean).join(' · ')} · 第 ${state.page.pagination.page} 页。`;
}
function failureText(job, view) {
if (view.protocolError) return '任务数据不符合公开协议;资源按可能已生效处理并保持锁定。';
if (job.recovery?.pending === true) {
const code = String(job.recovery?.code || job.finalization_error_code || '');
const message = text(job.recovery.message, '系统仍会继续恢复。');
if (code === 'recovery_dispatch_ledger_conflict' || job.dispatch_state === 'invalid') {
return `派发账本异常,任务原终态保持不变,资源继续安全锁定;修复账本后系统会重新核验。${message}`;
}
if (job.dispatch_state === 'not_dispatched') {
return `宿主机操作已确认未派发,但 PHP 本地账本收尾尚未完成;资源保持安全锁定,系统会持续重试本地收尾。${message}`;
}
return `任务尚在持续恢复,资源保持安全锁定;系统不会重复执行原操作。${message}`;
}
if (view.status !== 'failed') return '';
if (job.kind === 'host_storage_configure') {
return '旧存储任务已终止且不会重放;部分固定存储池可能已应用。可到宿主机存储目录页修正后提交新的独立任务。';
}
if (job.effect_may_have_applied === true && job.effect_resolution === 'unknown') {
return '操作效果可能已发生;资源已安全锁定,需管理员人工处理。';
}
if (job.effect_may_have_applied === true && job.effect_resolution === 'applied'
&& job.effect_scope === 'partial') {
return '任务仍为失败;系统已确认部分宿主机已应用、部分未应用,未确认状态已收敛,任务级安全栅栏已解除。';
}
if (job.effect_may_have_applied === true && ['applied', 'not_applied'].includes(job.effect_resolution)) {
return `任务仍为失败;系统已确认操作${job.effect_resolution === 'applied' ? '已应用' : '未应用'},任务级安全栅栏已解除。`;
}
return text(job.error, '任务执行失败。');
}
function renderRows() {
const body = byId('operations-body');
body.replaceChildren();
for (const job of state.page.items) {
const view = taskView(job);
const tr = el('tr');
tr.dataset.operationId = String(job.id || '');
const detailButton = el('button', 'btn btn-primary btn-sm', '查看详情');
detailButton.type = 'button'; detailButton.dataset.operationDetail = String(job.id || '');
const actions = el('div', 'd-flex flex-wrap gap-1'); actions.append(detailButton);
const warning = failureText(job, view);
const cells = [
stack(`#${text(job.id)} · ${text(job.kind_label || job.title || job.display?.kind || job.kind, '后台任务')}`, job.created_at ? `创建 ${date(job.created_at)}` : ''),
stack(text(job.instance_name, '无关联实例'), job.instance_id ? `实例 #${job.instance_id}` : '', job.order_id ? `订单 #${job.order_id}` : ''),
stack(`操作人:${text(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`, job.owner_id ? `所属:${text(job.owner_name)} #${job.owner_id}` : ''),
stack(text(job.host_name), text(job.region, '地区未记录')),
stack(el('strong', view.tone, view.label), warning ? el('span', 'text-danger', warning) : ''),
stack(text(job.operation_id, '无操作标识'), text(job.phase, view.terminal ? '已终结' : '后台执行中')),
stack(job.updated_at ? date(job.updated_at) : '更新时间未记录', job.error && view.status === 'failed' ? el('span', 'text-danger', job.error) : ''),
actions,
];
cells.forEach((content, index) => {
const td = el('td'); td.dataset.label = columns[index]; td.append(content); tr.append(td);
});
body.append(tr);
}
if (!state.page.items.length) {
const row = el('tr'); const cell = el('td', 'text-center text-muted py-4', '没有符合条件的任务。');
cell.colSpan = columns.length; row.append(cell); body.append(row);
}
}
function renderPagination() {
const page = state.page?.pagination;
byId('operations-count').textContent = page ? `共 ${page.total} 条` : '数据未获取';
byId('operations-pagination').hidden = !page || !page.total;
byId('operations-page-label').textContent = page ? `第 ${page.page} / ${page.total_pages} 页 · 共 ${page.total} 条` : '任务数据暂不可用';
byId('operations-previous').disabled = state.loading || !page || page.page <= 1;
byId('operations-next').disabled = state.loading || !page || page.page >= page.total_pages;
byId('operations-refresh').disabled = state.loading;
byId('operations-body').setAttribute('aria-busy', String(state.loading));
}
function summaryValue(summary, key) {
const field = key === 'locked' ? 'unresolved_effect' : key;
const value = summary[field];
const number = Number(value);
return Number.isFinite(number) && number >= 0 ? number.toLocaleString('zh-CN') : '—';
}
function applyPage(page, replaceRows = true) {
if (!Array.isArray(page?.items) || !page.pagination || !page.filters || !page.summary) {
throw new Error('任务数据格式无效,请刷新。');
}
state.page = page; state.loadedUrl = payloadUrl(page);
syncOptions(page); readForm(state.loadedUrl);
for (const key of ['total', 'active', 'failed', 'locked']) {
byId(`operations-summary-${key}`).textContent = summaryValue(page.summary, key);
}
if (replaceRows) renderRows();
byId('operations-shown-filters').textContent = shownFilters();
renderPagination();
}
async function loadPage(input, historyMode = 'push') {
const url = listUrl(input);
state.request?.abort('replaced');
const controller = new AbortController(); state.request = controller;
const serial = ++state.serial; state.loading = true;
renderPagination(); notice('正在读取任务记录…');
try {
const payload = await api(`/api/v1/admin/operations${url.search}`, controller);
if (controller.signal.aborted || serial !== state.serial) return;
applyPage(payload);
if (historyMode === 'push' && state.loadedUrl.href !== location.href) history.pushState(historyData(), '', state.loadedUrl);
notice(`已读取 ${payload.pagination.total} 条任务${payload.generated_at ? ` · ${date(payload.generated_at)}` : ''}`);
} catch (error) {
if ((controller.signal.aborted && controller.signal.reason !== 'timeout') || serial !== state.serial) return;
notice(`${error.message}${state.page ? ' 已保留上次读取的任务记录。' : ''}`, true);
} finally {
if (serial === state.serial) { state.loading = false; state.request = null; renderPagination(); }
}
}
function healthNotice(message, error = false) {
const node = byId('operations-health-state');
node.textContent = message;
node.className = `fs-13 mb-0 ${error ? 'text-danger' : 'text-muted'}`;
}
function renderHealth(payload) {
if (!Array.isArray(payload?.checks) || !payload.checked_at) throw new Error('运行状态数据格式无效。');
const body = byId('operations-health-body'); body.replaceChildren();
const statuses = { ok: ['正常', 'success'], busy: ['运行中', 'primary'], warning: ['需处理', 'warning'], error: ['异常', 'danger'], unknown: ['未知', 'secondary'], disabled: ['未启用', 'secondary'] };
for (const check of payload.checks) {
const [label, tone] = statuses[check.status] || statuses.unknown;
const column = el('div', 'col-md-6 col-xl-4');
const title = el('div', 'd-flex align-items-center gap-2 mb-1');
title.append(el('h3', 'fs-14 fw-semibold mb-0', text(check.label)), el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, label));
column.append(title, el('p', 'text-muted fs-13 mb-1 text-break', text(check.message)));
if (check.last_seen_at) column.append(el('p', 'text-muted fs-12 mb-0', `最近活动 ${date(check.last_seen_at)}`));
body.append(column);
}
state.health = payload;
healthNotice(`检查于 ${date(payload.checked_at)} · 运行状态只在打开页面或手动点击时读取。`);
}
async function refreshHealth() {
if (document.hidden || state.healthRequest) return;
const controller = new AbortController(); state.healthRequest = controller;
byId('operations-health-refresh').disabled = true;
byId('operations-health-body').setAttribute('aria-busy', 'true');
healthNotice('正在检查运行状态…');
try {
const payload = await api('/api/v1/admin/operations/health', controller);
if (!controller.signal.aborted) renderHealth(payload);
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
healthNotice(`${error.message}${state.health ? ' 已保留上次结果。' : ''}`, true);
} finally {
if (state.healthRequest === controller) {
state.healthRequest = null;
byId('operations-health-refresh').disabled = false;
byId('operations-health-body').setAttribute('aria-busy', 'false');
}
}
}
function safeLink(value, label) {
if (!value) return null;
try {
const url = new URL(value, location.origin);
if (url.origin !== location.origin || !/^https?:$/.test(url.protocol)) return null;
const link = el('a', 'btn btn-light btn-sm', label); link.href = url.pathname + url.search + url.hash;
return link;
} catch { return null; }
}
function infoList(entries) {
const list = el('dl', 'admin-instance-details');
for (const [label, value] of entries) list.append(el('dt', '', label), el('dd', '', text(value)));
return list;
}
function detailNotice(message, error = false) {
const node = byId('operation-detail-state');
node.textContent = message; node.hidden = !message;
node.className = `alert alert-${error ? 'danger' : 'info'}`;
node.setAttribute('role', error ? 'alert' : 'status');
}
function taskFailureMessage(task, fallback) {
const message = task?.error || fallback;
const recoveryNotice = recoveryTaskFailureNotice(task);
if (recoveryNotice) return recoveryNotice;
if (task?.effect_may_have_applied === true) {
return `${message} 操作效果可能已经发生,请勿再次提交,并联系管理员核查。`;
}
return task?.safe_to_resubmit === false
? `${message} 此任务不可再次提交,请联系管理员核查。` : message;
}
function canManage() { return root?.dataset.canManage === '1'; }
function renderDetailActions() {
const busy = Boolean(state.actionRequest);
const inspect = byId('operation-detail-inspect');
inspect.hidden = state.detailJob?.can_inspect !== true;
inspect.disabled = busy;
inspect.textContent = busy && state.actionRequest?.kind === 'inspect' ? '正在检查…' : '只读检查宿主机';
const force = byId('operation-detail-force-delete');
force.hidden = !canManage() || state.detailJob?.can_force_delete !== true;
force.disabled = busy || state.forceDeleteAccepted || state.forceDeleteBlocked;
force.textContent = state.forceDeleteAccepted ? '任务已接收'
: state.forceDeleteBlocked ? '操作已锁定' : '确认强制删除';
const resolution = byId('operation-effect-resolution');
resolution.hidden = !canManage() || state.detailJob?.can_resolve_effect !== true || state.effectResolved;
byId('operation-effect-submit').disabled = busy;
}
function renderDetail(payload) {
const job = payload?.job;
if (!job || String(job.id) !== state.detailId) throw new Error('任务详情与请求不一致,请重新打开。');
state.detailJob = job;
state.inspection = payload.inspection && typeof payload.inspection === 'object' ? payload.inspection : null;
const view = taskView(job);
byId('operation-detail-title').textContent = `#${job.id} · ${text(job.kind_label || job.title || job.display?.kind || job.kind, '后台任务')}`;
const body = byId('operation-detail-body');
body.replaceChildren(infoList([
['任务状态', view.label], ['操作标识', job.operation_id], ['处理阶段', job.phase],
['操作人', `${text(job.actor_name)}${job.actor_id ? ` #${job.actor_id}` : ''}`],
['实例所属用户', job.owner_id ? `${text(job.owner_name)} #${job.owner_id}` : '未关联'],
['宿主机', `${text(job.host_name)}${job.host_id ? ` #${job.host_id}` : ''}`],
['关联实例', job.instance_id ? `${text(job.instance_name)} #${job.instance_id}` : '无关联实例'],
['实例 UUID', job.instance_uuid], ['关联订单', job.order_id ? `#${job.order_id}` : '无关联订单'],
['Agent 原因', job.agent_cause_label || job.agent_cause_code],
['创建时间', date(job.created_at)], ['更新时间', date(job.updated_at)],
]));
const failure = failureText(job, view);
const storageFailure = job.kind === 'host_storage_configure'
&& view.status === 'failed';
if (failure) body.append(el('h3', 'h6 mt-4', job.recovery?.pending === true
? '安全恢复状态' : '失败详情'), el('p', 'text-danger text-break', failure));
if (job.recovery?.pending === true) {
const code = String(job.recovery.code || job.finalization_error_code || '');
const recoveryTitle = code === 'recovery_dispatch_ledger_conflict'
|| job.dispatch_state === 'invalid' ? '派发账本修复'
: job.dispatch_state === 'not_dispatched'
? 'PHP 本地账本收尾' : '持续恢复详情';
const recoveryMode = recoveryTitle === '派发账本修复'
? '修复派发计数后,使用原任务身份和已保存回执重新核验;不会重放宿主机操作'
: recoveryTitle === 'PHP 本地账本收尾'
? '只重试面板本地账本收尾;不会联系 Agent 或执行宿主机操作'
: '按原任务身份持续核对;不会重复执行原操作';
body.append(el('h3', 'h6 mt-4', recoveryTitle), infoList([
['恢复方式', recoveryMode],
['最近异常', job.recovery.message],
['异常代码', job.recovery.code],
['最近核对', date(job.recovery.last_checked_at)],
['下次核对', job.recovery.next_check_at
? date(job.recovery.next_check_at) : '等待后台调度'],
]));
} else if (job.finalization_incident === true) {
body.append(el('h3', 'h6 mt-4', '业务账本收尾事件'),
el('p', 'text-danger text-break', storageFailure
? `旧存储任务已终态失败,收尾事件仅保留审计且不会重放;存储目录页仍可以终态任务账本为准提交新的独立任务。${job.finalization_error_code ? ` 事件代码:${job.finalization_error_code}` : ''}`
: `任务已终态失败,但业务账本未能安全收敛;资金和资源已保持锁定,不会自动重试。${job.finalization_error_code ? ` 事件代码:${job.finalization_error_code}` : ''}`));
}
if (state.inspection) {
const inspectedAt = state.inspection.checked_at || state.inspection.inspected_at;
const paymentEvidence = job.kind === 'payment_create';
const completionDeliveryError = typeof state.inspection.completion_delivery_error === 'string'
? state.inspection.completion_delivery_error.trim() : '';
body.append(el('h3', 'h6 mt-4', paymentEvidence ? '支付账本审计' : '宿主机只读检查'),
el('p', 'text-muted fs-13', paymentEvidence
? `已记录外部支付平台核验结论${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。原任务仍保持失败,且没有重新下单。`
: storageFailure
? `已完成只读检查${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。检查不会执行 Agent 操作;旧任务仍保持失败,也不会影响存储目录页提交新的独立任务。`
: `已完成只读检查${inspectedAt ? ` · ${date(inspectedAt)}` : ''}。检查不会执行 Agent 操作;任务仍以失败详情和资源安全栅栏为准。`));
if (completionDeliveryError) {
// infoList/el write via textContent; Agent-supplied text never becomes
// markup even if a future protocol regression returns HTML-like data.
body.append(infoList([['回执异常', completionDeliveryError]]));
}
}
for (const note of payload.notes || []) body.append(el('p', 'text-muted fs-13 mt-3 mb-0', note));
const links = byId('operation-detail-links'); links.replaceChildren();
for (const [key, label] of [['instance', '查看实例'], ['billing', '按订单号查账']]) {
const link = safeLink(job.links?.[key], label); if (link) links.append(link);
}
renderDetailActions();
}
async function inspectOperation(id) {
if (state.detailId !== String(id) || state.detailJob?.can_inspect !== true || state.actionRequest) return;
const controller = new AbortController(); controller.kind = 'inspect'; state.actionRequest = controller;
renderDetailActions(); detailNotice('正在执行一次宿主机只读检查;不会执行 Agent 操作。');
try {
const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/inspect`, controller, 30000, {
method: 'POST', body: '{}',
});
if (String(payload?.job?.id || '') !== String(id)) throw new Error('只读检查结果与当前任务不匹配。');
if (state.detailId !== String(id) || !byId('operation-detail').open) return;
renderDetail(payload);
detailNotice('宿主机只读检查已完成。任务状态未被重写,也未执行 Agent 操作。');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
detailNotice(`宿主机只读检查失败:${error.message}`, true);
} finally {
if (state.actionRequest === controller) { state.actionRequest = null; renderDetailActions(); }
}
}
async function resolveEffect(id) {
if (!canManage() || state.detailId !== String(id) || state.detailJob?.can_resolve_effect !== true
|| state.actionRequest || state.effectResolved) return;
const resolution = byId('operation-effect-value').value;
const reason = byId('operation-effect-reason').value.trim();
if (!['applied', 'not_applied'].includes(resolution)) {
detailNotice('请选择人工核实结果。', true); return;
}
if (reason.length < 20 || reason.length > 500) {
detailNotice('审计说明必须为 20–500 个字符。', true); return;
}
const label = resolution === 'applied' ? '操作效果已经发生' : '操作效果未发生';
if (!window.confirm(`确认将人工核实结果记录为“${label}”?\n\n原任务仍保持失败,不会重放 Agent 或支付请求。服务端仅会在可原子收敛相关业务账本时写入结论。`)) return;
const controller = new AbortController(); controller.kind = 'resolve-effect'; state.actionRequest = controller;
renderDetailActions(); detailNotice('正在核验最新证据并原子写入人工审计结论…');
try {
const payload = await api(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/resolve-effect`, controller, 45000, {
method: 'POST', body: JSON.stringify({ resolution, reason }),
});
if (String(payload?.job?.id || '') !== String(id)) throw new Error('审计结果与当前任务不匹配。');
if (state.detailId !== String(id) || !byId('operation-detail').open) return;
state.effectResolved = true;
renderDetail(payload);
state.effectResolved = true;
renderDetailActions();
detailNotice('人工核实结论与对应账本已原子收敛;原任务仍保持失败。');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
detailNotice(`人工审计未完成:${error.message}`, true);
} finally {
if (state.actionRequest === controller) { state.actionRequest = null; renderDetailActions(); }
}
}
async function forceDelete(id) {
if (!canManage() || state.detailId !== String(id) || state.detailJob?.can_force_delete !== true
|| state.actionRequest || state.forceDeleteAccepted || state.forceDeleteBlocked) return;
if (!window.confirm('这是强制删除的数据丢失确认。\n\n继续会创建一个新的后台任务,并允许宿主机强制断电;未刷入磁盘的数据可能永久丢失。\n\n确认承担风险并继续?')) return;
const controller = new AbortController(); state.actionRequest = controller;
renderDetailActions(); detailNotice('正在提交强制删除请求…');
try {
const payload = await acceptedTask(`/api/v1/admin/operations/jobs/${encodeURIComponent(id)}/force-delete`, controller, 30000, {
method: 'POST', body: JSON.stringify({ ack_data_loss: true }),
});
state.forceDeleteAccepted = true;
state.forceDeleteAcceptedIds.add(String(id));
announceTaskAccepted(payload, { source: 'admin-force-delete' });
const taskId = String(payload.task_id || '').trim();
const handle = observeTask(payload, {
onUpdate: task => {
if (state.detailId === String(id) && !task.terminal) detailNotice(`强制删除任务 #${task.id} 正在后台执行。`);
},
onTerminal: task => {
const succeeded = taskSucceededWithoutRecovery(task);
const message = succeeded
? `强制删除任务 #${task.id} 已成功。`
: taskFailureMessage(task, `强制删除任务 #${task.id} 失败。`);
void (async () => {
await loadPage(listUrl(), 'none');
if (byId('operation-detail').open && state.detailId === String(id)) await openDetail(task.id, null);
notice(message, !succeeded);
if (byId('operation-detail').open && state.detailId === String(task.id)) detailNotice(message, !succeeded);
})();
},
onStop: reason => {
if (reason !== 'deadline') return;
const message = `强制删除任务 #${taskId} 的自动观察已到达截止时间。任务可能仍在后台执行;请刷新任务列表核对结果。`;
notice(message, true);
if (state.detailId === String(id)) detailNotice(message, true);
},
});
state.forceDeleteObservers.set(String(id), handle);
void handle.done.finally(() => state.forceDeleteObservers.delete(String(id)));
detailNotice(`任务已接收(#${taskId}),正在后台执行。`);
notice(`强制删除任务已接收${taskId ? `(#${taskId})` : ''}。`);
} catch (error) {
state.forceDeleteBlocked = true;
state.forceDeleteBlockedIds.add(String(id));
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
detailNotice(error.message || '请求未成功;为避免重复执行,请先确认任务中心。', true);
notice(`强制删除请求未确认:${error.message}`, true);
} finally {
if (state.actionRequest === controller) { state.actionRequest = null; renderDetailActions(); }
}
}
function finishDetailClose(id) {
state.detailClosing = false;
document.documentElement.classList.remove('admin-instance-detail-open');
document.body.style.removeProperty('--admin-instance-scroll-top');
if (state.scroll) {
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
state.scroll = null;
}
const opener = state.opener?.isConnected ? state.opener : (id ? root.querySelector(`[data-operation-detail="${id}"]`) : null);
opener?.focus({ preventScroll: true }); state.opener = null;
}
function closeDetail() {
if (state.detailClosing) return;
const id = state.detailId;
state.detailRequest?.abort('closed'); state.detailRequest = null;
state.actionRequest?.abort('closed'); state.actionRequest = null;
state.detailId = null; state.detailJob = null; state.forceDeleteAccepted = false;
state.forceDeleteBlocked = false;
state.inspection = null; state.effectResolved = false;
state.detailClosing = true;
void window.VenixDrawerMotion.closeDrawerWithMotion(byId('operation-detail')).then(closed => {
if (closed) finishDetailClose(id);
else state.detailClosing = false;
});
}
async function openDetail(id, opener) {
if (!/^[1-9][0-9]*$/.test(id) || state.detailClosing) return;
state.detailRequest?.abort('replaced');
state.detailId = id; state.detailJob = null; state.opener = opener; state.forceDeleteAccepted = state.forceDeleteAcceptedIds.has(String(id));
state.forceDeleteBlocked = state.forceDeleteBlockedIds.has(String(id));
state.inspection = null; state.effectResolved = false;
const controller = new AbortController(); state.detailRequest = controller;
byId('operation-detail-title').textContent = `任务 #${id}`;
byId('operation-detail-body').replaceChildren(); byId('operation-detail-links').replaceChildren();
byId('operation-detail-inspect').hidden = true;
byId('operation-detail-force-delete').hidden = true;
byId('operation-effect-resolution').hidden = true;
byId('operation-effect-value').value = '';
byId('operation-effect-reason').value = '';
detailNotice('正在读取任务详情…');
if (!byId('operation-detail').open) {
state.scroll = { x: window.scrollX, y: window.scrollY };
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.scroll.y}px`);
document.documentElement.classList.add('admin-instance-detail-open');
window.VenixDrawerMotion.openDrawerWithMotion(byId('operation-detail'));
}
try {
const payload = await api(`/api/v1/admin/operations/jobs/${id}`, controller);
if (controller.signal.aborted || state.detailId !== id) return;
renderDetail(payload); detailNotice('');
} catch (error) {
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
if (state.detailId === id) detailNotice(`${error.message} 请关闭后刷新列表。`, true);
} finally { if (state.detailRequest === controller) state.detailRequest = null; }
}
if (root) {
try {
const payload = JSON.parse(byId('admin-operations-bootstrap').textContent);
if (payload) applyPage(payload); else readForm(listUrl());
} catch { notice('初始任务数据无效,请点击刷新。', true); readForm(listUrl()); }
byId('operations-filter').addEventListener('submit', event => { event.preventDefault(); void loadPage(formUrl()); });
byId('operations-reset').addEventListener('click', event => {
if (event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
event.preventDefault();
const url = new URL('/admin/operations', location.origin); readForm(url); void loadPage(url);
});
byId('operations-refresh').addEventListener('click', () => { void loadPage(listUrl(), 'none'); });
for (const [id, delta] of [['operations-previous', -1], ['operations-next', 1]]) {
byId(id).addEventListener('click', () => {
if (!state.page) return;
const url = new URL(state.loadedUrl); url.searchParams.set('page', state.page.pagination.page + delta); void loadPage(url);
});
}
root.addEventListener('click', event => {
const button = event.target.closest('[data-operation-detail]');
if (button) void openDetail(button.dataset.operationDetail, button);
});
byId('operations-health-refresh').addEventListener('click', () => { void refreshHealth(); });
const dialog = byId('operation-detail');
byId('operation-detail-close').addEventListener('click', closeDetail);
byId('operation-detail-inspect').addEventListener('click', event => {
event.preventDefault(); if (state.detailId) void inspectOperation(state.detailId);
});
byId('operation-detail-force-delete').addEventListener('click', event => {
event.preventDefault(); if (state.detailId) void forceDelete(state.detailId);
});
byId('operation-effect-submit').addEventListener('click', event => {
event.preventDefault(); if (state.detailId) void resolveEffect(state.detailId);
});
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDetail(); });
dialog.addEventListener('click', event => {
if (event.target === dialog) {
const rect = dialog.getBoundingClientRect();
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) closeDetail();
}
const link = event.target.closest('a[href]');
if (link && event.button === 0 && !event.ctrlKey && !event.metaKey && !event.shiftKey && !event.altKey && !event.defaultPrevented) closeDetail();
});
window.addEventListener('popstate', () => { closeDetail(); readForm(listUrl()); void loadPage(listUrl(), 'none'); });
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
state.request?.abort('hidden'); state.healthRequest?.abort('hidden');
state.detailRequest?.abort('hidden'); state.actionRequest?.abort('hidden');
}
});
window.addEventListener('pagehide', () => {
state.request?.abort('pagehide'); state.healthRequest?.abort('pagehide');
state.detailRequest?.abort('pagehide'); state.actionRequest?.abort('pagehide');
if (state.scroll) history.replaceState(historyData({ operationsDetailScroll: state.scroll }), '', location.href);
});
const stored = history.state?.operationsDetailScroll;
if (stored && Number.isFinite(stored.y) && Number.isFinite(stored.x)) {
requestAnimationFrame(() => { window.scrollTo({ left: stored.x, top: stored.y, behavior: 'instant' }); });
}
renderPagination(); void refreshHealth();
}