|
|
import { normalizeTask } from './task-observer.js?v=2026101903';
|
|
|
|
|
|
const REFRESH_MS = 10000;
|
|
|
// Covers the longest server-side absolute task deadline (145 minutes) while
|
|
|
// remaining finite and GET-only.
|
|
|
const OBSERVATION_BUDGET_MS = 9_300_000;
|
|
|
const REQUEST_TIMEOUT_MS = 12000;
|
|
|
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = {
|
|
|
items: [], nextCursor: '', hasMore: false, activeCount: 0, unreadCount: 0,
|
|
|
loading: false, request: null, serial: 0, timer: null, deadline: 0,
|
|
|
opener: null, scroll: null, closing: false, initialized: false,
|
|
|
readQueue: new Set(), readAttempted: new Set(), readInFlight: false,
|
|
|
readRequest: null, badgeRequest: null, csrfToken: '', reloadRequested: false,
|
|
|
};
|
|
|
|
|
|
function element(tag, className = '', value = undefined) {
|
|
|
const node = document.createElement(tag);
|
|
|
node.className = className;
|
|
|
if (value !== undefined) node.textContent = String(value);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function validCount(value) {
|
|
|
return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;
|
|
|
}
|
|
|
|
|
|
function validPagination(value) {
|
|
|
return value && typeof value === 'object' && !Array.isArray(value)
|
|
|
&& (value.next_cursor === null || typeof value.next_cursor === 'string')
|
|
|
&& typeof value.has_more === 'boolean';
|
|
|
}
|
|
|
|
|
|
export function dateText(value) {
|
|
|
if (!value) return '';
|
|
|
const numeric = Number(value);
|
|
|
const parsed = Number.isFinite(numeric) && numeric > 0
|
|
|
? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(String(value));
|
|
|
return Number.isFinite(parsed) ? new Date(parsed).toLocaleString('zh-CN', { hour12: false }) : String(value);
|
|
|
}
|
|
|
|
|
|
async function csrfToken(controller) {
|
|
|
if (state.csrfToken) return state.csrfToken;
|
|
|
const response = await fetch('/api/v1/session', {
|
|
|
method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin',
|
|
|
cache: 'no-store', signal: controller.signal,
|
|
|
});
|
|
|
const payload = await response.json();
|
|
|
if (!response.ok || typeof payload?.csrf_token !== 'string' || !payload.csrf_token) {
|
|
|
throw new Error('无法确认任务已读状态。');
|
|
|
}
|
|
|
state.csrfToken = payload.csrf_token;
|
|
|
return state.csrfToken;
|
|
|
}
|
|
|
|
|
|
async function markPresentedRead(items) {
|
|
|
for (const item of items) {
|
|
|
const task = normalizeTask(item);
|
|
|
if (task.terminal && task.id && !state.readAttempted.has(task.id)) {
|
|
|
state.readQueue.add(task.id);
|
|
|
}
|
|
|
}
|
|
|
if (state.readInFlight || !state.readQueue.size || !canRead()) return;
|
|
|
const ids = Array.from(state.readQueue).slice(0, 50);
|
|
|
ids.forEach(id => { state.readQueue.delete(id); state.readAttempted.add(id); });
|
|
|
state.readInFlight = true;
|
|
|
const controller = new AbortController();
|
|
|
state.readRequest = controller;
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), REQUEST_TIMEOUT_MS);
|
|
|
try {
|
|
|
const token = await csrfToken(controller);
|
|
|
const response = await fetch('/api/v1/tasks/read', {
|
|
|
method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'X-CSRF-Token': token },
|
|
|
credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
|
|
|
body: JSON.stringify({ ids }),
|
|
|
});
|
|
|
const payload = await response.json();
|
|
|
if (!response.ok || !validCount(payload?.read_count) || !validCount(payload?.unread_count)) {
|
|
|
throw new Error('任务已读状态更新失败。');
|
|
|
}
|
|
|
const marked = new Set(ids);
|
|
|
for (const item of state.items) {
|
|
|
if (marked.has(String(item?.id || ''))) item.unread = false;
|
|
|
}
|
|
|
document.querySelectorAll('.panel-task-item[data-task-id]').forEach(article => {
|
|
|
if (marked.has(article.dataset.taskId || '')) article.classList.remove('is-unread');
|
|
|
});
|
|
|
state.unreadCount = payload.unread_count;
|
|
|
renderBadge();
|
|
|
} catch {
|
|
|
// Presentation remains successful. A failed acknowledgement is not
|
|
|
// automatically retried; another drawer session may acknowledge it.
|
|
|
} finally {
|
|
|
clearTimeout(timeout);
|
|
|
if (state.readRequest === controller) state.readRequest = null;
|
|
|
state.readInFlight = false;
|
|
|
if (state.readQueue.size && canRead()) void markPresentedRead([]);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
export function taskTitle(task) {
|
|
|
for (const value of [
|
|
|
task?.kind_label, task?.action_label, task?.title, task?.label, task?.summary,
|
|
|
]) {
|
|
|
if (typeof value === 'string' && value.trim()) return value.trim();
|
|
|
}
|
|
|
return '后台任务';
|
|
|
}
|
|
|
|
|
|
function statusText(task) {
|
|
|
if (!task.terminal) return '执行中';
|
|
|
return { succeeded: '已成功', failed: '已失败' }[task.status] || '已失败';
|
|
|
}
|
|
|
|
|
|
function statusClass(task) {
|
|
|
return task.terminal ? task.status : 'running';
|
|
|
}
|
|
|
|
|
|
function setMessage(message, tone = '') {
|
|
|
const target = byId('panel-task-state');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `panel-task-state${tone ? ` is-${tone}` : ''}`;
|
|
|
target.setAttribute('role', tone === 'error' ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function renderBadge() {
|
|
|
const badge = byId('cloud-task-center-badge');
|
|
|
if (!badge) return;
|
|
|
const count = Math.max(0, Number(state.unreadCount) || Number(state.activeCount) || 0);
|
|
|
badge.textContent = count > 99 ? '99+' : String(count);
|
|
|
badge.hidden = count === 0;
|
|
|
}
|
|
|
|
|
|
function copyButton(taskId) {
|
|
|
const button = element('button', 'button button-ghost small panel-task-copy', '复制任务编号');
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
try {
|
|
|
if (!navigator.clipboard?.writeText) throw new Error();
|
|
|
await navigator.clipboard.writeText(taskId);
|
|
|
setMessage('任务编号已复制。');
|
|
|
} catch {
|
|
|
setMessage(`任务编号:${taskId}`);
|
|
|
}
|
|
|
});
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function detailBlock(task) {
|
|
|
const details = element('details', 'panel-task-details');
|
|
|
details.append(element('summary', '', '查看详情'));
|
|
|
const list = element('dl', 'panel-task-detail-list');
|
|
|
const append = (label, value) => {
|
|
|
if (value === null || value === undefined || value === '') return;
|
|
|
list.append(element('dt', '', label), element('dd', '', value));
|
|
|
};
|
|
|
append('任务编号', task.id);
|
|
|
append('当前状态', statusText(task));
|
|
|
append('错误代码', task.error_code);
|
|
|
if (task.result !== null && task.result !== undefined) {
|
|
|
let result = '';
|
|
|
try { result = typeof task.result === 'string' ? task.result : JSON.stringify(task.result, null, 2); }
|
|
|
catch { result = '结果数据无法显示。'; }
|
|
|
append('任务结果', result);
|
|
|
}
|
|
|
details.append(list);
|
|
|
return details;
|
|
|
}
|
|
|
|
|
|
function renderItems(emptyMessage = '暂无任务记录。') {
|
|
|
const list = byId('panel-task-list');
|
|
|
if (!list) return;
|
|
|
list.replaceChildren();
|
|
|
const normalized = state.items.map(raw => ({ raw, task: normalizeTask(raw) }));
|
|
|
for (const group of [
|
|
|
{ title: '进行中', items: normalized.filter(item => !item.task.terminal) },
|
|
|
{ title: '已完成', items: normalized.filter(item => item.task.terminal) },
|
|
|
]) {
|
|
|
if (!group.items.length) continue;
|
|
|
const section = element('section', 'panel-task-group');
|
|
|
section.append(element('h2', 'panel-task-group-title', `${group.title}(${group.items.length})`));
|
|
|
for (const { raw, task } of group.items) {
|
|
|
const article = element('article', `panel-task-item is-${statusClass(task)}${raw?.unread === true ? ' is-unread' : ''}`);
|
|
|
if (task.id) article.dataset.taskId = task.id;
|
|
|
const heading = element('div', 'panel-task-item-heading');
|
|
|
heading.append(element('h3', '', taskTitle(raw)), element('span', `panel-task-status is-${statusClass(task)}`, statusText(task)));
|
|
|
article.append(heading);
|
|
|
const meta = element('div', 'panel-task-meta');
|
|
|
const recordedAt = dateText(raw.updated_at || raw.completed_at || raw.created_at);
|
|
|
if (recordedAt) meta.append(element('time', '', recordedAt));
|
|
|
if (task.id) meta.append(element('code', '', task.id));
|
|
|
if (meta.children.length) article.append(meta);
|
|
|
if (task.status === 'failed') {
|
|
|
article.append(element('p', 'panel-task-error', task.error || '任务执行失败。'));
|
|
|
if (raw?.kind === 'host_storage_configure') {
|
|
|
article.append(element('p', 'panel-task-warning', '旧存储任务已终止且不会重放;可到宿主机存储目录页修正后提交新的独立任务。'));
|
|
|
} else if (task.effect_may_have_applied) {
|
|
|
article.append(element('p', 'panel-task-warning', '操作效果可能已经发生。为避免重复执行,请勿再次提交;请将任务编号提供给管理员核查。'));
|
|
|
} else if (task.safe_to_resubmit === false) {
|
|
|
article.append(element('p', 'panel-task-warning', '此任务不可再次提交,请联系管理员核查。'));
|
|
|
}
|
|
|
}
|
|
|
article.append(detailBlock(task));
|
|
|
if (task.id) article.append(copyButton(task.id));
|
|
|
section.append(article);
|
|
|
}
|
|
|
list.append(section);
|
|
|
}
|
|
|
if (!state.items.length) list.append(element('p', 'panel-task-empty', emptyMessage));
|
|
|
}
|
|
|
|
|
|
function renderControls() {
|
|
|
const refresh = byId('panel-task-refresh');
|
|
|
const more = byId('panel-task-more');
|
|
|
if (refresh) refresh.disabled = state.loading;
|
|
|
if (more) { more.hidden = !state.hasMore; more.disabled = state.loading; }
|
|
|
const list = byId('panel-task-list');
|
|
|
if (list) list.setAttribute('aria-busy', String(state.loading));
|
|
|
const count = byId('panel-task-count');
|
|
|
if (count) count.textContent = state.items.length ? `已显示 ${state.items.length} 条` : '';
|
|
|
renderBadge();
|
|
|
}
|
|
|
|
|
|
function clearTimer() {
|
|
|
if (state.timer !== null) clearTimeout(state.timer);
|
|
|
state.timer = null;
|
|
|
}
|
|
|
|
|
|
function canRead() {
|
|
|
const dialog = byId('panel-task-drawer');
|
|
|
return Boolean(dialog?.open) && !state.closing && document.visibilityState === 'visible';
|
|
|
}
|
|
|
|
|
|
function stopRequest() {
|
|
|
clearTimer();
|
|
|
state.request?.abort('stopped');
|
|
|
state.request = null;
|
|
|
state.readRequest?.abort('stopped');
|
|
|
state.readRequest = null;
|
|
|
state.badgeRequest?.abort('stopped');
|
|
|
state.badgeRequest = null;
|
|
|
state.reloadRequested = false;
|
|
|
state.serial += 1;
|
|
|
state.loading = false;
|
|
|
}
|
|
|
|
|
|
async function loadBadgeCounts() {
|
|
|
if (document.visibilityState !== 'visible' || state.badgeRequest) return;
|
|
|
const controller = new AbortController(); state.badgeRequest = controller;
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), REQUEST_TIMEOUT_MS);
|
|
|
try {
|
|
|
const response = await fetch('/api/v1/tasks?state=active&limit=1', {
|
|
|
method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin',
|
|
|
cache: 'no-store', signal: controller.signal,
|
|
|
});
|
|
|
const payload = await response.json();
|
|
|
if (!response.ok || !Array.isArray(payload?.items) || !validPagination(payload?.pagination)
|
|
|
|| !validCount(payload?.active_count) || !validCount(payload?.unread_count)) return;
|
|
|
state.activeCount = payload.active_count;
|
|
|
state.unreadCount = payload.unread_count;
|
|
|
renderBadge();
|
|
|
} catch {
|
|
|
// This one-shot badge read is optional, never retried automatically, and
|
|
|
// never changes task read state.
|
|
|
} finally {
|
|
|
clearTimeout(timeout);
|
|
|
if (state.badgeRequest === controller) state.badgeRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function scheduleRefresh() {
|
|
|
clearTimer();
|
|
|
if (!canRead() || state.loading || state.activeCount < 1) return;
|
|
|
if (Date.now() >= state.deadline) {
|
|
|
setMessage('自动刷新已停止。任务仍会在后台执行,可点击“刷新”查看结果。');
|
|
|
return;
|
|
|
}
|
|
|
state.timer = setTimeout(() => {
|
|
|
state.timer = null;
|
|
|
void load('', 'auto');
|
|
|
}, REFRESH_MS);
|
|
|
}
|
|
|
|
|
|
async function requestPage(taskState, cursor, controller) {
|
|
|
const params = new URLSearchParams({ state: taskState, limit: '20' });
|
|
|
if (cursor) params.set('cursor', cursor);
|
|
|
const timeout = setTimeout(() => controller.abort('timeout'), REQUEST_TIMEOUT_MS);
|
|
|
try {
|
|
|
const response = await fetch(`/api/v1/tasks?${params}`, {
|
|
|
method: 'GET', headers: { Accept: 'application/json' }, credentials: 'same-origin',
|
|
|
cache: 'no-store', signal: controller.signal,
|
|
|
});
|
|
|
let payload;
|
|
|
try { payload = await response.json(); }
|
|
|
catch { throw new Error('任务中心返回了无效数据。'); }
|
|
|
if (!response.ok) {
|
|
|
const error = new Error(payload?.error || payload?.message || `任务中心暂时不可用 (${response.status})。`);
|
|
|
error.status = response.status;
|
|
|
throw error;
|
|
|
}
|
|
|
if (!Array.isArray(payload?.items) || !validPagination(payload?.pagination)
|
|
|
|| !validCount(payload?.active_count) || !validCount(payload?.unread_count)) {
|
|
|
throw new Error('任务中心数据格式无效。');
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
if (controller.signal.reason === 'timeout') throw new Error('任务中心读取超时,请稍后刷新。');
|
|
|
throw error;
|
|
|
} finally { clearTimeout(timeout); }
|
|
|
}
|
|
|
|
|
|
async function load(cursor = '', source = 'manual') {
|
|
|
if (!canRead() || state.loading) return;
|
|
|
clearTimer();
|
|
|
if (source === 'manual') state.deadline = Date.now() + OBSERVATION_BUDGET_MS;
|
|
|
const controller = new AbortController();
|
|
|
const serial = ++state.serial;
|
|
|
state.request = controller;
|
|
|
state.loading = true;
|
|
|
renderControls();
|
|
|
if (source !== 'auto') setMessage('正在读取任务…');
|
|
|
try {
|
|
|
const payload = cursor
|
|
|
? await requestPage('completed', cursor, controller)
|
|
|
: await Promise.all([
|
|
|
requestPage('active', '', controller),
|
|
|
requestPage('completed', '', controller),
|
|
|
]).then(([active, completed]) => ({
|
|
|
...completed,
|
|
|
items: [...active.items, ...completed.items],
|
|
|
active_count: active.active_count,
|
|
|
unread_count: Math.max(active.unread_count, completed.unread_count),
|
|
|
}));
|
|
|
if (controller.signal.aborted || serial !== state.serial || !canRead()) return;
|
|
|
const incoming = payload.items;
|
|
|
const combined = cursor ? [...state.items, ...incoming] : incoming;
|
|
|
const seen = new Set();
|
|
|
state.items = combined.filter(item => {
|
|
|
const key = normalizeTask(item).id || JSON.stringify(item);
|
|
|
if (seen.has(key)) return false;
|
|
|
seen.add(key);
|
|
|
return true;
|
|
|
});
|
|
|
state.nextCursor = String(payload.pagination.next_cursor || '');
|
|
|
state.hasMore = payload.pagination.has_more === true && Boolean(state.nextCursor);
|
|
|
state.activeCount = payload.active_count;
|
|
|
state.unreadCount = payload.unread_count;
|
|
|
renderItems();
|
|
|
void markPresentedRead(state.items);
|
|
|
setMessage(state.activeCount > 0 ? `${state.activeCount} 个任务正在后台执行。` : '已读取最新任务。');
|
|
|
} catch (error) {
|
|
|
if (serial !== state.serial || (controller.signal.aborted && controller.signal.reason !== 'timeout')) return;
|
|
|
if (!state.items.length) renderItems('任务记录暂时不可用,请稍后刷新。');
|
|
|
if (source !== 'auto' || !state.items.length) setMessage(error.message || '任务中心暂时不可用。', 'error');
|
|
|
} finally {
|
|
|
if (serial === state.serial) {
|
|
|
state.request = null;
|
|
|
state.loading = false;
|
|
|
renderControls();
|
|
|
if (state.reloadRequested && canRead()) {
|
|
|
state.reloadRequested = false;
|
|
|
void load('', 'receipt');
|
|
|
} else scheduleRefresh();
|
|
|
}
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function finishClose() {
|
|
|
const dialog = byId('panel-task-drawer');
|
|
|
state.closing = false;
|
|
|
stopRequest();
|
|
|
document.documentElement.classList.remove('panel-task-open');
|
|
|
document.body.style.removeProperty('--panel-task-scroll-top');
|
|
|
if (state.scroll) {
|
|
|
window.scrollTo({ left: state.scroll.x, top: state.scroll.y, behavior: 'instant' });
|
|
|
state.scroll = null;
|
|
|
}
|
|
|
document.querySelectorAll('[data-task-center-open]').forEach(button => button.setAttribute('aria-expanded', 'false'));
|
|
|
if (state.opener?.isConnected) state.opener.focus({ preventScroll: true });
|
|
|
state.opener = null;
|
|
|
if (dialog?.open && !window.VenixDrawerMotion) dialog.close();
|
|
|
}
|
|
|
|
|
|
function close() {
|
|
|
const dialog = byId('panel-task-drawer');
|
|
|
if (!dialog || state.closing) return;
|
|
|
state.closing = true;
|
|
|
stopRequest();
|
|
|
if (window.VenixDrawerMotion) {
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (closed) finishClose();
|
|
|
else state.closing = false;
|
|
|
});
|
|
|
} else {
|
|
|
dialog.close();
|
|
|
finishClose();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function open(opener) {
|
|
|
const dialog = byId('panel-task-drawer');
|
|
|
if (!dialog || dialog.open) return;
|
|
|
state.closing = false;
|
|
|
state.opener = opener || document.querySelector('[data-task-center-open]');
|
|
|
state.scroll = { x: window.scrollX, y: window.scrollY };
|
|
|
document.body.style.setProperty('--panel-task-scroll-top', `${-state.scroll.y}px`);
|
|
|
document.documentElement.classList.add('panel-task-open');
|
|
|
if (window.VenixDrawerMotion) window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
else dialog.showModal();
|
|
|
document.querySelectorAll('[data-task-center-open]').forEach(button => button.setAttribute('aria-expanded', 'true'));
|
|
|
byId('panel-task-close')?.focus({ preventScroll: true });
|
|
|
state.deadline = Date.now() + OBSERVATION_BUDGET_MS;
|
|
|
state.readAttempted.clear();
|
|
|
void load('', 'initial');
|
|
|
}
|
|
|
|
|
|
export function initializeTaskCenter() {
|
|
|
const dialog = byId('panel-task-drawer');
|
|
|
if (!dialog || state.initialized) return;
|
|
|
state.initialized = true;
|
|
|
renderItems();
|
|
|
renderControls();
|
|
|
document.addEventListener('click', event => {
|
|
|
const trigger = event.target.closest('[data-task-center-open]');
|
|
|
if (!trigger || event.defaultPrevented || event.button !== 0 || event.ctrlKey || event.metaKey || event.shiftKey || event.altKey) return;
|
|
|
event.preventDefault();
|
|
|
open(trigger);
|
|
|
});
|
|
|
byId('panel-task-close')?.addEventListener('click', close);
|
|
|
byId('panel-task-refresh')?.addEventListener('click', () => { void load('', 'manual'); });
|
|
|
byId('panel-task-more')?.addEventListener('click', () => { if (state.nextCursor) void load(state.nextCursor, 'more'); });
|
|
|
document.addEventListener('visibilitychange', () => {
|
|
|
if (document.visibilityState === 'hidden') stopRequest();
|
|
|
else if (dialog.open) void load('', 'visible');
|
|
|
else void loadBadgeCounts();
|
|
|
});
|
|
|
dialog.addEventListener('cancel', event => { event.preventDefault(); close(); });
|
|
|
dialog.addEventListener('click', event => {
|
|
|
if (event.target !== dialog) return;
|
|
|
const rect = dialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) close();
|
|
|
});
|
|
|
window.addEventListener('pagehide', stopRequest);
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (!event.persisted) return;
|
|
|
if (dialog.open) close();
|
|
|
void loadBadgeCounts();
|
|
|
});
|
|
|
window.addEventListener('virt-cloud:task-accepted', () => {
|
|
|
state.activeCount += 1;
|
|
|
renderBadge();
|
|
|
if (!canRead()) return;
|
|
|
if (state.loading) state.reloadRequested = true;
|
|
|
else void load('', 'receipt');
|
|
|
});
|
|
|
void loadBadgeCounts();
|
|
|
}
|
|
|
|
|
|
export const taskCenterTest = { statusText, taskTitle };
|