~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
test(ui): add CI coverage for journal quality dashboard and download manager (#4449)
LearningCircuit8d04f3365d8e
diff --git a/tests/ui_tests/README.md b/tests/ui_tests/README.mdindex 684914c38d..14d6b1850c 100644--- a/tests/ui_tests/README.md+++ b/tests/ui_tests/README.md@@ -39,18 +39,39 @@ node tests/ui_tests/run_all_tests.js### Run a Single Shard-Tests are partitioned into five shards so CI can run them in parallel matrix-cells. Each entry in `run_all_tests.js` carries a `shard:` property. Local dev-rarely needs this, but you can reproduce a CI cell with:+Tests are partitioned into shards so CI can run them in parallel matrix+cells. Each entry in `run_all_tests.js` carries a `shard:` property; the+authoritative shard list is `VALID_SHARDS` at the top of that file (kept in+sync with `strategy.matrix.shard` in `.github/workflows/docker-tests.yml`).+Local dev rarely needs this, but you can reproduce a CI cell with:```bash-node tests/ui_tests/run_all_tests.js --shard=auth-core-node tests/ui_tests/run_all_tests.js --shard=research-node tests/ui_tests/run_all_tests.js --shard=settings-library-node tests/ui_tests/run_all_tests.js --shard=misc-mobile+node tests/ui_tests/run_all_tests.js --shard=settings-pages+node tests/ui_tests/run_all_tests.js --shard=librarynode tests/ui_tests/run_all_tests.js --shard=accessibility```+Valid shards (source of truth: `VALID_SHARDS` in `run_all_tests.js`):++| Shard | Scope |+|-------|-------|+| `auth-login` | Login/auth flow |+| `auth-register` | Registration (isolated — heavy SQLCipher DB creation) |+| `auth-pages` | Page browsing, navigation, comprehensive auth |+| `research-workflow` | Core research lifecycle |+| `research-form` | Research form interactions + results |+| `research-metrics` | Metrics charts, dashboard, progress |+| `settings-core` | Settings page, errors, save, interactions |+| `settings-pages` | Settings tabs, star reviews, journal quality |+| `library` | Collections, documents, download manager |+| `history-news` | History page, news subscriptions |+| `mobile` | Mobile navigation, interactions, UI |+| `api-crud` | API endpoints, CRUD operations, rate limiting |+| `error-benchmark` | Error handling/recovery, benchmark, context overflow |+| `accessibility` | Keyboard navigation & ARIA |+| `chat-core` | Chat ARIA, CSRF, suggestion chips |+| `chat-lifecycle` | Chat sessions, export, edit title |+Passing an unknown shard, or leaving `--shard` off while `CI=true` is set,fails fast with an error — this catches matrix misconfiguration before a cellwastes compute running the wrong slice.diff --git a/tests/ui_tests/run_all_tests.js b/tests/ui_tests/run_all_tests.jsindex 0222419d47..83d9584ea1 100644--- a/tests/ui_tests/run_all_tests.js+++ b/tests/ui_tests/run_all_tests.js@@ -240,7 +240,7 @@ const tests = [},// =====================================================================- // Shard: settings-pages (2 tests)+ // Shard: settings-pages (3 tests)// ====================================================================={name: 'Settings Pages CI Tests',@@ -254,9 +254,15 @@ const tests = [shard: 'settings-pages',description: 'Tests star reviews analytics page and visualizations'},+ {+ name: 'Journal Quality CI Tests',+ file: 'test_journal_quality_ci.js',+ shard: 'settings-pages',+ description: 'Tests journal quality dashboard: tabs, threshold slider settings round-trip, data-status APIs'+ },// =====================================================================- // Shard: library (3 tests)+ // Shard: library (4 tests)// ====================================================================={name: 'Library Collections CI Tests',@@ -276,6 +282,12 @@ const tests = [shard: 'library',description: 'Tests library collections page'},+ {+ name: 'Download Manager CI Tests',+ file: 'test_download_manager_ci.js',+ shard: 'library',+ description: 'Tests download manager: stats, filters, selection cycle, collections API'+ },// =====================================================================// Shard: history-news (3 tests)diff --git a/tests/ui_tests/test_download_manager_ci.js b/tests/ui_tests/test_download_manager_ci.jsnew file mode 100644index 0000000000..a0c23dd8f4--- /dev/null+++ b/tests/ui_tests/test_download_manager_ci.js@@ -0,0 +1,366 @@+#!/usr/bin/env node+/**+ * Download Manager UI Tests+ *+ * Tests for /library/download-manager — bulk PDF/text download page.+ *+ * Asserts on the page's real contracts (element IDs from+ * download_manager.html, API shapes from library_routes.py):+ * - server-rendered structure: header, 4 summary stat cards, filters+ * - collection selector resolves its async load (not stuck on+ * "Loading collections..." and not in the error state)+ * - download buttons stay disabled while nothing is selected and the+ * Select All / Select None cycle keeps counts + disabled state+ * consistent (works with any number of research items, incl. zero)+ * - progress modal exists but is hidden+ * - /library/api/collections/list contract+ *+ * Context: this page had a real production bug (#3941 UNIQUE-collision+ * cascade) and previously had zero UI test coverage.+ *+ * Run: node test_download_manager_ci.js+ */++const { setupTest, teardownTest, TestResults, log, navigateTo, withTimeout } = require('./test_lib');++const PAGE_PATH = '/library/download-manager';++// ============================================================================+// Page structure+// ============================================================================+const PageTests = {+ async pageLoads(page) {+ await page.waitForSelector('.ldr-download-manager-container', { timeout: 30000 });+ const result = await page.evaluate(() => ({+ headerText: document.querySelector('.ldr-manager-header h1')?.textContent?.trim(),+ }));++ const passed = result.headerText === 'Download Manager';+ return {+ passed,+ message: passed+ ? 'Download Manager page loaded with header'+ : `Unexpected header: "${result.headerText}"`+ };+ },++ async summaryStatsRendered(page) {+ // Four server-rendered stat cards, each with an integer value:+ // total researches, total resources, downloaded, available.+ const result = await page.evaluate(() => {+ const cards = Array.from(document.querySelectorAll('.ldr-summary-stats .ldr-stat-card'));+ return cards.map(c => ({+ value: c.querySelector('h3')?.textContent?.trim(),+ label: c.querySelector('p')?.textContent?.trim(),+ }));+ });++ if (result.length !== 4) {+ return { passed: false, message: `Expected 4 stat cards, found ${result.length}` };+ }+ const badValues = result.filter(c => !/^\d+$/.test(c.value || ''));+ return {+ passed: badValues.length === 0,+ message: badValues.length === 0+ ? `4 stat cards with integer values: ${result.map(c => `${c.label}=${c.value}`).join(', ')}`+ : `Non-integer stat values: ${JSON.stringify(badValues)}`+ };+ },++ async filterControlsPresent(page) {+ const result = await page.evaluate(() => {+ const mode = document.getElementById('filter-mode');+ const bulkTexts = Array.from(+ document.querySelectorAll('.ldr-bulk-actions .ldr-btn-bulk')+ ).map(b => b.textContent?.trim());+ return {+ modeOptions: mode ? Array.from(mode.options).map(o => o.value) : null,+ hasDateFrom: document.getElementById('filter-from')?.type === 'date',+ hasDateTo: document.getElementById('filter-to')?.type === 'date',+ hasRating: !!document.getElementById('filter-rating'),+ hasPdfs: !!document.getElementById('filter-pdfs'),+ hasSearch: !!document.getElementById('search-research'),+ bulkButtons: bulkTexts.length,+ hasSelectAll: bulkTexts.includes('Select All'),+ hasSelectNone: bulkTexts.includes('Select None'),+ hasSelectFiltered: bulkTexts.includes('Select Filtered'),+ };+ });++ const problems = [];+ if (!result.modeOptions?.includes('quick') || !result.modeOptions?.includes('detailed')) {+ problems.push(`mode filter options: ${JSON.stringify(result.modeOptions)}`);+ }+ if (!result.hasDateFrom || !result.hasDateTo) problems.push('date range inputs missing/wrong type');+ if (!result.hasRating) problems.push('rating filter missing');+ if (!result.hasPdfs) problems.push('PDF status filter missing');+ if (!result.hasSearch) problems.push('search input missing');+ if (result.bulkButtons < 3) problems.push(`expected at least 3 bulk buttons, found ${result.bulkButtons}`);+ if (!result.hasSelectAll) problems.push('Select All bulk button missing');+ if (!result.hasSelectNone) problems.push('Select None bulk button missing');+ if (!result.hasSelectFiltered) problems.push('Select Filtered bulk button missing');++ return {+ passed: problems.length === 0,+ message: problems.length === 0+ ? `All filters present (mode, date range, rating, PDF status, search) + ${result.bulkButtons} bulk buttons (Select All/None/Filtered)`+ : `Problems: ${problems.join('; ')}`+ };+ },++ async collectionSelectorResolves(page) {+ // loadCollections() runs at script eval and replaces the+ // "Loading collections..." placeholder with either real+ // collections or "No collections available". The error branch+ // ("Error loading collections") is a failure.+ await page.waitForFunction(() => {+ const select = document.getElementById('target-collection');+ if (!select || select.options.length === 0) return false;+ return !Array.from(select.options).some(o => o.textContent === 'Loading collections...');+ }, { timeout: 30000 });++ const result = await page.evaluate(() => {+ const select = document.getElementById('target-collection');+ const options = Array.from(select.options).map(o => o.textContent);+ return { options, errorState: options.includes('Error loading collections') };+ });++ if (result.errorState) {+ return { passed: false, message: 'Collection selector is in the error state (collections/list fetch failed)' };+ }+ return {+ passed: true,+ message: `Collection selector resolved: ${result.options.slice(0, 5).join(', ')}${result.options.length > 5 ? ', …' : ''}`+ };+ },++ async storageModeButtonPresent(page) {+ // One of three storage-mode variants is server-rendered; all+ // share the .ldr-storage-mode-btn class and "PDF Storage:" label.+ const result = await page.evaluate(() => {+ const btn = document.querySelector('.ldr-storage-mode-btn');+ return { exists: !!btn, text: btn?.textContent?.trim().replace(/\s+/g, ' ').slice(0, 80) };+ });++ const passed = result.exists && /PDF Storage:/.test(result.text || '');+ return {+ passed,+ message: passed+ ? `Storage mode button present: "${result.text}"`+ : `Storage mode button missing or unlabeled (text: "${result.text}")`+ };+ },++ async progressModalHidden(page) {+ const result = await page.evaluate(() => {+ const modal = document.getElementById('download-progress-modal');+ return {+ exists: !!modal,+ hidden: modal ? getComputedStyle(modal).display === 'none' : null,+ hasProgressBar: !!document.getElementById('overall-progress'),+ hasLog: !!document.getElementById('download-log'),+ };+ });++ const passed = result.exists && result.hidden && result.hasProgressBar && result.hasLog;+ return {+ passed,+ message: passed+ ? 'Progress modal exists with progress bar + log, hidden by default'+ : `Modal state wrong: ${JSON.stringify(result)}`+ };+ },++ async settingsLinkPresent(page) {+ const exists = await page.evaluate(() =>+ !!document.querySelector('a[href="/settings#research-library"]')+ );+ return {+ passed: exists,+ message: exists+ ? 'Configure Library Settings link points to /settings#research-library'+ : 'Settings link missing'+ };+ },+};++// ============================================================================+// Selection behavior+// ============================================================================+const SelectionTests = {+ async downloadButtonsDisabledAtZero(page) {+ const result = await page.evaluate(() => ({+ pdfDisabled: document.getElementById('download-pdfs')?.disabled,+ textDisabled: document.getElementById('download-text-db')?.disabled,+ pdfCount: document.querySelector('.ldr-selected-count-pdf')?.textContent?.trim(),+ textCount: document.querySelector('.ldr-selected-count-text-db')?.textContent?.trim(),+ }));++ const passed = result.pdfDisabled === true && result.textDisabled === true &&+ result.pdfCount === '0' && result.textCount === '0';+ return {+ passed,+ message: passed+ ? 'Both download buttons disabled with 0 selected'+ : `Initial state wrong: ${JSON.stringify(result)}`+ };+ },++ async selectAllNoneCycle(page) {+ // Select All must set the count to the number of checkboxes and+ // (when items exist) enable the Text Only button; Select None+ // must return to 0/disabled. Works with zero items too: the+ // count stays 0 and buttons stay disabled.+ // window.selectAll/selectNone are page globals defined in the+ // inline script of templates/pages/download_manager.html.+ // TODO: consider wrapping selectAll/selectNone in a test helper+ // (e.g. window.__ldrTest__.downloadManager) to reduce coupling+ // as more contract tests are added for this page.+ const result = await page.evaluate(() => {+ const checkboxCount = document.querySelectorAll('.ldr-research-select').length;+ const read = () => ({+ count: document.querySelector('.ldr-selected-count-text-db')?.textContent?.trim(),+ textDisabled: document.getElementById('download-text-db')?.disabled,+ selectedItems: document.querySelectorAll('.ldr-research-item.ldr-selected').length,+ });++ window.selectAll();+ const afterAll = read();+ window.selectNone();+ const afterNone = read();++ return { checkboxCount, afterAll, afterNone };+ });++ const problems = [];+ if (result.afterAll.count !== String(result.checkboxCount)) {+ problems.push(`Select All count=${result.afterAll.count}, expected ${result.checkboxCount}`);+ }+ if (result.afterAll.selectedItems !== result.checkboxCount) {+ problems.push(`Select All highlighted ${result.afterAll.selectedItems}/${result.checkboxCount} items`);+ }+ if (result.checkboxCount > 0 && result.afterAll.textDisabled !== false) {+ problems.push('Text Only button still disabled after Select All');+ }+ if (result.afterNone.count !== '0' || result.afterNone.textDisabled !== true || result.afterNone.selectedItems !== 0) {+ problems.push(`Select None state wrong: ${JSON.stringify(result.afterNone)}`);+ }++ return {+ passed: problems.length === 0,+ message: problems.length === 0+ ? `Select All/None cycle consistent (${result.checkboxCount} research items)`+ : `Problems: ${problems.join('; ')}`+ };+ },+};++// ============================================================================+// API contracts+// ============================================================================+const ApiTests = {+ async collectionsListContract(page) {+ const result = await page.evaluate(async () => {+ const resp = await fetch('/library/api/collections/list');+ if (!resp.ok) return { ok: false, status: resp.status };+ const data = await resp.json();+ return {+ ok: true,+ success: data.success,+ collectionsIsArray: Array.isArray(data.collections),+ count: Array.isArray(data.collections) ? data.collections.length : null,+ shapeOk: Array.isArray(data.collections) && data.collections.every(+ c => c.id !== undefined && typeof c.name === 'string'+ ),+ };+ });++ if (!result.ok) {+ return { passed: false, message: `collections/list returned HTTP ${result.status}` };+ }+ const passed = result.success === true && result.collectionsIsArray && result.shapeOk;+ return {+ passed,+ message: passed+ ? `collections/list contract OK (${result.count} collections, each with id + name)`+ : `Contract violation: ${JSON.stringify(result)}`+ };+ },+};++// ============================================================================+// Main Test Runner+// ============================================================================+async function main() {+ log.section('Download Manager Tests');++ const ctx = await setupTest({ authenticate: true });+ const results = new TestResults('Download Manager Tests');+ const { page } = ctx;+ const { baseUrl } = ctx.config;++ // Collect uncaught page exceptions for the whole run.+ const pageErrors = [];+ page.on('pageerror', (err) => pageErrors.push(err.message));++ const subTestTimeout = ctx.config.isCI ? 60000 : 30000;+ async function run(category, name, testFn) {+ try {+ const result = await withTimeout(testFn(page), subTestTimeout, `${category}/${name}`);+ if (result.skipped) {+ results.skip(category, name, result.message);+ } else {+ results.add(category, name, result.passed, result.message);+ }+ } catch (error) {+ results.add(category, name, false, `Error: ${error.message}`);+ }+ }++ try {+ await navigateTo(page, `${baseUrl}${PAGE_PATH}`);++ log.section('Page Structure');+ await run('Page', 'Page Loads', PageTests.pageLoads);+ await run('Page', 'Summary Stats Rendered', PageTests.summaryStatsRendered);+ await run('Page', 'Filter Controls Present', PageTests.filterControlsPresent);+ await run('Page', 'Collection Selector Resolves', PageTests.collectionSelectorResolves);+ await run('Page', 'Storage Mode Button Present', PageTests.storageModeButtonPresent);+ await run('Page', 'Progress Modal Hidden', PageTests.progressModalHidden);+ await run('Page', 'Settings Link Present', PageTests.settingsLinkPresent);++ log.section('Selection Behavior');+ await run('Selection', 'Download Buttons Disabled At Zero', SelectionTests.downloadButtonsDisabledAtZero);+ await run('Selection', 'Select All/None Cycle', SelectionTests.selectAllNoneCycle);++ log.section('API Contracts');+ await run('API', 'Collections List Contract', ApiTests.collectionsListContract);++ log.section('Page Errors');+ results.add(+ 'Errors', 'No Uncaught Page Exceptions',+ pageErrors.length === 0,+ pageErrors.length === 0+ ? 'No uncaught exceptions during the whole run'+ : `Uncaught exceptions: ${pageErrors.slice(0, 3).join(' | ')}`+ );+ } catch (error) {+ log.error(`Fatal error: ${error.message}`);+ console.error(error.stack);+ results.add('Fatal', 'Test Suite Execution', false, error.message);+ } finally {+ results.print();+ results.save();+ await teardownTest(ctx);+ process.exit(results.exitCode());+ }+}++if (require.main === module) {+ main().catch(error => {+ console.error('Test runner failed:', error);+ process.exit(1);+ });+}++module.exports = { PageTests, SelectionTests, ApiTests };diff --git a/tests/ui_tests/test_journal_quality_ci.js b/tests/ui_tests/test_journal_quality_ci.jsnew file mode 100644index 0000000000..609550c4a0--- /dev/null+++ b/tests/ui_tests/test_journal_quality_ci.js@@ -0,0 +1,555 @@+#!/usr/bin/env node+/**+ * Journal Quality Dashboard UI Tests+ *+ * Tests for /metrics/journals — the journal quality dashboard.+ *+ * Asserts on the page's real contracts (element IDs from+ * journal_quality.html, API response shapes from metrics_routes.py)+ * rather than heuristic selectors:+ * - init completes: #ldr-loading hides, #ldr-content shows+ * - tab bar switches panels and the active class+ * - threshold slider live-preview + debounced save round-trips+ * through /settings/api/search.journal_reputation.threshold+ * - data-sources banner renders one card per source from+ * /metrics/api/journal-data/status+ * - "Your Research" tab resolves to exactly one of empty/content+ *+ * First-install state (reference DB not downloaded — the CI default,+ * since datasets are fetched fresh at runtime and never bundled):+ * /metrics/api/journals does NOT fast-fail in that state. Its first+ * access lazily builds the reference DB via+ * ensure_journal_data(auto_download=True) (journal_quality/db.py+ * _build_or_raise) — a synchronous multi-minute download from+ * OpenAlex/DOAJ inside the request. The test therefore gates every+ * code path that could touch that endpoint on+ * /metrics/api/journal-data/status (pure filesystem check, always+ * fast): when data is not installed the global-journals API test is+ * skipped, and the tab-switch test stubs the journals fetch so+ * clicking the tab cannot kick off the download in CI.+ *+ * Run: node test_journal_quality_ci.js+ */++const { setupTest, teardownTest, TestResults, log, navigateTo, withTimeout } = require('./test_lib');++const PAGE_PATH = '/metrics/journals';+const THRESHOLD_KEY = 'search.journal_reputation.threshold';++// ============================================================================+// Page structure & init+// ============================================================================+const PageTests = {+ async initCompletes(page) {+ // Init runs on window `load` (after Vite module scripts): it hides+ // #ldr-loading and shows #ldr-content. Wait for that contract.+ await page.waitForFunction(() => {+ const loading = document.getElementById('ldr-loading');+ const content = document.getElementById('ldr-content');+ return loading && content &&+ getComputedStyle(loading).display === 'none' &&+ getComputedStyle(content).display !== 'none';+ }, { timeout: 30000 });++ const result = await page.evaluate(() => ({+ headerText: document.querySelector('.ldr-metrics-header h1')?.textContent?.trim(),+ errorVisible: getComputedStyle(document.getElementById('ldr-error')).display !== 'none',+ errorText: document.getElementById('ldr-error')?.textContent?.trim(),+ }));++ if (!result.headerText?.includes('Journal Quality')) {+ return { passed: false, message: `Unexpected header: "${result.headerText}"` };+ }+ if (result.errorVisible) {+ return { passed: false, message: `Error box visible after init: "${result.errorText}"` };+ }+ return { passed: true, message: 'Init completed: loading hidden, content shown, no error box' };+ },++ async tabBarStructure(page) {+ const result = await page.evaluate(() => {+ const tabs = Array.from(document.querySelectorAll('.ldr-tab-bar .ldr-tab-btn'));+ return {+ tabIds: tabs.map(t => t.dataset.tab),+ activeTab: tabs.find(t => t.classList.contains('ldr-tab-active'))?.dataset.tab,+ yourResearchVisible: getComputedStyle(document.getElementById('ldr-tab-your-research')).display !== 'none',+ globalDbVisible: getComputedStyle(document.getElementById('ldr-tab-global-db')).display !== 'none',+ howItWorksVisible: getComputedStyle(document.getElementById('ldr-tab-how-it-works')).display !== 'none',+ };+ });++ const expected = ['your-research', 'global-db', 'how-it-works'];+ const missing = expected.filter(t => !result.tabIds.includes(t));+ if (missing.length > 0) {+ return { passed: false, message: `Missing tabs: ${missing.join(', ')} (found: ${result.tabIds.join(', ')})` };+ }+ // Default tab is "Your Research" — only its panel may be visible.+ const passed = result.activeTab === 'your-research' &&+ result.yourResearchVisible && !result.globalDbVisible && !result.howItWorksVisible;+ return {+ passed,+ message: passed+ ? 'Tab bar has all 3 tabs; default is "Your Research" with only its panel visible'+ : `Bad default tab state: active=${result.activeTab}, visible panels: yr=${result.yourResearchVisible}, db=${result.globalDbVisible}, how=${result.howItWorksVisible}`+ };+ },++ async yourResearchResolves(page) {+ // loadUserResearchJournals() must resolve the tab to exactly one of+ // the two terminal states: empty state (fresh user) or content.+ await page.waitForFunction(() => {+ const loading = document.getElementById('ldr-yr-loading');+ return loading && getComputedStyle(loading).display === 'none';+ }, { timeout: 30000 });++ const result = await page.evaluate(() => ({+ emptyVisible: getComputedStyle(document.getElementById('ldr-yr-empty')).display !== 'none',+ contentVisible: getComputedStyle(document.getElementById('ldr-yr-content')).display !== 'none',+ }));++ const states = [result.emptyVisible, result.contentVisible].filter(Boolean).length;+ if (states !== 1) {+ return { passed: false, message: `Expected exactly one of empty/content visible, got empty=${result.emptyVisible}, content=${result.contentVisible}` };+ }+ return {+ passed: true,+ message: `"Your Research" tab resolved to ${result.emptyVisible ? 'empty state (no research yet)' : 'content with stats'}`+ };+ },++ async tabSwitchingWorks(page, dataInstalled) {+ // The first click on "Global Database" lazily fires+ // loadJournalPage() → GET /metrics/api/journals. In the+ // first-install state that GET triggers the server's synchronous+ // fetch-on-first-use download (multi-minute, by design — see the+ // header comment), so stub just that URL with the 503 the page+ // already handles as its documented first-install response. The+ // contract under test — active-class movement and panel swap —+ // is pure DOM and unaffected by the stub.+ if (!dataInstalled) {+ await page.evaluate(() => {+ window.__ldrTestRealFetch = window.fetch;+ window.fetch = (input, init) => {+ const url = typeof input === 'string' ? input : input.url;+ if (url.includes('/metrics/api/journals?')) {+ return Promise.resolve(new Response('', { status: 503 }));+ }+ return window.__ldrTestRealFetch(input, init);+ };+ });+ }++ let afterSwitch;+ try {+ // Click "Global Database" → active class moves, panels swap.+ await page.evaluate(() => {+ document.querySelector('.ldr-tab-btn[data-tab="global-db"]').click();+ });+ afterSwitch = await page.evaluate(() => ({+ activeTab: document.querySelector('.ldr-tab-btn.ldr-tab-active')?.dataset.tab,+ globalDbVisible: getComputedStyle(document.getElementById('ldr-tab-global-db')).display !== 'none',+ yourResearchVisible: getComputedStyle(document.getElementById('ldr-tab-your-research')).display !== 'none',+ }));++ // Switch back to leave the page in its default state for later tests.+ await page.evaluate(() => {+ document.querySelector('.ldr-tab-btn[data-tab="your-research"]').click();+ });+ } finally {+ if (!dataInstalled) {+ await page.evaluate(() => {+ if (window.__ldrTestRealFetch) {+ window.fetch = window.__ldrTestRealFetch;+ delete window.__ldrTestRealFetch;+ }+ });+ }+ }++ const passed = afterSwitch.activeTab === 'global-db' &&+ afterSwitch.globalDbVisible && !afterSwitch.yourResearchVisible;+ return {+ passed,+ message: passed+ ? 'Tab switch to Global Database moved active class and swapped panels'+ : `Tab switch failed: active=${afterSwitch.activeTab}, db=${afterSwitch.globalDbVisible}, yr=${afterSwitch.yourResearchVisible}`+ };+ },++ async globalDbControlsPresent(page) {+ const result = await page.evaluate(() => {+ const tierFilter = document.getElementById('ldr-filter-tier');+ const sourceFilter = document.getElementById('ldr-filter-source');+ return {+ hasSearch: !!document.getElementById('ldr-journal-search'),+ tierOptions: tierFilter ? tierFilter.options.length : 0,+ sourceOptions: sourceFilter ? sourceFilter.options.length : 0,+ sortableHeaders: document.querySelectorAll('.ldr-journal-table th[data-sort]').length,+ defaultSortDesc: !!document.querySelector('.ldr-journal-table th[data-sort="quality"].ldr-sorted-desc'),+ hasTbody: !!document.getElementById('ldr-journal-tbody'),+ hasPagination: !!document.getElementById('ldr-pagination'),+ };+ });++ const problems = [];+ if (!result.hasSearch) problems.push('search input missing');+ if (result.tierOptions < 2) problems.push(`tier filter has ${result.tierOptions} options`);+ if (result.sourceOptions < 2) problems.push(`source filter has ${result.sourceOptions} options`);+ if (result.sortableHeaders < 1) problems.push('no sortable headers');+ if (!result.defaultSortDesc) problems.push('default quality desc sort indicator missing');+ if (!result.hasTbody || !result.hasPagination) problems.push('table body or pagination container missing');++ return {+ passed: problems.length === 0,+ message: problems.length === 0+ ? `Global DB controls present (${result.sortableHeaders} sortable columns, tier/source filters, search)`+ : `Problems: ${problems.join('; ')}`+ };+ },++ async sourcesBannerRendered(page) {+ // checkDataStatus() injects one card per data source into+ // #ldr-sources-grid, each with a Downloaded/Not-downloaded pill.+ await page.waitForFunction(+ () => document.getElementById('ldr-sources-grid')?.children.length > 0,+ { timeout: 15000 }+ );++ const result = await page.evaluate(() => {+ const cards = Array.from(document.getElementById('ldr-sources-grid').children);+ return {+ cardCount: cards.length,+ cardsWithPill: cards.filter(c => /Downloaded|Not downloaded/.test(c.textContent)).length,+ names: cards.map(c => c.querySelector('a')?.textContent?.trim()).filter(Boolean),+ };+ });++ const passed = result.cardCount >= 3 && result.cardsWithPill === result.cardCount;+ return {+ passed,+ message: passed+ ? `Sources banner rendered ${result.cardCount} cards with status pills: ${result.names.join(', ')}`+ : `Banner incomplete: ${result.cardCount} cards, ${result.cardsWithPill} with status pill`+ };+ },+};++// ============================================================================+// Threshold slider+// ============================================================================+const ThresholdTests = {+ async livePreviewUpdates(page) {+ // Dragging the top slider must update the value label, the+ // explanation text, and sync the second slider — without saving.+ const result = await page.evaluate(() => {+ const slider = document.getElementById('ldr-threshold-slider-top');+ slider.value = '7';+ slider.dispatchEvent(new Event('input'));+ return {+ valueLabel: document.getElementById('ldr-threshold-value-top')?.textContent?.trim(),+ explanation: document.getElementById('ldr-threshold-explanation-top')?.textContent || '',+ otherSliderValue: document.getElementById('ldr-threshold-slider')?.value,+ };+ });++ // "Good quality" is THRESHOLD_DESCRIPTIONS[7].label in+ // journal_quality.html — the label text is part of the asserted+ // contract; update both together if the copy changes.+ const passed = result.valueLabel === '7' &&+ result.explanation.includes('Good quality') &&+ result.otherSliderValue === '7';+ return {+ passed,+ message: passed+ ? 'Slider input updates value label, explanation, and syncs the second slider'+ : `Live preview wrong: label=${result.valueLabel} (expected "7"), synced=${result.otherSliderValue}, explanation expected "Good quality" but got "${result.explanation.slice(0, 60)}"`+ };+ },++ async changePersistsToSettings(page) {+ // The slider's change handler debounces 300 ms, PUTs the setting,+ // and shows "✓ Saved". Verify the full round-trip via the GET API.+ const original = await page.evaluate(async (key) => {+ const resp = await fetch(`/settings/api/${key}`);+ const data = await resp.json();+ return (data.setting && data.setting.value) ?? data.value;+ }, THRESHOLD_KEY);++ if (typeof original !== 'number') {+ return { passed: false, message: `Could not read current threshold (got ${JSON.stringify(original)})` };+ }++ // Pick a target that differs from the current value (both are+ // inside the slider's valid 1–10 range).+ const target = original === 5 ? 6 : 5;++ // Mutate-then-verify inside try/catch and restore unconditionally+ // afterwards: a transient failure (e.g. the save-status wait+ // timing out) must not leave the user's setting at `target`.+ let mutated = false;+ let statusText = null;+ let saved = null;+ let roundTripError = null;+ try {+ await page.evaluate((value) => {+ const slider = document.getElementById('ldr-threshold-slider-top');+ slider.value = String(value);+ slider.dispatchEvent(new Event('input'));+ slider.dispatchEvent(new Event('change'));+ }, target);+ mutated = true;++ // Wait for the save status to resolve (debounce 300 ms + PUT).+ await page.waitForFunction(() => {+ const status = document.getElementById('ldr-threshold-save-status-top')?.textContent || '';+ return status.includes('Saved') || status.includes('failed');+ }, { timeout: 15000 });++ statusText = await page.evaluate(() =>+ document.getElementById('ldr-threshold-save-status-top')?.textContent?.trim()+ );++ saved = await page.evaluate(async (key) => {+ const resp = await fetch(`/settings/api/${key}`);+ const data = await resp.json();+ return (data.setting && data.setting.value) ?? data.value;+ }, THRESHOLD_KEY);+ } catch (e) {+ roundTripError = e.message;+ }++ // Restore the original value so the test doesn't leak state —+ // even when the round-trip above failed part-way.+ let restored = true;+ if (mutated) {+ restored = await page.evaluate(async ([key, value]) => {+ const csrf = document.querySelector('meta[name="csrf-token"]');+ const headers = { 'Content-Type': 'application/json' };+ if (csrf) headers['X-CSRFToken'] = csrf.content;+ const resp = await fetch(`/settings/api/${key}`, {+ method: 'PUT', headers, body: JSON.stringify({ value }),+ });+ return resp.ok;+ }, [THRESHOLD_KEY, original]);+ }++ if (!restored) {+ return { passed: false, message: `FAILED to restore original value ${original} after mutating to ${target} — user setting is dirty` };+ }+ if (roundTripError) {+ return { passed: false, message: `Round-trip error (setting restored to ${original}): ${roundTripError}` };+ }+ const passed = statusText?.includes('Saved') && saved === target;+ return {+ passed,+ message: passed+ ? `Slider change persisted: ${original} → ${target} (status "${statusText}"), then restored to ${original}`+ : `Persist failed: status="${statusText}", GET returned ${JSON.stringify(saved)} (expected ${target}); setting restored to ${original}`+ };+ },+};++// ============================================================================+// API contracts+// ============================================================================+const ApiTests = {+ async journalDataStatusContract(page) {+ const result = await page.evaluate(async () => {+ const resp = await fetch('/metrics/api/journal-data/status');+ if (!resp.ok) return { ok: false, status: resp.status };+ const data = await resp.json();+ return {+ ok: true,+ availableIsBool: typeof data.available === 'boolean',+ sourcesIsArray: Array.isArray(data.sources),+ sourceCount: Array.isArray(data.sources) ? data.sources.length : 0,+ sourcesShapeOk: Array.isArray(data.sources) && data.sources.every(+ s => typeof s.name === 'string' && typeof s.present === 'boolean'+ ),+ hasLatestVersion: typeof data.latest_version === 'string',+ };+ });++ if (!result.ok) {+ return { passed: false, message: `Status endpoint returned HTTP ${result.status}` };+ }+ const passed = result.availableIsBool && result.sourcesIsArray &&+ result.sourceCount >= 3 && result.sourcesShapeOk && result.hasLatestVersion;+ return {+ passed,+ message: passed+ ? `journal-data/status contract OK (${result.sourceCount} sources, available + latest_version present)`+ : `Contract violation: ${JSON.stringify(result)}`+ };+ },++ async userResearchContract(page) {+ const result = await page.evaluate(async () => {+ const resp = await fetch('/metrics/api/journals/user-research');+ if (!resp.ok) return { ok: false, status: resp.status };+ const data = await resp.json();+ return {+ ok: true,+ status: data.status,+ hasSummary: typeof data.summary === 'object' && data.summary !== null,+ totalJournals: data.summary?.total_journals,+ journalsIsArray: Array.isArray(data.journals),+ };+ });++ if (!result.ok) {+ return { passed: false, message: `user-research endpoint returned HTTP ${result.status}` };+ }+ const passed = result.status === 'success' && result.hasSummary &&+ typeof result.totalJournals === 'number' && result.journalsIsArray;+ return {+ passed,+ message: passed+ ? `user-research contract OK (${result.totalJournals} journals for this user)`+ : `Contract violation: ${JSON.stringify(result)}`+ };+ },++ async globalJournalsContract(page, dataInstalled) {+ // Only exercised when the reference DB is installed: in the+ // first-install state this endpoint does not fast-fail — it+ // synchronously downloads + builds the reference DB inside the+ // request (multi-minute; see header comment), which would both+ // time out this sub-test and burn CI bandwidth.+ if (!dataInstalled) {+ return {+ passed: null,+ skipped: true,+ message: 'Reference DB not installed — querying /metrics/api/journals would trigger the synchronous fetch-on-first-use download; contract is covered on installed systems'+ };+ }++ // status said the data is installed, so anything but a fast+ // success here (including 503) is a real contract violation.+ const result = await page.evaluate(async () => {+ const resp = await fetch('/metrics/api/journals?page=1&per_page=25&sort=quality&order=desc');+ if (!resp.ok) return { ok: false, status: resp.status };+ if (!resp.headers.get('content-type')?.includes('application/json')) {+ return { ok: false, status: resp.status, badContentType: true };+ }+ const data = await resp.json();+ return {+ ok: true,+ status: data.status,+ journalsIsArray: Array.isArray(data.journals),+ hasPagination: typeof data.pagination === 'object' && data.pagination !== null,+ };+ });++ if (!result.ok) {+ return { passed: false, message: `journals API failed despite status reporting data installed: HTTP ${result.status}${result.badContentType ? ' (non-JSON body)' : ''}` };+ }+ const passed = result.status === 'success' && result.journalsIsArray && result.hasPagination;+ return {+ passed,+ message: passed+ ? 'journals API contract OK (success + journals[] + pagination)'+ : `Contract violation: ${JSON.stringify(result)}`+ };+ },+};++// ============================================================================+// Main Test Runner+// ============================================================================+async function main() {+ log.section('Journal Quality Dashboard Tests');++ const ctx = await setupTest({ authenticate: true });+ const results = new TestResults('Journal Quality Tests');+ const { page } = ctx;+ const { baseUrl } = ctx.config;++ // Collect uncaught page exceptions for the whole run — a page that+ // throws during init is a regression even if individual asserts pass.+ const pageErrors = [];+ page.on('pageerror', (err) => pageErrors.push(err.message));++ // Set per test below — whether the journal reference data is+ // installed on this server (pure filesystem check, always fast).+ // Gates every code path that could touch /metrics/api/journals,+ // because in the first-install state that endpoint synchronously+ // downloads the data inside the request (see header comment).+ let dataInstalled = false;++ const subTestTimeout = ctx.config.isCI ? 60000 : 30000;+ async function run(category, name, testFn) {+ try {+ const result = await withTimeout(testFn(page, dataInstalled), subTestTimeout, `${category}/${name}`);+ if (result.skipped) {+ results.skip(category, name, result.message);+ } else {+ results.add(category, name, result.passed, result.message);+ }+ } catch (error) {+ results.add(category, name, false, `Error: ${error.message}`);+ }+ }++ try {+ // Navigate once and wait for the full `load` event — the page's+ // init handler is bound to window load (after Vite module scripts).+ await navigateTo(page, `${baseUrl}${PAGE_PATH}`, { waitUntil: 'load' });++ // Snapshotted once at suite start; not re-checked mid-run.+ dataInstalled = await page.evaluate(async () => {+ try {+ const resp = await fetch('/metrics/api/journal-data/status');+ const data = await resp.json();+ return data.available === true;+ } catch {+ return false;+ }+ });+ log.info(`Journal reference data installed: ${dataInstalled}`);++ log.section('Page Structure & Init');+ await run('Page', 'Init Completes', PageTests.initCompletes);+ await run('Page', 'Tab Bar Structure', PageTests.tabBarStructure);+ await run('Page', 'Your Research Tab Resolves', PageTests.yourResearchResolves);+ await run('Page', 'Tab Switching Works', PageTests.tabSwitchingWorks);+ await run('Page', 'Global DB Controls Present', PageTests.globalDbControlsPresent);+ await run('Page', 'Sources Banner Rendered', PageTests.sourcesBannerRendered);++ log.section('Threshold Slider');+ await run('Threshold', 'Live Preview Updates', ThresholdTests.livePreviewUpdates);+ await run('Threshold', 'Change Persists To Settings', ThresholdTests.changePersistsToSettings);++ log.section('API Contracts');+ await run('API', 'Journal Data Status Contract', ApiTests.journalDataStatusContract);+ await run('API', 'User Research Contract', ApiTests.userResearchContract);+ await run('API', 'Global Journals Contract', ApiTests.globalJournalsContract);++ log.section('Page Errors');+ results.add(+ 'Errors', 'No Uncaught Page Exceptions',+ pageErrors.length === 0,+ pageErrors.length === 0+ ? 'No uncaught exceptions during the whole run'+ : `Uncaught exceptions: ${pageErrors.slice(0, 3).join(' | ')}`+ );+ } catch (error) {+ log.error(`Fatal error: ${error.message}`);+ console.error(error.stack);+ results.add('Fatal', 'Test Suite Execution', false, error.message);+ } finally {+ results.print();+ results.save();+ await teardownTest(ctx);+ process.exit(results.exitCode());+ }+}++if (require.main === module) {+ main().catch(error => {+ console.error('Test runner failed:', error);+ process.exit(1);+ });+}++module.exports = { PageTests, ThresholdTests, ApiTests };