Тесты и опросы: генерация ИИ, критерии оценки, версия 2.0

- ИИ-генерация черновиков тестов (lib/quiz-ai.js, quiz-ai-jobs, quiz-ai.selftest.js)
- Критерии оценки (quiz_grade_scales/quiz_grade_ranges, lib/quiz-grades.js, public/js/grade-scales.js)
- Версия 2.0 формата бэкапа, добавление таблиц тестов в BACKUP_TABLES
- Обновление AGENTS.md под новый функционал тестов/опросов
This commit is contained in:
dev
2026-12-02 14:27:57 +03:00
parent 664f76d820
commit ef4d7cc472
22 changed files with 2884 additions and 130 deletions
+544 -33
View File
@@ -1,8 +1,19 @@
(function () {
let items = [];
let loading = false;
let loaded = false;
let deletedMode = false;
let loadSeq = 0;
let loadAbort = null;
let aiEnabled = false;
let aiBusy = false;
let aiModelsCache = null;
let aiJob = null;
let aiPoll = null;
const AI_HISTORY_LIMIT = 20;
const LOAD_TIMEOUT_MS = 15000;
const aiHistory = { offset: 0, total: 0, items: [], error: '', loading: false, poll: null };
let liveSource = null;
let liveDebounce = null;
function attr(s) {
return esc(String(s == null ? '' : s)).replace(/"/g, '"');
@@ -12,11 +23,19 @@
return {
search: document.getElementById('quizSearch').value.trim(),
kind: document.getElementById('quizKindFilter').value,
mine: document.getElementById('quizMineOnly').checked ? '1' : '',
deleted: document.getElementById('quizDeletedOnly').checked ? '1' : '',
};
}
function mineOnly() {
return !!document.getElementById('quizMineOnly').checked;
}
function visibleItems() {
if (!mineOnly() || !currentUser) return items;
return items.filter(q => Number(q.author_id) === Number(currentUser.id));
}
function kindLabel(kind) {
return kind === 'survey' ? 'Опрос' : 'Тест';
}
@@ -27,7 +46,7 @@
: '<span class="quiz-cover-ic"><i data-lucide="clipboard-list"></i></span>';
const flags = [];
flags.push(`<span class="quiz-flag${q.is_published ? ' on' : ''}">${q.is_published ? 'Опубликован' : 'Черновик'}</span>`);
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Анонимный</span>');
if (q.allow_anonymous) flags.push('<span class="quiz-flag on">Ссылка</span>');
if (q.deleted_at) flags.push('<span class="quiz-flag del">Удалён</span>');
const attempts = q.kind === 'test'
? `Попыток: <b>${q.attempt_count}</b>${q.my_attempt_count ? ` · моих: <b>${q.my_attempt_count}</b>` : ''}`
@@ -41,6 +60,7 @@
} else {
if (q.can_take) actions.push(`<a class="btn-link" href="quiz.html?id=${q.id}">Пройти</a>`);
if (q.can_edit) actions.push(`<a class="btn-link" href="quiz-edit.html?id=${q.id}">Изменить</a>`);
if (q.can_edit && q.allow_anonymous && q.is_published) actions.push(`<button type="button" class="btn-link" data-copy-link="${q.id}">Ссылку</button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link" data-stats="${q.id}">Статистика</button>`);
if (q.can_edit) actions.push(`<button type="button" class="btn-link danger" data-del="${q.id}">Удалить</button>`);
}
@@ -66,58 +86,95 @@
function render() {
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
if (loading) {
if (!loaded) {
list.innerHTML = '';
empty.hidden = true;
return;
}
if (!items.length) {
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-empty';
empty.textContent = deletedMode ? 'В корзине нет тестов и опросов' : 'Тестов и опросов пока нет';
const shown = visibleItems();
if (!shown.length) {
renderPlaceholder(deletedMode
? 'В корзине нет тестов и опросов'
: (mineOnly() ? 'У вас пока нет своих тестов и опросов' : 'Тестов и опросов пока нет'));
return;
}
empty.hidden = true;
list.innerHTML = items.map(cardHtml).join('');
list.innerHTML = shown.map(cardHtml).join('');
renderIcons();
}
function renderPlaceholder(text) {
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-empty';
empty.textContent = text;
}
function renderLoadError(message) {
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-error';
empty.innerHTML = `${esc(message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
document.getElementById('quizRetry').addEventListener('click', () => load());
}
function setBusy(busy) {
const bar = document.getElementById('quizBusy');
if (bar) bar.classList.toggle('on', busy);
const list = document.getElementById('quizList');
if (list) list.classList.toggle('quiz-busy', busy);
}
async function load() {
const seq = ++loadSeq;
loading = true;
render();
const f = filters();
deletedMode = !!f.deleted;
const nextDeleted = !!f.deleted;
const params = new URLSearchParams();
if (f.search) params.set('search', f.search);
if (f.kind) params.set('kind', f.kind);
if (f.mine) params.set('mine', f.mine);
if (f.deleted) params.set('deleted', f.deleted);
if (loadAbort) loadAbort.abort();
const controller = new AbortController();
loadAbort = controller;
let expired = false;
const timer = setTimeout(() => {
expired = true;
controller.abort();
}, LOAD_TIMEOUT_MS);
setBusy(true);
let failure = null;
let nextItems = [];
try {
const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr() });
const res = await fetch(API + '/api/quizzes?' + params.toString(), { headers: hdr(), signal: controller.signal });
const data = await res.json().catch(() => ({}));
if (seq !== loadSeq) return;
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить тесты');
items = Array.isArray(data.items) ? data.items : [];
nextItems = Array.isArray(data.items) ? data.items : [];
aiEnabled = data.ai_enabled !== false;
syncAiButton();
} catch (e) {
if (seq !== loadSeq) return;
if (e && e.name === 'AbortError' && !expired) return;
failure = expired
? new Error('Сервер не ответил вовремя. Закройте лишние вкладки приложения и нажмите «Повторить».')
: e;
} finally {
clearTimeout(timer);
if (loadAbort === controller) loadAbort = null;
if (seq === loadSeq) setBusy(false);
}
loaded = true;
deletedMode = nextDeleted;
if (failure) {
items = [];
loading = false;
const list = document.getElementById('quizList');
const empty = document.getElementById('quizEmpty');
list.innerHTML = '';
empty.hidden = false;
empty.className = 'quiz-error';
empty.innerHTML = `${esc(e.message)}<div style="margin-top:10px"><button type="button" class="btn-primary ghost" id="quizRetry">Повторить</button></div>`;
document.getElementById('quizRetry').addEventListener('click', () => {
empty.className = 'quiz-empty';
load();
});
renderLoadError(failure.message);
return;
}
if (seq !== loadSeq) return;
loading = false;
items = nextItems;
render();
}
@@ -136,6 +193,381 @@
}
}
function syncAiButton() {
const btn = document.getElementById('quizAiBtn');
if (btn) btn.style.display = aiEnabled ? '' : 'none';
}
function setAiStatus(text, kind) {
const el = document.getElementById('quizAiStatus');
el.textContent = text;
el.className = 'quiz-ai-status' + (kind ? ' ' + kind : '');
}
function setAiBusy(busy) {
aiBusy = !!busy;
const runBtn = document.getElementById('quizAiRun');
if (runBtn) runBtn.disabled = aiBusy;
}
function stopAiPoll() {
if (aiPoll) {
clearInterval(aiPoll);
aiPoll = null;
}
}
function syncAiResult(job) {
const box = document.getElementById('quizAiResult');
const text = document.getElementById('quizAiResultText');
const edit = document.getElementById('quizAiOpenEdit');
const pub = document.getElementById('quizAiOpenPublic');
if (!box || !text) return;
if (job && job.status === 'done' && job.quiz_id) {
const editUrl = 'quiz-edit.html?id=' + job.quiz_id;
box.hidden = false;
text.textContent = `Готово: создан тест #${job.quiz_id}, вопросов: ${job.questions || 0}.`;
if (edit) edit.href = editUrl;
if (pub) pub.href = editUrl + '#public';
renderIcons();
} else {
box.hidden = true;
if (text) text.textContent = '';
if (edit) edit.removeAttribute('href');
if (pub) pub.removeAttribute('href');
}
}
function applyAiJob(job) {
aiJob = job || null;
if (!job) {
setAiBusy(false);
syncAiResult(null);
return;
}
if (job.status === 'pending' || job.status === 'processing') {
setAiBusy(true);
syncAiResult(null);
setAiStatus(job.status === 'pending'
? 'Задание в очереди… страницу можно закрыть, результат появится в списке.'
: 'ИИ генерирует вопросы… страницу можно закрыть, результат появится в списке.', 'busy');
return;
}
setAiBusy(false);
stopAiPoll();
if (job.status === 'done') {
syncAiResult(job);
setAiStatus('Генерация завершена. Тест создан как черновик.');
load();
} else {
syncAiResult(null);
setAiStatus('Ошибка: ' + (job.error || 'Не удалось сгенерировать тест'), 'error');
}
}
async function refreshAiJob() {
try {
const res = await fetch(API + '/api/quizzes/ai-jobs/active', { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) return;
if (data.job) applyAiJob(data.job);
else if (aiBusy) applyAiJob(null);
} catch (e) {}
}
function startAiPoll() {
stopAiPoll();
aiPoll = setInterval(refreshAiJob, 3000);
}
function aiStatusLabel(status) {
if (status === 'pending') return 'В очереди';
if (status === 'processing') return 'В работе';
if (status === 'done') return 'Готово';
if (status === 'error') return 'Ошибка';
return status || '—';
}
function aiDifficultyLabel(value) {
if (value === 'easy') return 'лёгкая';
if (value === 'hard') return 'сложная';
return 'средняя';
}
function aiHistoryMeta(job) {
const parts = [];
parts.push(`#${job.id}`);
parts.push(kindLabel(job.kind));
parts.push(`вопросов: <b>${job.questions != null ? job.questions : job.count}</b>`);
parts.push(`сложность: ${aiDifficultyLabel(job.difficulty)}`);
if (job.attempts > 1) parts.push(`попыток: <b>${job.attempts}</b>`);
if (job.model) parts.push(`модель: <b>${esc(job.model)}</b>`);
else if (job.profile && job.profile !== 'native') parts.push(`профиль: <b>${esc(job.profile)}</b>`);
else parts.push('модель: <b>нативная</b>');
if (currentUser && currentUser.role === 'admin') {
const who = job.user_name || job.user_username;
if (who) parts.push(`автор: <b>${esc(who)}</b>`);
}
return parts.join(' · ');
}
function aiHistoryRow(job) {
const prompt = String(job.prompt || '').trim();
const created = job.created_at ? fmtDateTime(job.created_at) : '';
const finished = job.finished_at ? ' → ' + fmtDateTime(job.finished_at) : '';
const link = job.quiz_id
? `<a class="btn-link quiz-ai-job-link" href="quiz-edit.html?id=${job.quiz_id}">Открыть тест #${job.quiz_id}</a>`
: '';
return `<div class="quiz-ai-job">
<div class="quiz-ai-job-head">
<span class="quiz-ai-job-status ${attr(job.status)}" data-job-status="${job.id}">${aiStatusLabel(job.status)}</span>
<span class="quiz-ai-job-meta">${created}${finished}</span>
</div>
<div class="quiz-ai-job-prompt" title="${attr(prompt.slice(0, 300))}">${prompt ? esc(prompt) : '<span style="color:var(--muted)">Без описания</span>'}</div>
<div class="quiz-ai-job-meta">${aiHistoryMeta(job)}</div>
${job.error ? `<div class="quiz-ai-job-error">${esc(job.error)}</div>` : ''}
${link}
</div>`;
}
function renderAiHistory() {
const list = document.getElementById('quizAiHistoryList');
if (!list) return;
if (aiHistory.loading && !aiHistory.items.length) {
list.innerHTML = '<div class="quiz-ai-history-empty">Загрузка…</div>';
} else if (aiHistory.error && !aiHistory.items.length) {
list.innerHTML = `<div class="quiz-ai-history-empty">${esc(aiHistory.error)}</div>`;
} else if (!aiHistory.items.length) {
list.innerHTML = '<div class="quiz-ai-history-empty">Заданий пока нет. Сгенерируйте тест — оно появится здесь.</div>';
} else {
list.innerHTML = aiHistory.items.map(aiHistoryRow).join('');
}
const from = aiHistory.total ? aiHistory.offset + 1 : 0;
const to = Math.min(aiHistory.offset + AI_HISTORY_LIMIT, aiHistory.total);
document.getElementById('quizAiHistoryPage').textContent = `${from}–${to} из ${aiHistory.total}`;
document.getElementById('quizAiHistoryPrev').disabled = aiHistory.loading || aiHistory.offset <= 0;
document.getElementById('quizAiHistoryNext').disabled = aiHistory.loading || aiHistory.offset + AI_HISTORY_LIMIT >= aiHistory.total;
renderIcons();
}
async function fetchAiHistory() {
const res = await fetch(API + '/api/quizzes/ai-jobs?limit=' + AI_HISTORY_LIMIT + '&offset=' + aiHistory.offset, { headers: hdr() });
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Не удалось загрузить историю');
return {
items: Array.isArray(data.items) ? data.items : [],
total: Number(data.total) || 0,
};
}
async function loadAiHistory() {
aiHistory.loading = true;
renderAiHistory();
try {
const data = await fetchAiHistory();
aiHistory.items = data.items;
aiHistory.total = data.total;
aiHistory.error = '';
} catch (e) {
aiHistory.error = e.message;
} finally {
aiHistory.loading = false;
renderAiHistory();
}
}
async function refreshAiHistory() {
if (!document.getElementById('quizAiHistoryModal').classList.contains('open')) return;
if (aiHistory.loading) return;
try {
const data = await fetchAiHistory();
const sameSet = data.items.length === aiHistory.items.length
&& data.items.every((job, i) => aiHistory.items[i] && aiHistory.items[i].id === job.id);
const totalChanged = data.total !== aiHistory.total;
const finalChanged = data.items.some(job => {
const prev = aiHistory.items.find(item => item.id === job.id);
return prev && prev.status !== job.status && job.status !== 'pending' && job.status !== 'processing';
});
aiHistory.items = data.items;
aiHistory.total = data.total;
aiHistory.error = '';
if (!sameSet || totalChanged || finalChanged) {
renderAiHistory();
return;
}
data.items.forEach(job => {
const badge = document.querySelector('[data-job-status="' + job.id + '"]');
if (!badge) return;
badge.textContent = aiStatusLabel(job.status);
badge.className = 'quiz-ai-job-status ' + job.status;
});
} catch (e) {}
}
function openQuizAiHistory() {
aiHistory.offset = 0;
aiHistory.items = [];
aiHistory.total = 0;
aiHistory.error = '';
document.getElementById('quizAiHistoryModal').classList.add('open');
renderIcons();
loadAiHistory();
if (aiHistory.poll) clearInterval(aiHistory.poll);
aiHistory.poll = setInterval(refreshAiHistory, 3000);
}
function closeQuizAiHistory() {
document.getElementById('quizAiHistoryModal').classList.remove('open');
if (aiHistory.poll) {
clearInterval(aiHistory.poll);
aiHistory.poll = null;
}
}
function aiHistoryPage(delta) {
const next = aiHistory.offset + delta * AI_HISTORY_LIMIT;
if (next < 0 || next >= aiHistory.total) return;
aiHistory.offset = next;
document.getElementById('quizAiHistoryList').scrollTop = 0;
loadAiHistory();
}
function aiNativeOption(label) {
const opt = document.createElement('option');
opt.value = 'native';
opt.textContent = label;
return opt;
}
function aiOptgroup(label, list) {
const group = document.createElement('optgroup');
group.label = label;
list.forEach(m => {
const opt = document.createElement('option');
opt.value = m.id;
opt.textContent = [m.name, m.model].filter(Boolean).join(' — ');
group.appendChild(opt);
});
return group;
}
async function loadAiModels() {
const [mineRes, optRes] = await Promise.allSettled([
fetch(API + '/api/user-settings', { headers: hdr() }),
fetch(API + '/api/ai/profiles/options', { headers: hdr() }),
]);
const result = { native: 'Нативная', active: 'native', profiles: [], personal: [], loaded: 0 };
if (optRes.status === 'fulfilled' && optRes.value.ok) {
const d = await optRes.value.json().catch(() => ({}));
result.loaded++;
if (d.native && d.native.model) result.native = 'Нативная — ' + d.native.model;
result.active = d.active || 'native';
if (Array.isArray(d.profiles)) result.profiles = d.profiles;
}
if (mineRes.status === 'fulfilled' && mineRes.value.ok) {
const d = await mineRes.value.json().catch(() => ({}));
let arr = [];
try {
arr = JSON.parse((d.settings && d.settings.feedback_models) || '[]');
} catch (e) {
arr = [];
}
result.loaded++;
if (Array.isArray(arr)) result.personal = arr.filter(m => m && m.id);
}
return result;
}
function fillAiModels(models) {
const sel = document.getElementById('quizAiModel');
const keep = sel.value;
sel.innerHTML = '';
sel.appendChild(aiNativeOption(models.native));
if (models.personal.length) sel.appendChild(aiOptgroup('Мои модели', models.personal));
if (models.profiles.length) sel.appendChild(aiOptgroup('Системные', models.profiles));
const wanted = keep || models.active;
sel.value = [...sel.options].some(o => o.value === wanted) ? wanted : 'native';
}
async function openQuizAi() {
if (!aiEnabled) {
showToast('ИИ-генерация отключена в настройках', true);
return;
}
document.getElementById('quizAiPrompt').value = '';
document.getElementById('quizAiPromptCount').textContent = '0';
document.getElementById('quizAiCount').value = '10';
document.getElementById('quizAiKind').value = 'test';
document.getElementById('quizAiDifficulty').value = 'medium';
const sel = document.getElementById('quizAiModel');
sel.innerHTML = '<option value="native">Нативная</option>';
if (aiModelsCache) fillAiModels(aiModelsCache);
syncAiResult(aiJob && aiJob.status === 'done' ? aiJob : null);
if (!aiBusy) setAiStatus('Готово к генерации');
document.getElementById('quizAiModal').classList.add('open');
renderIcons();
document.getElementById('quizAiPrompt').focus();
try {
const models = await loadAiModels();
aiModelsCache = models;
fillAiModels(models);
if (!models.loaded && !aiBusy) setAiStatus('Модели не загрузились — доступна нативная', 'error');
else if (!models.personal.length && !models.profiles.length && !aiBusy) {
setAiStatus('Доступна только нативная модель: добавьте свою в профиле, вкладка «ИИ и модели»');
}
} catch (e) {
if (!aiBusy) setAiStatus('Не удалось загрузить список моделей — доступна нативная', 'error');
}
refreshAiJob();
}
function closeQuizAi() {
document.getElementById('quizAiModal').classList.remove('open');
}
async function runQuizAi() {
if (aiBusy) return;
const promptText = document.getElementById('quizAiPrompt').value.trim();
if (!promptText) {
showToast('Опишите тему теста');
document.getElementById('quizAiPrompt').focus();
return;
}
const count = Math.max(1, Math.min(40, parseInt(document.getElementById('quizAiCount').value, 10) || 10));
document.getElementById('quizAiCount').value = String(count);
setAiBusy(true);
syncAiResult(null);
setAiStatus('Отправляем задание в очередь…', 'busy');
try {
const res = await fetch(API + '/api/quizzes/ai-generate', {
method: 'POST',
headers: hdrJson(),
body: JSON.stringify({
prompt: promptText,
kind: document.getElementById('quizAiKind').value === 'survey' ? 'survey' : 'test',
count,
difficulty: document.getElementById('quizAiDifficulty').value,
profile: document.getElementById('quizAiModel').value || 'native',
}),
});
const data = await res.json().catch(() => ({}));
if (res.status === 409 && data.job) {
applyAiJob(data.job);
startAiPoll();
showToast('Генерация уже идёт');
return;
}
if (!res.ok) throw new Error(data.error || 'Не удалось запустить генерацию');
applyAiJob(data.job);
startAiPoll();
showToast('Генерация запущена');
} catch (e) {
setAiBusy(false);
setAiStatus('Ошибка: ' + e.message, 'error');
showToast(e.message, true);
}
}
async function removeQuiz(id) {
if (!confirm('Удалить тест? Он попадёт в корзину и будет удалён окончательно по истечении срока.')) return;
try {
@@ -177,12 +609,43 @@
function bind() {
document.getElementById('quizNewTestBtn').addEventListener('click', () => createQuiz('test'));
document.getElementById('quizNewSurveyBtn').addEventListener('click', () => createQuiz('survey'));
document.getElementById('quizAiBtn').addEventListener('click', openQuizAi);
document.getElementById('quizAiCancel').addEventListener('click', closeQuizAi);
document.getElementById('quizAiRun').addEventListener('click', runQuizAi);
document.getElementById('quizAiModal').addEventListener('click', e => {
if (e.target.id === 'quizAiModal') closeQuizAi();
});
document.getElementById('quizAiPrompt').addEventListener('input', e => {
document.getElementById('quizAiPromptCount').textContent = String(e.target.value.length);
});
document.getElementById('quizAiHistoryBtn').addEventListener('click', openQuizAiHistory);
document.getElementById('quizAiHistoryClose').addEventListener('click', closeQuizAiHistory);
document.getElementById('quizAiHistoryPrev').addEventListener('click', () => aiHistoryPage(-1));
document.getElementById('quizAiHistoryNext').addEventListener('click', () => aiHistoryPage(1));
document.getElementById('quizAiHistoryRefresh').addEventListener('click', loadAiHistory);
document.getElementById('quizAiHistoryModal').addEventListener('click', e => {
if (e.target.id === 'quizAiHistoryModal') closeQuizAiHistory();
});
document.addEventListener('keydown', e => {
if (e.key !== 'Escape') return;
if (document.getElementById('quizAiHistoryModal').classList.contains('open')) {
closeQuizAiHistory();
return;
}
if (document.getElementById('quizAiModal').classList.contains('open')) closeQuizAi();
});
document.getElementById('quizSearch').addEventListener('input', () => {
clearTimeout(bind.t);
bind.t = setTimeout(load, 300);
});
document.getElementById('quizKindFilter').addEventListener('change', load);
document.getElementById('quizMineOnly').addEventListener('change', load);
document.getElementById('quizMineOnly').addEventListener('change', () => {
if (!loaded) {
load();
return;
}
render();
});
document.getElementById('quizDeletedOnly').addEventListener('change', load);
document.addEventListener('click', e => {
@@ -192,6 +655,17 @@
if (restore) { e.preventDefault(); restoreQuiz(restore.dataset.restore); return; }
const perm = e.target.closest('[data-perm]');
if (perm) { e.preventDefault(); purgeQuiz(perm.dataset.perm); return; }
const copyLink = e.target.closest('[data-copy-link]');
if (copyLink) {
e.preventDefault();
const url = location.origin + '/quiz-public.html?id=' + copyLink.dataset.copyLink;
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(url).then(() => showToast('Ссылка скопирована'), () => showToast('Не удалось скопировать ссылку', true));
} else {
showToast(url);
}
return;
}
const stats = e.target.closest('[data-stats]');
if (stats) { e.preventDefault(); location.href = 'quiz.html?id=' + stats.dataset.stats + '&tab=stats'; return; }
if (e.target.closest('a')) return;
@@ -201,21 +675,58 @@
}
function connectLive() {
let t = null;
if (liveSource) return;
const es = new EventSource(API + '/api/events?token=' + encodeURIComponent(token || ''));
liveSource = es;
es.addEventListener('quizzes_changed', () => {
clearTimeout(t);
t = setTimeout(load, 400);
clearTimeout(liveDebounce);
liveDebounce = setTimeout(load, 400);
});
es.addEventListener('quiz_ai_status', e => {
let payload = null;
try { payload = JSON.parse(e.data); } catch (err) { return; }
const job = payload && payload.job ? payload.job : null;
if (!job) return;
if (currentUser && Number(job.user_id) !== Number(currentUser.id)) return;
applyAiJob(job);
if (job.status === 'pending' || job.status === 'processing') startAiPoll();
if (document.getElementById('quizAiHistoryModal').classList.contains('open')) refreshAiHistory();
});
}
function disconnectLive() {
if (liveDebounce) {
clearTimeout(liveDebounce);
liveDebounce = null;
}
if (!liveSource) return;
liveSource.close();
liveSource = null;
}
function bindVisibility() {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
disconnectLive();
return;
}
connectLive();
load();
});
}
async function init() {
if (!(await checkAuth())) return;
buildSidebar(document.body.dataset.page);
const scalesBtn = document.getElementById('quizScalesBtn');
if (scalesBtn) scalesBtn.hidden = !(currentUser && currentUser.role === 'admin');
bind();
bindVisibility();
renderIcons();
await load();
connectLive();
await refreshAiJob();
if (aiJob && (aiJob.status === 'pending' || aiJob.status === 'processing')) startAiPoll();
}
init();