Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ==UserScript==
- // @name EyeWire Mystic Open+ Registry Scanner
- // @namespace eyewire-mystic-open-plus
- // @version 1.3.0
- // @description Scans marked EyeWire registry cells for genuine unresolved Scout's Log entries and persistently remembers progress/results.
- // @match https://eyewire.org/*
- // @run-at document-start
- // @grant GM_xmlhttpRequest
- // @grant GM_getValue
- // @grant GM_setValue
- // @grant GM_deleteValue
- // @grant GM_listValues
- // @connect script.google.com
- // @connect script.googleusercontent.com
- // @connect eyewire.org
- // @connect scoutslog2.eyewire.org
- // ==/UserScript==
- (function () {
- 'use strict';
- const REGISTRY_EXEC_URL =
- 'https://script.google.com/macros/s/AKfycbz5W8WNyqhjn9D3IHE32FGEBM1SjfY4IONl5C_yHvBSi7kAmheHOFhVcoqfe5BiFvIt/exec';
- const TAB_ID = 'mystic-open-plus-tab';
- const PANEL_ID = 'mystic-open-plus-panel';
- const STYLE_ID = 'mystic-open-plus-style';
- // Old page-owned checkpoint, kept for migration from your existing script.
- const OLD_PAGE_STATE_KEY = 'mystic-open-plus-registry-state-v110';
- // Tampermonkey-owned durable storage. These survive F5, Ctrl+F5 and normal browser restarts.
- const STATE_KEY = 'mystic-open-plus-persistent-state-v130';
- const RESULT_PREFIX = 'mystic-open-plus-persistent-result-v130:';
- // Existing IndexedDB cache from the previous script is still read/migrated.
- const DB_NAME = 'MysticOpenPlusDB';
- const DB_VERSION = 1;
- const RESULT_STORE = 'results';
- const CELL_BATCH_SIZE = 4;
- const ACTION_CONCURRENCY = 5;
- const BETWEEN_ACTION_DELAY_MS = 35;
- const BETWEEN_BATCH_DELAY_MS = 100;
- const RESOLVED_STATUSES = new Set(['good', 'resolved', 'closed']);
- let registryCells = [];
- let groupedResults = [];
- let running = false;
- let pauseRequested = false;
- let lastRenderTime = 0;
- let database = null;
- let resultsLoaded = false;
- /******************************************************************
- * PERSISTENT STATE
- ******************************************************************/
- function defaultState() {
- return {
- registryHash: '',
- registryCount: 0,
- nextCellIndex: 0,
- cellsCompleted: 0,
- cubesChecked: 0,
- errors: 0,
- startedAt: '',
- updatedAt: '',
- completed: false,
- scannedCellIds: []
- };
- }
- function normalizeState(raw) {
- const state = { ...defaultState(), ...(raw || {}) };
- state.registryHash = String(state.registryHash || '');
- state.registryCount = Number(state.registryCount || 0);
- state.nextCellIndex = Number(state.nextCellIndex || 0);
- state.cellsCompleted = Number(state.cellsCompleted || 0);
- state.cubesChecked = Number(state.cubesChecked || 0);
- state.errors = Number(state.errors || 0);
- state.startedAt = String(state.startedAt || '');
- state.updatedAt = String(state.updatedAt || '');
- state.completed = Boolean(state.completed);
- state.scannedCellIds = Array.from(
- new Set(
- (Array.isArray(state.scannedCellIds) ? state.scannedCellIds : [])
- .map(v => String(v || '').trim())
- .filter(Boolean)
- )
- );
- return state;
- }
- function loadState() {
- try {
- const saved = GM_getValue(STATE_KEY, null);
- if (saved) return normalizeState(typeof saved === 'string' ? JSON.parse(saved) : saved);
- } catch (error) {
- console.warn('[Mystic Open+] Could not read Tampermonkey checkpoint:', error);
- }
- // Migrate the existing v1.2.x page checkpoint if present.
- for (const storage of [localStorage, sessionStorage]) {
- try {
- const raw = storage.getItem(OLD_PAGE_STATE_KEY);
- if (!raw) continue;
- const migrated = normalizeState(JSON.parse(raw));
- saveState(migrated);
- return migrated;
- } catch (error) {
- console.warn('[Mystic Open+] Could not migrate old checkpoint:', error);
- }
- }
- return defaultState();
- }
- function saveState(state) {
- const clean = normalizeState({
- ...state,
- updatedAt: new Date().toISOString()
- });
- try {
- GM_setValue(STATE_KEY, clean);
- } catch (error) {
- console.warn('[Mystic Open+] Could not persist Tampermonkey checkpoint:', error);
- }
- // Keep a compatibility copy. The script no longer depends on this copy.
- try {
- localStorage.setItem(OLD_PAGE_STATE_KEY, JSON.stringify(clean));
- } catch (_) {}
- Object.assign(state, clean);
- }
- function clearPersistentState() {
- try { GM_deleteValue(STATE_KEY); } catch (_) {}
- try { localStorage.removeItem(OLD_PAGE_STATE_KEY); } catch (_) {}
- try { sessionStorage.removeItem(OLD_PAGE_STATE_KEY); } catch (_) {}
- }
- function resultKey(taskId) {
- return RESULT_PREFIX + String(taskId);
- }
- function loadGMResults() {
- const results = [];
- try {
- for (const key of GM_listValues()) {
- if (!String(key).startsWith(RESULT_PREFIX)) continue;
- try {
- const entry = GM_getValue(key, null);
- if (entry && entry.taskId) results.push(entry);
- } catch (error) {
- console.warn('[Mystic Open+] Could not read saved entry:', key, error);
- }
- }
- } catch (error) {
- console.warn('[Mystic Open+] Could not list saved entries:', error);
- }
- return results;
- }
- function saveGMResult(entry) {
- try {
- GM_setValue(resultKey(entry.taskId), entry);
- } catch (error) {
- console.warn('[Mystic Open+] Could not persist entry:', entry && entry.taskId, error);
- }
- }
- function deleteGMResult(taskId) {
- try { GM_deleteValue(resultKey(taskId)); } catch (_) {}
- }
- function clearGMResults() {
- try {
- for (const key of GM_listValues()) {
- if (String(key).startsWith(RESULT_PREFIX)) GM_deleteValue(key);
- }
- } catch (error) {
- console.warn('[Mystic Open+] Could not clear persistent entries:', error);
- }
- }
- /******************************************************************
- * INDEXEDDB CACHE + MIGRATION
- ******************************************************************/
- function openDatabase() {
- if (database) return Promise.resolve(database);
- return new Promise((resolve, reject) => {
- const request = indexedDB.open(DB_NAME, DB_VERSION);
- request.onupgradeneeded = event => {
- const db = event.target.result;
- if (!db.objectStoreNames.contains(RESULT_STORE)) {
- const store = db.createObjectStore(RESULT_STORE, { keyPath: 'taskId' });
- store.createIndex('cellId', 'cellId', { unique: false });
- }
- };
- request.onsuccess = event => {
- database = event.target.result;
- resolve(database);
- };
- request.onerror = () => reject(request.error);
- });
- }
- async function readIndexedResults() {
- try {
- await openDatabase();
- return await new Promise((resolve, reject) => {
- const tx = database.transaction(RESULT_STORE, 'readonly');
- const request = tx.objectStore(RESULT_STORE).getAll();
- request.onsuccess = () => resolve(request.result || []);
- request.onerror = () => reject(request.error);
- });
- } catch (error) {
- console.warn('[Mystic Open+] IndexedDB read unavailable:', error);
- return [];
- }
- }
- async function putIndexedResult(entry) {
- try {
- await openDatabase();
- await new Promise((resolve, reject) => {
- const tx = database.transaction(RESULT_STORE, 'readwrite');
- tx.objectStore(RESULT_STORE).put(entry);
- tx.oncomplete = resolve;
- tx.onerror = () => reject(tx.error);
- });
- } catch (error) {
- console.warn('[Mystic Open+] IndexedDB write unavailable:', error);
- }
- }
- async function deleteIndexedResult(taskId) {
- try {
- await openDatabase();
- await new Promise((resolve, reject) => {
- const tx = database.transaction(RESULT_STORE, 'readwrite');
- tx.objectStore(RESULT_STORE).delete(String(taskId));
- tx.oncomplete = resolve;
- tx.onerror = () => reject(tx.error);
- });
- } catch (error) {
- console.warn('[Mystic Open+] IndexedDB delete unavailable:', error);
- }
- }
- async function clearIndexedResults() {
- try {
- await openDatabase();
- await new Promise((resolve, reject) => {
- const tx = database.transaction(RESULT_STORE, 'readwrite');
- tx.objectStore(RESULT_STORE).clear();
- tx.oncomplete = resolve;
- tx.onerror = () => reject(tx.error);
- });
- } catch (error) {
- console.warn('[Mystic Open+] IndexedDB clear unavailable:', error);
- }
- }
- async function loadSavedResults() {
- const merged = new Map();
- // Read the old/current IndexedDB so upgrading does not lose existing discoveries.
- for (const entry of await readIndexedResults()) {
- if (entry && entry.taskId) merged.set(String(entry.taskId), entry);
- }
- // Tampermonkey storage is authoritative when both copies exist.
- for (const entry of loadGMResults()) {
- if (entry && entry.taskId) merged.set(String(entry.taskId), entry);
- }
- groupedResults = [];
- for (const entry of merged.values()) addResultToMemory(entry);
- // Self-heal both storage layers.
- for (const entry of merged.values()) {
- saveGMResult(entry);
- await putIndexedResult(entry);
- }
- resultsLoaded = true;
- sortGroupedResults();
- renderRows();
- }
- async function saveResult(entry) {
- saveGMResult(entry); // durable copy first
- await putIndexedResult(entry); // page-local cache second
- }
- async function deleteResult(taskId) {
- deleteGMResult(taskId);
- await deleteIndexedResult(taskId);
- }
- async function clearAllResults() {
- clearGMResults();
- await clearIndexedResults();
- }
- /******************************************************************
- * BOOT / TAB INSTALLATION
- ******************************************************************/
- async function start() {
- ensureStyles();
- ensureInstalled();
- installNativeNavigationWatcher();
- await loadSavedResults();
- renderRows();
- updateProgress(loadState());
- // Important: childList only. Watching style/class caused the previous freeze.
- new MutationObserver(ensureInstalled).observe(document.documentElement, {
- subtree: true,
- childList: true
- });
- setInterval(ensureInstalled, 750);
- console.log('[Mystic Open+] v1.3.0 started with durable Tampermonkey persistence.');
- }
- function ensureInstalled() {
- if (!document.body) return;
- ensureStyles();
- const context = findMysticContext();
- if (!context) {
- removeTab();
- hidePanel();
- return;
- }
- let tab = document.getElementById(TAB_ID);
- if (!tab) tab = createTab();
- if (
- tab.parentElement !== context.openLogsLi.parentElement ||
- tab.previousElementSibling !== context.openLogsLi
- ) {
- context.openLogsLi.parentElement.insertBefore(tab, context.openLogsLi.nextSibling);
- }
- ensurePanel(context.panel);
- }
- function findMysticContext() {
- const panels = Array.from(
- document.querySelectorAll('#slPanel, [id*="slPanel"], .slPanel')
- );
- for (const panel of panels) {
- if (!isVisible(panel)) continue;
- const text = normalizeText(panel.textContent);
- if (!text.includes("Scouts' Log") || !text.includes('Mystic:')) continue;
- for (const list of panel.querySelectorAll('ul.tabs')) {
- const openLogsLi = Array.from(list.children).find(li => {
- const t = normalizeText(li.textContent);
- return t === 'Open Logs' || /^Open Logs\s+\d+$/.test(t);
- });
- if (openLogsLi) return { panel, openLogsLi };
- }
- }
- return null;
- }
- function createTab() {
- const li = document.createElement('li');
- li.id = TAB_ID;
- const link = document.createElement('a');
- link.href = '#';
- link.textContent = 'Mystic Open+';
- link.title = 'Scan registry cells for unresolved Mystic Scout’s Log entries';
- link.addEventListener('mousedown', event => event.stopPropagation());
- link.addEventListener('click', event => {
- event.preventDefault();
- event.stopPropagation();
- openPanel();
- });
- li.appendChild(link);
- return li;
- }
- function removeTab() {
- document.getElementById(TAB_ID)?.remove();
- }
- /******************************************************************
- * NATIVE EYEWIRE JUMP
- ******************************************************************/
- function nativeEyeWireJump(taskId) {
- const task = String(taskId || '').trim();
- if (!task) return;
- clearError();
- const injected = document.createElement('script');
- injected.textContent = `
- (() => {
- const task = ${JSON.stringify(task)};
- try {
- if (!window.tomni || typeof window.tomni.jumpToTaskID !== 'function') {
- console.error('[Mystic Open+] window.tomni.jumpToTaskID is unavailable');
- return;
- }
- const scouts = window.scoutsLog && window.scoutsLog.S
- ? window.scoutsLog.S
- : null;
- const slVisible = window.jQuery
- ? window.jQuery('#slPanel').is(':visible')
- : false;
- if (slVisible && scouts && typeof scouts.hide === 'function') {
- scouts.hide();
- }
- if (
- window.tomni.gameMode &&
- typeof Attention !== 'undefined' &&
- Attention.Confirmation
- ) {
- const confirmation = new Attention.Confirmation({
- situation: 'information calm',
- title: typeof _ === 'function'
- ? _('Jump to Task #{0}?', task)
- : 'Jump to Task #' + task + '?',
- message: typeof _ === 'function'
- ? _('You will lose your progress on this cube.')
- : 'You will lose your progress on this cube.',
- ok: {
- label: typeof _ === 'function' ? _('Jump to Task') : 'Jump to Task',
- klass: 'flat'
- },
- cancel: {
- label: typeof _ === 'function' ? _('Stay Here') : 'Stay Here',
- klass: 'flat'
- }
- });
- confirmation
- .on('ok', () => window.tomni.jumpToTaskID(task))
- .on('cancel', () => {
- if (slVisible && scouts && typeof scouts.show === 'function') scouts.show();
- })
- .show();
- } else {
- window.tomni.jumpToTaskID(task);
- }
- } catch (error) {
- console.error('[Mystic Open+] jump failed:', error);
- }
- })();
- `;
- (document.head || document.documentElement).appendChild(injected);
- injected.remove();
- }
- /******************************************************************
- * REGISTRY / EYEWIRE HTTP
- ******************************************************************/
- function fetchRegistry() {
- return new Promise((resolve, reject) => {
- GM_xmlhttpRequest({
- method: 'GET',
- url: REGISTRY_EXEC_URL,
- timeout: 60000,
- onload: response => {
- try {
- const data = JSON.parse(response.responseText);
- if (!data.ok) throw new Error(data.error || 'Registry returned ok:false');
- const cells = Array.isArray(data.cells) ? data.cells : [];
- resolve({
- cells,
- count: Number(data.count) || cells.length,
- generatedAt: String(data.generatedAt || '')
- });
- } catch (error) {
- reject(error);
- }
- },
- onerror: () => reject(new Error('Could not reach Apps Script registry.')),
- ontimeout: () => reject(new Error('Apps Script registry request timed out.'))
- });
- });
- }
- async function requestJson(url) {
- const response = await fetch(url, {
- credentials: 'include',
- cache: 'no-store',
- headers: { Accept: 'application/json, text/plain, */*' }
- });
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${url}`);
- return response.json();
- }
- function cellTasksUrl(cellId) {
- return 'https://eyewire.org/1.0/cell/' + encodeURIComponent(cellId) + '/tasks';
- }
- function taskActionsUrl(taskId) {
- return 'https://scoutslog2.eyewire.org/1.1/task/' +
- encodeURIComponent(taskId) + '/actions';
- }
- function hashRegistry(cells) {
- let hash = 2166136261;
- for (const cell of cells) {
- const id = String(cell.id || '');
- for (let i = 0; i < id.length; i++) {
- hash ^= id.charCodeAt(i);
- hash = Math.imul(hash, 16777619);
- }
- hash ^= 44;
- hash = Math.imul(hash, 16777619);
- }
- return (hash >>> 0).toString(16);
- }
- /******************************************************************
- * SCANNING / DURABLE RESUME
- ******************************************************************/
- async function startResumeScan() {
- if (running) return;
- running = true;
- pauseRequested = false;
- updateButtons();
- clearError();
- try {
- if (!resultsLoaded) await loadSavedResults();
- setStatus('Loading Zfish cell registry…');
- const registry = await fetchRegistry();
- registryCells = registry.cells;
- if (!registryCells.length) {
- throw new Error('The registry returned zero marked cells.');
- }
- let state = loadState();
- // Migration from old numeric-only progress: convert the already-passed
- // registry rows into exact remembered cell IDs.
- if (!state.scannedCellIds.length && state.nextCellIndex > 0) {
- state.scannedCellIds = registryCells
- .slice(0, Math.min(state.nextCellIndex, registryCells.length))
- .map(cell => String(cell.id || '').trim())
- .filter(Boolean);
- }
- const registryIds = registryCells
- .map(cell => String(cell.id || '').trim())
- .filter(Boolean);
- const registryIdSet = new Set(registryIds);
- // Keep only remembered IDs that are still in the marked registry.
- state.scannedCellIds = Array.from(
- new Set(
- state.scannedCellIds
- .map(id => String(id || '').trim())
- .filter(id => id && registryIdSet.has(id))
- )
- );
- const scanned = new Set(state.scannedCellIds);
- const currentHash = hashRegistry(registryCells);
- state.registryHash = currentHash;
- state.registryCount = registryCells.length;
- if (!state.startedAt) state.startedAt = new Date().toISOString();
- const firstUnscanned = registryCells.findIndex(
- cell => !scanned.has(String(cell.id || '').trim())
- );
- state.nextCellIndex = firstUnscanned < 0 ? registryCells.length : firstUnscanned;
- state.cellsCompleted = scanned.size;
- state.completed = firstUnscanned < 0;
- saveState(state);
- if (state.completed) {
- setStatus(
- `All ${registryCells.length.toLocaleString()} marked cells are already remembered as scanned.`
- );
- updateProgress(state);
- return;
- }
- setStatus(
- `Resuming with ${scanned.size.toLocaleString()} remembered scanned cells — ` +
- `next unscanned row ${state.nextCellIndex + 1} of ${registryCells.length.toLocaleString()}…`
- );
- await runRegistryBatches(state);
- } catch (error) {
- console.error('[Mystic Open+]', error);
- showError(error.message);
- } finally {
- running = false;
- updateButtons();
- }
- }
- async function runRegistryBatches(state) {
- const scanned = new Set(
- (state.scannedCellIds || []).map(id => String(id || '').trim()).filter(Boolean)
- );
- let cursor = Math.max(0, Number(state.nextCellIndex || 0));
- while (cursor < registryCells.length) {
- if (pauseRequested) break;
- const batch = [];
- while (cursor < registryCells.length && batch.length < CELL_BATCH_SIZE) {
- const cell = registryCells[cursor++];
- const id = String(cell && cell.id || '').trim();
- if (!id || scanned.has(id)) continue;
- batch.push(cell);
- }
- if (!batch.length) break;
- const results = await Promise.allSettled(
- batch.map(cell => scanCell(cell, state))
- );
- for (let i = 0; i < results.length; i++) {
- const id = String(batch[i] && batch[i].id || '').trim();
- if (results[i].status === 'rejected') {
- state.errors++;
- console.warn('[Mystic Open+] Cell failed:', id, results[i].reason);
- }
- // Matches previous behavior: once a registry cell has been processed,
- // remember it so a reload/browser restart does not scan it again.
- if (id) scanned.add(id);
- }
- state.scannedCellIds = Array.from(scanned);
- state.cellsCompleted = scanned.size;
- let next = registryCells.length;
- for (let i = cursor; i < registryCells.length; i++) {
- const id = String(registryCells[i] && registryCells[i].id || '').trim();
- if (id && !scanned.has(id)) {
- next = i;
- break;
- }
- }
- state.nextCellIndex = next;
- saveState(state);
- updateProgress(state);
- scheduleRender();
- if (pauseRequested) break;
- cursor = next;
- await sleep(BETWEEN_BATCH_DELAY_MS);
- }
- let remaining = -1;
- for (let i = 0; i < registryCells.length; i++) {
- const id = String(registryCells[i] && registryCells[i].id || '').trim();
- if (id && !scanned.has(id)) {
- remaining = i;
- break;
- }
- }
- state.scannedCellIds = Array.from(scanned);
- state.cellsCompleted = scanned.size;
- if (!pauseRequested && remaining < 0) {
- state.completed = true;
- state.nextCellIndex = registryCells.length;
- saveState(state);
- setStatus(
- `Finished — remembered ${scanned.size.toLocaleString()} scanned cells; ` +
- `${countEntries().toLocaleString()} unresolved entries across ` +
- `${groupedResults.length.toLocaleString()} cells.`
- );
- } else {
- state.completed = false;
- if (remaining >= 0) state.nextCellIndex = remaining;
- saveState(state);
- setStatus(
- `Paused — ${scanned.size.toLocaleString()} scanned cells safely remembered; ` +
- `next unscanned row ${Math.min(state.nextCellIndex + 1, registryCells.length).toLocaleString()} / ` +
- `${registryCells.length.toLocaleString()}.`
- );
- }
- updateProgress(state);
- }
- async function scanCell(registryCell, state) {
- const cellId = String(registryCell.id || '').trim();
- if (!cellId) return;
- const data = await requestJson(cellTasksUrl(cellId));
- const tasks = Array.isArray(data.tasks) ? data.tasks : [];
- let nextTaskIndex = 0;
- async function worker() {
- while (true) {
- if (pauseRequested) return;
- const index = nextTaskIndex++;
- if (index >= tasks.length) return;
- const task = tasks[index];
- if (!task || task.id === undefined || task.id === null) continue;
- const taskId = String(task.id);
- try {
- const log = await requestJson(taskActionsUrl(taskId));
- state.cubesChecked++;
- if (isCurrentlyUnresolved(log)) {
- const entry = makeResultEntry(log, registryCell);
- if (entry) {
- addResultToMemory(entry);
- await saveResult(entry);
- }
- } else {
- removeResultFromMemory(taskId);
- await deleteResult(taskId);
- }
- } catch (error) {
- state.errors++;
- console.warn('[Mystic Open+] Task failed:', taskId, error);
- }
- await sleep(BETWEEN_ACTION_DELAY_MS);
- }
- }
- await Promise.all(
- Array.from(
- { length: ACTION_CONCURRENCY },
- () => worker()
- )
- );
- }
- function isCurrentlyUnresolved(log) {
- if (!log) return false;
- if (!Array.isArray(log.actions) || !log.actions.length) return false;
- const cell = String(log.cell || '').trim();
- if (!cell || cell === '0') return false;
- const status = normalizeStatus(log.status);
- if (!status || status === 'n/a') return false;
- if (RESOLVED_STATUSES.has(status)) return false;
- return true;
- }
- function makeResultEntry(log, registryCell) {
- const taskId = String(log.task || '').trim();
- const cellId = String(log.cell || registryCell.id || '').trim();
- if (!taskId || !cellId) return null;
- return {
- taskId,
- cellId,
- cellName: String(
- log.cellName ||
- log.cellNameKO ||
- registryCell.name ||
- ''
- ).trim(),
- status: String(log.status || ''),
- statusText: String(log.statusText || ''),
- issue: String(log.issue || ''),
- lastUser: String(log.lastUser || ''),
- lastUpdated: String(log.lastUpdated || '')
- };
- }
- /******************************************************************
- * RESULTS / GROUPING
- ******************************************************************/
- function addResultToMemory(entry) {
- let group = groupedResults.find(item => item.cellId === entry.cellId);
- if (!group) {
- group = {
- cellId: entry.cellId,
- cellName: entry.cellName,
- entries: []
- };
- groupedResults.push(group);
- }
- if (entry.cellName) group.cellName = entry.cellName;
- const existing = group.entries.find(item => item.taskId === entry.taskId);
- if (existing) Object.assign(existing, entry);
- else group.entries.push(entry);
- group.entries.sort((a, b) => parseDate(b.lastUpdated) - parseDate(a.lastUpdated));
- }
- function removeResultFromMemory(taskId) {
- const id = String(taskId);
- for (let i = groupedResults.length - 1; i >= 0; i--) {
- const group = groupedResults[i];
- group.entries = group.entries.filter(entry => entry.taskId !== id);
- if (!group.entries.length) groupedResults.splice(i, 1);
- }
- }
- function sortGroupedResults() {
- for (const group of groupedResults) {
- group.entries.sort((a, b) => parseDate(b.lastUpdated) - parseDate(a.lastUpdated));
- }
- groupedResults.sort((a, b) => {
- const aDate = a.entries[0] ? parseDate(a.entries[0].lastUpdated) : 0;
- const bDate = b.entries[0] ? parseDate(b.entries[0].lastUpdated) : 0;
- return bDate - aDate;
- });
- }
- function countEntries() {
- return groupedResults.reduce((total, group) => total + group.entries.length, 0);
- }
- /******************************************************************
- * RESET / FULL RESCAN
- ******************************************************************/
- async function resetProgress() {
- if (running) return;
- if (!confirm('Reset Mystic Open+ progress and all cached results?')) return;
- clearPersistentState();
- await clearAllResults();
- groupedResults = [];
- registryCells = [];
- resultsLoaded = true;
- renderRows();
- updateProgress(defaultState());
- setStatus('Progress and all remembered results cleared.');
- }
- async function fullRescan() {
- if (running) return;
- clearPersistentState();
- await clearAllResults();
- groupedResults = [];
- registryCells = [];
- resultsLoaded = true;
- renderRows();
- await startResumeScan();
- }
- /******************************************************************
- * EMBEDDED SCOUT'S LOG PANEL
- ******************************************************************/
- function getScoutLogContainers(panelHint) {
- const slPanel = panelHint || document.querySelector('#slPanel');
- if (!slPanel) return null;
- const slContent =
- slPanel.querySelector('.slPanelContent, #slPanelContent') ||
- document.querySelector('#slPanel .slPanelContent, #slPanelContent');
- if (!slContent) return null;
- return {
- slPanel,
- slContent,
- nativeOptions: slContent.querySelector('.slOptions, #slOptions'),
- nativeMain: slContent.querySelector('#sl-main-table')
- };
- }
- function ensurePanel(panelHint) {
- const containers = getScoutLogContainers(panelHint);
- if (!containers) return null;
- const { slContent } = containers;
- let panel = document.getElementById(PANEL_ID);
- if (panel) {
- if (panel.parentElement !== slContent) slContent.appendChild(panel);
- return panel;
- }
- panel = document.createElement('div');
- panel.id = PANEL_ID;
- panel.style.display = 'none';
- panel.innerHTML = `
- <div class="mop-toolbar">
- <div class="mop-search-wrap">
- <input
- id="mop-search"
- type="text"
- autocomplete="off"
- placeholder="Search cube, cell, issue, status or player…"
- >
- </div>
- <div class="mop-toolbar-buttons">
- <button id="mop-start" type="button">Start / Resume</button>
- <button id="mop-pause" type="button">Pause</button>
- <button id="mop-full-rescan" type="button">Full Rescan</button>
- <button id="mop-reset" type="button" class="danger">Reset progress</button>
- </div>
- </div>
- <div class="mop-status-row">
- <span>
- <strong>Mystic Open+</strong>
- <span id="mop-result-count"></span>
- </span>
- <span id="mop-status">Ready.</span>
- <span id="mop-progress-text"></span>
- </div>
- <div class="mop-progress-track">
- <div id="mop-progress-bar"></div>
- </div>
- <div id="mop-error" class="mop-error" style="display:none"></div>
- <div class="mop-table-wrap">
- <table class="sl-table mop-table">
- <thead>
- <tr>
- <th>Cube</th>
- <th>Cell</th>
- <th>Status</th>
- <th>Issue</th>
- <th>Last User</th>
- <th>Last Updated (UTC)</th>
- </tr>
- </thead>
- <tbody id="mop-table-body"></tbody>
- </table>
- </div>
- `;
- slContent.appendChild(panel);
- panel.querySelector('#mop-start').addEventListener('click', startResumeScan);
- panel.querySelector('#mop-pause').addEventListener('click', () => {
- if (!running) return;
- pauseRequested = true;
- setStatus('Pausing after the current batch finishes…');
- });
- panel.querySelector('#mop-full-rescan').addEventListener('click', fullRescan);
- panel.querySelector('#mop-reset').addEventListener('click', resetProgress);
- panel.querySelector('#mop-search').addEventListener('input', renderRows);
- panel.addEventListener('click', event => {
- const jump = event.target.closest('[data-mop-jump]');
- if (!jump) return;
- event.preventDefault();
- event.stopPropagation();
- nativeEyeWireJump(jump.getAttribute('data-mop-jump'));
- });
- renderRows();
- updateProgress(loadState());
- return panel;
- }
- function openPanel() {
- const context = findMysticContext();
- if (!context) return;
- const panel = ensurePanel(context.panel);
- const containers = getScoutLogContainers(context.panel);
- if (!panel || !containers) return;
- if (containers.nativeMain) {
- containers.nativeMain.style.setProperty('display', 'none', 'important');
- }
- containers.slContent.classList.add('mop-view-active');
- panel.style.setProperty('display', 'flex', 'important');
- const tab = document.getElementById(TAB_ID);
- if (tab) {
- for (const sibling of Array.from(tab.parentElement?.children || [])) {
- sibling.classList.remove('active');
- }
- tab.classList.add('active');
- }
- renderRows();
- updateProgress(loadState());
- }
- function hidePanel() {
- const panel = document.getElementById(PANEL_ID);
- if (panel) panel.style.setProperty('display', 'none', 'important');
- const containers = getScoutLogContainers();
- if (containers) {
- containers.slContent.classList.remove('mop-view-active');
- containers.nativeMain?.style.removeProperty('display');
- }
- document.getElementById(TAB_ID)?.classList.remove('active');
- }
- function installNativeNavigationWatcher() {
- if (document.documentElement.dataset.mopNativeNavigationWatcher === '1') return;
- document.documentElement.dataset.mopNativeNavigationWatcher = '1';
- document.addEventListener('click', event => {
- const panel = document.getElementById(PANEL_ID);
- if (!panel || getComputedStyle(panel).display === 'none') return;
- if (
- event.target.closest(`#${PANEL_ID}`) ||
- event.target.closest(`#${TAB_ID}`)
- ) return;
- const nativeTab = event.target.closest(
- '.slOptions ul.tabs > li, ' +
- '.slOptions .tabs > li, ' +
- '#slOptions ul.tabs > li, ' +
- '#slOptions .tabs > li'
- );
- if (nativeTab) hidePanel();
- }, true);
- }
- /******************************************************************
- * TABLE RENDERING
- ******************************************************************/
- function scheduleRender() {
- const now = Date.now();
- if (now - lastRenderTime < 400) return;
- lastRenderTime = now;
- sortGroupedResults();
- renderRows();
- }
- function renderRows() {
- const panel = document.getElementById(PANEL_ID);
- if (!panel) return;
- sortGroupedResults();
- const tbody = panel.querySelector('#mop-table-body');
- const searchInput = panel.querySelector('#mop-search');
- if (!tbody || !searchInput) return;
- const query = String(searchInput.value || '').trim().toLowerCase();
- tbody.innerHTML = '';
- let visibleCells = 0;
- let visibleEntries = 0;
- for (const group of groupedResults) {
- const matching = group.entries.filter(entry => {
- if (!query) return true;
- return [
- entry.taskId,
- group.cellId,
- group.cellName,
- entry.status,
- entry.statusText,
- entry.issue,
- entry.lastUser,
- entry.lastUpdated
- ].join(' ').toLowerCase().includes(query);
- });
- if (!matching.length) continue;
- visibleCells++;
- visibleEntries += matching.length;
- const row = document.createElement('tr');
- row.innerHTML = `
- <td>
- ${matching.map(entry => `
- <div class="entry-line mop-cube-line">
- <a
- href="#"
- class="mop-cube-link"
- data-mop-jump="${escapeHtml(entry.taskId)}"
- title="Jump to cube ${escapeHtml(entry.taskId)} in EyeWire"
- >${escapeHtml(entry.taskId)}</a>
- <span class="mop-jump-separator">|</span>
- <a
- href="#"
- class="mop-jump-link"
- data-mop-jump="${escapeHtml(entry.taskId)}"
- title="Jump to cube ${escapeHtml(entry.taskId)} in EyeWire"
- >Jump</a>
- </div>
- `).join('')}
- </td>
- <td>
- <strong>${escapeHtml(group.cellName || ('Cell ' + group.cellId))}</strong>
- <div class="secondary">${escapeHtml(group.cellId)}</div>
- </td>
- <td>
- ${matching.map(entry => `
- <div class="entry-line status">
- ${escapeHtml(entry.statusText || titleCase(entry.status))}
- </div>
- `).join('')}
- </td>
- <td>
- ${matching.map(entry => `
- <div class="entry-line">${escapeHtml(titleCase(entry.issue))}</div>
- `).join('')}
- </td>
- <td>
- ${matching.map(entry => `
- <div class="entry-line">${escapeHtml(entry.lastUser)}</div>
- `).join('')}
- </td>
- <td>
- ${matching.map(entry => `
- <div class="entry-line">${escapeHtml(entry.lastUpdated)}</div>
- `).join('')}
- </td>
- `;
- tbody.appendChild(row);
- }
- const counter = panel.querySelector('#mop-result-count');
- if (counter) {
- counter.textContent =
- ` ${visibleCells.toLocaleString()} cells / ${visibleEntries.toLocaleString()} entries`;
- }
- }
- /******************************************************************
- * PROGRESS / HELPERS
- ******************************************************************/
- function updateProgress(state) {
- const panel = document.getElementById(PANEL_ID);
- if (!panel) return;
- const total = registryCells.length || Number(state.registryCount || 0);
- const done = Math.min(
- total || Number.MAX_SAFE_INTEGER,
- Number(state.cellsCompleted || state.scannedCellIds?.length || 0)
- );
- const percent = total > 0 ? Math.min(100, (done / total) * 100) : 0;
- const text = panel.querySelector('#mop-progress-text');
- if (text) {
- text.textContent = total
- ? `${done.toLocaleString()} / ${total.toLocaleString()} cells — ` +
- `${Number(state.cubesChecked || 0).toLocaleString()} cubes checked — ` +
- `${countEntries().toLocaleString()} unresolved — ` +
- `${Number(state.errors || 0).toLocaleString()} errors`
- : '';
- }
- const bar = panel.querySelector('#mop-progress-bar');
- if (bar) bar.style.width = `${percent}%`;
- updateButtons();
- }
- function updateButtons() {
- const panel = document.getElementById(PANEL_ID);
- if (!panel) return;
- panel.querySelector('#mop-start').disabled = running;
- panel.querySelector('#mop-pause').disabled = !running;
- panel.querySelector('#mop-full-rescan').disabled = running;
- panel.querySelector('#mop-reset').disabled = running;
- }
- function normalizeStatus(value) {
- return String(value || '').trim().toLowerCase().replace(/\s+/g, '-');
- }
- function normalizeText(value) {
- return String(value || '').replace(/\s+/g, ' ').trim();
- }
- function titleCase(value) {
- return String(value || '')
- .trim()
- .replace(/[-_]+/g, ' ')
- .replace(/\b\w/g, char => char.toUpperCase());
- }
- function escapeHtml(value) {
- return String(value || '')
- .replace(/&/g, '&')
- .replace(/</g, '<')
- .replace(/>/g, '>')
- .replace(/"/g, '"')
- .replace(/'/g, ''');
- }
- function parseDate(value) {
- if (!value) return 0;
- const raw = String(value).trim();
- let parsed = Date.parse(raw);
- if (!Number.isFinite(parsed)) {
- parsed = Date.parse(raw.replace(' ', 'T') + 'Z');
- }
- return Number.isFinite(parsed) ? parsed : 0;
- }
- function sleep(ms) {
- return new Promise(resolve => setTimeout(resolve, ms));
- }
- function setStatus(text) {
- const element = document.querySelector(`#${PANEL_ID} #mop-status`);
- if (element) element.textContent = text;
- console.log('[Mystic Open+] ' + text);
- }
- function clearError() {
- const element = document.querySelector(`#${PANEL_ID} #mop-error`);
- if (!element) return;
- element.style.display = 'none';
- element.textContent = '';
- }
- function showError(text) {
- const element = document.querySelector(`#${PANEL_ID} #mop-error`);
- if (!element) return;
- element.style.display = 'block';
- element.textContent = String(text || 'Unknown error');
- }
- function isVisible(element) {
- if (!element) return false;
- const rect = element.getBoundingClientRect();
- if (!rect.width || !rect.height) return false;
- const style = getComputedStyle(element);
- return style.display !== 'none' && style.visibility !== 'hidden';
- }
- /******************************************************************
- * CSS
- ******************************************************************/
- function ensureStyles() {
- if (document.getElementById(STYLE_ID)) return;
- const style = document.createElement('style');
- style.id = STYLE_ID;
- style.textContent = `
- #${TAB_ID} > a {
- background: #245f49 !important;
- border-color: #62cf96 !important;
- color: #fff !important;
- }
- #${TAB_ID} > a:hover,
- #${TAB_ID}.active > a {
- background: #327b5e !important;
- border-color: #74dfa9 !important;
- color: #fff !important;
- }
- .slPanelContent.mop-view-active,
- #slPanelContent.mop-view-active {
- display: flex !important;
- flex-direction: column !important;
- min-height: 0 !important;
- overflow-x: hidden !important;
- overflow-y: hidden !important;
- }
- .slPanelContent.mop-view-active .slOptions,
- #slPanelContent.mop-view-active #slOptions {
- flex: 0 0 auto !important;
- }
- .slPanelContent.mop-view-active #${PANEL_ID},
- #slPanelContent.mop-view-active #${PANEL_ID} {
- flex: 1 1 auto !important;
- display: flex !important;
- flex-direction: column !important;
- min-height: 0 !important;
- height: auto !important;
- overflow: hidden !important;
- }
- #${PANEL_ID} {
- position: static !important;
- left: auto !important;
- right: auto !important;
- top: auto !important;
- bottom: auto !important;
- width: 100% !important;
- height: auto !important;
- min-width: 0 !important;
- min-height: 0 !important;
- max-width: none !important;
- margin: 0 !important;
- padding: 0 !important;
- box-sizing: border-box !important;
- overflow: visible !important;
- background: transparent !important;
- border: 0 !important;
- border-radius: 0 !important;
- box-shadow: none !important;
- color: #eee;
- font: 13px Arial, sans-serif;
- }
- #${PANEL_ID} .mop-toolbar {
- display: flex;
- align-items: center;
- gap: 8px;
- box-sizing: border-box;
- padding: 8px 8px 5px;
- flex: 0 0 auto !important;
- }
- #${PANEL_ID} .mop-search-wrap {
- flex: 1 1 auto;
- min-width: 120px;
- }
- #${PANEL_ID} #mop-search {
- display: block;
- width: 100%;
- height: 28px;
- box-sizing: border-box;
- padding: 4px 7px;
- color: white;
- background: #101215;
- border: 1px solid #555;
- border-radius: 3px;
- }
- #${PANEL_ID} .mop-toolbar-buttons {
- display: flex;
- flex: 0 0 auto;
- align-items: center;
- gap: 5px;
- }
- #${PANEL_ID} button {
- display: inline-block;
- width: auto !important;
- min-width: 0 !important;
- height: 28px !important;
- margin: 0 !important;
- padding: 4px 8px !important;
- color: white !important;
- background: #25282d !important;
- border: 1px solid #555 !important;
- border-radius: 3px !important;
- font: 11px Arial, sans-serif !important;
- cursor: pointer !important;
- }
- #${PANEL_ID} button:hover {
- background: #33373c !important;
- }
- #${PANEL_ID} button.danger {
- background: #783c4e !important;
- }
- #${PANEL_ID} button:disabled {
- opacity: .45 !important;
- cursor: default !important;
- }
- #${PANEL_ID} .mop-status-row {
- display: grid;
- grid-template-columns: auto 1fr auto;
- align-items: center;
- gap: 15px;
- padding: 3px 8px 5px;
- color: #aab1b7;
- font-size: 11px;
- flex: 0 0 auto !important;
- }
- #${PANEL_ID} #mop-status {
- overflow: hidden;
- text-overflow: ellipsis;
- white-space: nowrap;
- }
- #${PANEL_ID} #mop-progress-text {
- white-space: nowrap;
- text-align: right;
- }
- #${PANEL_ID} .mop-progress-track {
- height: 2px;
- margin: 0 8px 4px;
- background: #292d32;
- flex: 0 0 auto !important;
- }
- #${PANEL_ID} #mop-progress-bar {
- width: 0%;
- height: 100%;
- background: #50b982;
- transition: width 100ms linear;
- }
- #${PANEL_ID} .mop-error {
- margin: 5px 8px;
- padding: 6px;
- color: #ffaaaa;
- background: #351d1d;
- border: 1px solid #864b4b;
- flex: 0 0 auto !important;
- }
- #${PANEL_ID} .mop-table-wrap {
- flex: 1 1 auto !important;
- width: 100%;
- height: auto !important;
- min-height: 0 !important;
- max-height: none !important;
- overflow-x: hidden !important;
- overflow-y: auto !important;
- overscroll-behavior: contain;
- scrollbar-gutter: stable;
- box-sizing: border-box !important;
- border-top: 1px solid #292d32;
- }
- #${PANEL_ID} table {
- width: 100%;
- border-collapse: collapse;
- table-layout: auto;
- }
- #${PANEL_ID} thead {
- position: sticky;
- top: 0;
- z-index: 2;
- background: #171a1e;
- }
- #${PANEL_ID} th,
- #${PANEL_ID} td {
- padding: 5px 8px;
- text-align: left;
- vertical-align: top;
- border-bottom: 1px solid #292d32;
- }
- #${PANEL_ID} tbody tr:nth-child(even) {
- background: rgba(255,255,255,.035);
- }
- #${PANEL_ID} tbody tr:hover {
- background: rgba(65,130,100,.16);
- }
- #${PANEL_ID} .entry-line {
- min-height: 18px;
- white-space: nowrap;
- }
- #${PANEL_ID} .mop-cube-link,
- #${PANEL_ID} .mop-jump-link {
- color: #55d9ff !important;
- text-decoration: none !important;
- cursor: pointer !important;
- font-weight: bold;
- }
- #${PANEL_ID} .mop-cube-link:hover,
- #${PANEL_ID} .mop-jump-link:hover {
- text-decoration: underline !important;
- }
- #${PANEL_ID} .mop-jump-separator {
- color: #777;
- margin: 0 4px;
- }
- #${PANEL_ID} .status {
- color: #ffff00;
- }
- #${PANEL_ID} .secondary {
- color: #828b94;
- font-size: 11px;
- margin-top: 2px;
- }
- `;
- (document.head || document.documentElement).appendChild(style);
- }
- if (document.readyState === 'loading') {
- document.addEventListener('DOMContentLoaded', start, { once: true });
- } else {
- start();
- }
- })();
Advertisement
Add Comment
Please, Sign In to add comment