~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
fix(ui): improve mobile navigation and add comprehensive layout tests
LearningCircuit0818b5a16f8a
diff --git a/src/local_deep_research/web/static/css/mobile-navigation.css b/src/local_deep_research/web/static/css/mobile-navigation.cssindex 82ad946d77..71a8348bb1 100644--- a/src/local_deep_research/web/static/css/mobile-navigation.css+++ b/src/local_deep_research/web/static/css/mobile-navigation.css@@ -127,7 +127,9 @@transform: translateY(100%);transition: transform var(--mobile-transition);z-index: 2000;- max-height: 85vh;+ /* Allow more height for all menu sections - use dvh for dynamic viewport on mobile */+ max-height: calc(100vh - 60px);+ max-height: calc(100dvh - 60px); /* Fallback for browsers supporting dvh */display: flex;flex-direction: column;box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.3);@@ -350,35 +352,63 @@}}-/* Short viewport height - switch to mobile nav when sidebar would be cut off */-/* This handles cases where screen width is large but height is small */+/* Short viewport height - make sidebar ultra-compact */+/* Keep sidebar visible but minimize spacing to fit all items */@media (min-width: 768px) and (max-height: 600px) {- /* Show mobile nav */- .ldr-mobile-bottom-nav {+ /* Ensure sidebar is visible */+ .ldr-sidebar {display: flex !important;+ visibility: visible !important;+ width: 200px !important;}-- .ldr-mobile-bottom-nav.visible {- display: flex !important;+ .ldr-main-content {+ margin-left: 200px !important;}-- /* Hide desktop sidebar */- .ldr-sidebar {- display: none !important;+ /* Ultra-compact sidebar for very short viewports */+ .ldr-sidebar-header {+ padding: 0.25rem 0.5rem !important;}-- /* Adjust main content */- .ldr-main-content {- margin-left: 0 !important;- width: 100% !important;+ .ldr-sidebar-header h2 {+ font-size: 0.9rem !important;+ }+ .ldr-sidebar-nav {+ padding: 0.125rem 0 !important;}+ .ldr-sidebar-nav li {+ min-height: 20px !important;+ }+ .ldr-sidebar-nav li a {+ padding: 0.15rem 0.5rem !important;+ font-size: 0.8rem !important;+ }+ .ldr-sidebar-section {+ margin-bottom: 0.15rem !important;+ }+ .ldr-sidebar-section-label {+ padding: 0.1rem 0.5rem !important;+ font-size: 0.5rem !important;+ }+ .ldr-sidebar-footer {+ padding: 0.25rem 0.5rem !important;+ font-size: 0.7rem !important;+ }+ .ldr-sidebar-footer p {+ margin: 0 !important;+ }+}- /* Adjust body padding for nav bar */- body.ldr-has-mobile-nav {- padding-bottom: calc(var(--mobile-nav-height) + env(safe-area-inset-bottom));+/* Extremely short viewport - hide footer, keep nav */+@media (min-width: 768px) and (max-height: 500px) {+ .ldr-sidebar-footer {+ display: none !important;+ }+ .ldr-sidebar-section-label {+ display: none !important;}+}- /* Adjust top bar */+/* Mobile: Adjust top bar for narrow screens */+@media (max-width: 767px) {.ldr-top-bar {left: 0 !important;}diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.cssindex d80619a624..d75e63d626 100644--- a/src/local_deep_research/web/static/css/styles.css+++ b/src/local_deep_research/web/static/css/styles.css@@ -66,7 +66,7 @@ a:hover {}.ldr-sidebar-header {- padding: 1.5rem;+ padding: 0.75rem 1rem;border-bottom: 1px solid var(--border-color);}@@ -85,7 +85,7 @@ a:hover {.ldr-sidebar-nav {flex: 1;- padding: 1rem 0;+ padding: 0.5rem 0;overflow-y: auto;/* Smooth scrolling */scroll-behavior: smooth;@@ -113,20 +113,20 @@ a:hover {}.ldr-sidebar-nav li {- margin-bottom: 0.25rem;+ margin-bottom: 0;cursor: pointer;color: var(--text-secondary);border-left: 3px solid transparent;transition: all 0.2s;position: relative;- min-height: 52px; /* Ensures a reasonable clickable height */+ min-height: 28px; /* Compact */}.ldr-sidebar-nav li a {display: flex;align-items: center;- gap: 0.75rem;- padding: 0.75rem 1.5rem;+ gap: 0.5rem;+ padding: 0.35rem 1rem;color: inherit;text-decoration: none;width: 100%;@@ -220,12 +220,12 @@ a:hover {/* Sidebar Sections */.ldr-sidebar-section {- margin-bottom: 1.5rem;+ margin-bottom: 0.5rem;}.ldr-sidebar-section-label {- padding: 0.5rem 1.5rem 0.5rem 1.5rem;- font-size: 0.75rem;+ padding: 0.25rem 1rem 0.125rem 1rem;+ font-size: 0.65rem;font-weight: 700;text-transform: uppercase;letter-spacing: 0.05em;@@ -234,7 +234,7 @@ a:hover {}.ldr-sidebar-section ul {- margin-top: 0.25rem;+ margin-top: 0.125rem;}/* Nested sidebar items */@@ -1155,6 +1155,55 @@ textarea:focus, input[type="text"]:focus {opacity: 1;}+/* Adaptive sidebar - compact when viewport height is limited */+@media (max-height: 800px) {+ .ldr-sidebar-header {+ padding: 0.5rem 1rem;+ }+ .ldr-sidebar-nav {+ padding: 0.25rem 0;+ }+ .ldr-sidebar-nav li {+ min-height: 26px;+ }+ .ldr-sidebar-nav li a {+ padding: 0.25rem 1rem;+ }+ .ldr-sidebar-section {+ margin-bottom: 0.35rem;+ }+ .ldr-sidebar-section-label {+ padding: 0.2rem 1rem 0.1rem 1rem;+ font-size: 0.6rem;+ }+}++@media (max-height: 700px) {+ .ldr-sidebar-header {+ padding: 0.35rem 0.75rem;+ }+ .ldr-sidebar-header h2 {+ font-size: 1rem;+ }+ .ldr-sidebar-nav li {+ min-height: 24px;+ }+ .ldr-sidebar-nav li a {+ padding: 0.2rem 0.75rem;+ font-size: 0.85rem;+ }+ .ldr-sidebar-section {+ margin-bottom: 0.25rem;+ }+ .ldr-sidebar-section-label {+ padding: 0.15rem 0.75rem 0.1rem 0.75rem;+ font-size: 0.55rem;+ }+ .ldr-sidebar-footer {+ padding: 0.5rem 0.75rem;+ }+}+/* Responsive */@media (max-width: 991px) {.ldr-sidebar {diff --git a/tests/ui_tests/mobile/test_layout_bugs_ci.js b/tests/ui_tests/mobile/test_layout_bugs_ci.jsnew file mode 100644index 0000000000..896803f8c9--- /dev/null+++ b/tests/ui_tests/mobile/test_layout_bugs_ci.js@@ -0,0 +1,793 @@+/**+ * Layout Bug Tests for CI+ *+ * Comprehensive automated tests that catch mobile and desktop UI layout bugs.+ * Uses geometry-based assertions that are reliable in headless CI environments.+ *+ * Run: node test_layout_bugs_ci.js+ *+ * Environment variables:+ * - BASE_URL: Server URL (default: http://localhost:5000)+ * - CI: Set to 'true' for CI mode (no screenshots on pass)+ * - OUTPUT_FORMAT: 'json' or 'junit' (default: json)+ * - HEADLESS: 'true' or 'false' (default: true)+ */++const puppeteer = require('puppeteer');+const fs = require('fs');+const path = require('path');+const AuthHelper = require('../auth_helper');++// Configuration+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:5000';+const IS_CI = process.env.CI === 'true';+const OUTPUT_FORMAT = process.env.OUTPUT_FORMAT || 'json';+const HEADLESS = process.env.HEADLESS !== 'false';++// Viewports to test - covers mobile, tablet, desktop, and short heights+// Note: The app uses 768px as mobile breakpoint, so 767px is mobile, 768px is tablet+const VIEWPORTS = {+ 'mobile_iPhone_SE': { width: 375, height: 667, isMobile: true },+ 'mobile_iPhone_14': { width: 430, height: 932, isMobile: true },+ 'tablet_iPad': { width: 768, height: 1024, isMobile: false }, // 768px = tablet (sidebar visible)+ 'desktop_normal': { width: 1280, height: 800, isMobile: false },+ 'desktop_short': { width: 1280, height: 600, isMobile: false },+ 'desktop_very_short': { width: 1280, height: 500, isMobile: false },+ 'desktop_wide': { width: 1920, height: 1080, isMobile: false },+};++// Pages to test (authenticated)+const AUTHENTICATED_PAGES = [+ { path: '/', name: 'Research' },+ { path: '/history/', name: 'History' },+ { path: '/news/', name: 'News' },+ { path: '/settings/', name: 'Settings' },+ { path: '/metrics/', name: 'Metrics' },+];++// Pages to test (unauthenticated)+const UNAUTHENTICATED_PAGES = [+ { path: '/auth/login', name: 'Login' },+];++// Test results collector+class TestResults {+ constructor() {+ this.tests = [];+ this.startTime = Date.now();+ }++ addResult(viewport, page, testName, passed, message = '', duration = 0) {+ this.tests.push({+ viewport,+ page,+ testName,+ passed,+ message,+ duration,+ timestamp: new Date().toISOString()+ });+ }++ get summary() {+ const total = this.tests.length;+ const passed = this.tests.filter(t => t.passed).length;+ const failed = total - passed;+ return { total, passed, failed, duration: Date.now() - this.startTime };+ }++ toJSON() {+ return {+ summary: this.summary,+ tests: this.tests+ };+ }++ toJUnitXML() {+ const { summary } = this;+ const testsByViewport = {};++ for (const test of this.tests) {+ if (!testsByViewport[test.viewport]) {+ testsByViewport[test.viewport] = [];+ }+ testsByViewport[test.viewport].push(test);+ }++ let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;+ xml += `<testsuites name="Layout Bug Tests" tests="${summary.total}" failures="${summary.failed}" time="${(summary.duration / 1000).toFixed(2)}">\n`;++ for (const [viewport, tests] of Object.entries(testsByViewport)) {+ const vpPassed = tests.filter(t => t.passed).length;+ const vpFailed = tests.length - vpPassed;+ const vpTime = tests.reduce((sum, t) => sum + t.duration, 0) / 1000;++ xml += ` <testsuite name="${viewport}" tests="${tests.length}" failures="${vpFailed}" time="${vpTime.toFixed(2)}">\n`;++ for (const test of tests) {+ xml += ` <testcase name="${test.page} - ${test.testName}" time="${(test.duration / 1000).toFixed(3)}"`;+ if (test.passed) {+ xml += ` />\n`;+ } else {+ xml += `>\n`;+ xml += ` <failure message="${escapeXml(test.message)}">${escapeXml(test.message)}</failure>\n`;+ xml += ` </testcase>\n`;+ }+ }++ xml += ` </testsuite>\n`;+ }++ xml += `</testsuites>\n`;+ return xml;+ }+}++function escapeXml(str) {+ return str+ .replace(/&/g, '&')+ .replace(/</g, '<')+ .replace(/>/g, '>')+ .replace(/"/g, '"')+ .replace(/'/g, ''');+}++// Layout assertions - all geometry-based, no animation dependencies+const Assertions = {+ /**+ * Check for horizontal overflow (content wider than viewport)+ */+ async noHorizontalOverflow(page) {+ const result = await page.evaluate(() => {+ const scrollWidth = document.documentElement.scrollWidth;+ const innerWidth = window.innerWidth;+ const overflow = scrollWidth - innerWidth;+ return {+ passed: overflow <= 5, // 5px tolerance for scrollbars+ scrollWidth,+ innerWidth,+ overflow+ };+ });+ return {+ passed: result.passed,+ message: result.passed+ ? 'No horizontal overflow'+ : `Horizontal overflow: ${result.overflow}px (scrollWidth=${result.scrollWidth}, innerWidth=${result.innerWidth})`+ };+ },++ /**+ * Check sidebar visibility matches expected state for viewport+ * - Mobile (<768px): sidebar hidden+ * - Tablet (768-991px): sidebar collapsed (60px)+ * - Desktop (≥992px): sidebar full width (200-240px)+ */+ async sidebarCorrectState(page, viewportName, viewportConfig) {+ const isMobileWidth = viewportConfig.width < 768;+ const isTabletWidth = viewportConfig.width >= 768 && viewportConfig.width <= 991;++ // On mobile, sidebar should be hidden+ // On tablet/desktop, sidebar should be visible (but may be collapsed on tablet)+ const shouldBeVisible = !isMobileWidth;++ const result = await page.evaluate(() => {+ const sidebar = document.querySelector('.ldr-sidebar');+ if (!sidebar) {+ return { exists: false, isVisible: false };+ }++ const style = window.getComputedStyle(sidebar);+ const rect = sidebar.getBoundingClientRect();++ // Check various ways sidebar could be hidden+ const displayNone = style.display === 'none';+ const visibilityHidden = style.visibility === 'hidden';+ const offScreen = rect.right <= 0;+ const zeroWidth = rect.width === 0;+ const transformHidden = style.transform && style.transform.includes('-100%');++ const isHidden = displayNone || visibilityHidden || offScreen || zeroWidth || transformHidden;++ return {+ exists: true,+ isVisible: !isHidden,+ display: style.display,+ visibility: style.visibility,+ width: rect.width,+ left: rect.left,+ right: rect.right+ };+ });++ if (!result.exists) {+ // Sidebar might not exist on some pages (like login)+ return { passed: true, message: 'Sidebar not present on page (expected for some pages)' };+ }++ // For tablet, sidebar should exist but may be collapsed (60px)+ if (isTabletWidth) {+ const isCollapsedOrVisible = result.width >= 50 || result.isVisible;+ return {+ passed: isCollapsedOrVisible,+ message: isCollapsedOrVisible+ ? `Sidebar correctly ${result.width >= 100 ? 'visible' : 'collapsed'} on tablet (width=${result.width}px)`+ : `Sidebar should be visible/collapsed on tablet but is hidden (width=${result.width}px)`+ };+ }++ const stateCorrect = result.isVisible === shouldBeVisible;+ const expectedState = shouldBeVisible ? 'visible' : 'hidden';+ const actualState = result.isVisible ? 'visible' : 'hidden';++ return {+ passed: stateCorrect,+ message: stateCorrect+ ? `Sidebar correctly ${expectedState}`+ : `Sidebar should be ${expectedState} but is ${actualState} (width=${result.width}, left=${result.left})`+ };+ },++ /**+ * Check mobile nav visibility matches expected state+ * @param {Page} page - Puppeteer page+ * @param {string} viewportName - Name of viewport+ * @param {object} viewportConfig - Viewport configuration+ * @param {boolean} isAuthenticatedPage - Whether this is an authenticated page+ */+ async mobileNavCorrectState(page, viewportName, viewportConfig, isAuthenticatedPage = true) {+ const isMobileWidth = viewportConfig.width < 768;++ // Mobile nav should only be visible on mobile widths AND authenticated pages+ // Unauthenticated pages (login, register) don't have mobile nav+ const shouldBeVisible = isMobileWidth && isAuthenticatedPage;++ const result = await page.evaluate(() => {+ const mobileNav = document.querySelector('.ldr-mobile-bottom-nav');+ if (!mobileNav) {+ return { exists: false, isVisible: false };+ }++ const style = window.getComputedStyle(mobileNav);+ const rect = mobileNav.getBoundingClientRect();++ const displayNone = style.display === 'none';+ const visibilityHidden = style.visibility === 'hidden';+ const offScreen = rect.top >= window.innerHeight;+ const zeroHeight = rect.height === 0;++ const isHidden = displayNone || visibilityHidden || offScreen || zeroHeight;++ return {+ exists: true,+ isVisible: !isHidden,+ display: style.display,+ visibility: style.visibility,+ height: rect.height,+ top: rect.top,+ bottom: rect.bottom+ };+ });++ if (!result.exists) {+ if (shouldBeVisible) {+ return { passed: false, message: 'Mobile nav should exist but is not found in DOM' };+ }+ // Not visible and not expected - that's correct+ const reason = !isAuthenticatedPage ? 'unauthenticated page' : 'desktop viewport';+ return { passed: true, message: `Mobile nav not present (expected for ${reason})` };+ }++ const stateCorrect = result.isVisible === shouldBeVisible;+ const expectedState = shouldBeVisible ? 'visible' : 'hidden';+ const actualState = result.isVisible ? 'visible' : 'hidden';++ return {+ passed: stateCorrect,+ message: stateCorrect+ ? `Mobile nav correctly ${expectedState}`+ : `Mobile nav should be ${expectedState} but is ${actualState} (height=${result.height}, top=${result.top})`+ };+ },++ /**+ * Check that all navigation items are accessible (Settings not cut off)+ * @param {Page} page - Puppeteer page+ * @param {object} viewportConfig - Viewport configuration+ * @param {boolean} isAuthenticatedPage - Whether this is an authenticated page+ */+ async allNavItemsAccessible(page, viewportConfig, isAuthenticatedPage = true) {+ const isMobileWidth = viewportConfig.width < 768;++ // Unauthenticated pages don't have navigation menus+ if (!isAuthenticatedPage) {+ return { passed: true, message: 'Navigation check skipped for unauthenticated page' };+ }++ if (isMobileWidth) {+ // For mobile, check that Settings items exist in the sheet menu+ // Note: Sheet menu uses <button> elements with data-action attributes, not <a> links+ const result = await page.evaluate(() => {+ const sheetMenu = document.querySelector('.ldr-mobile-sheet-menu');+ if (!sheetMenu) {+ return { exists: false, settingsFound: false };+ }++ // Look for Settings/Configuration buttons in sheet menu by data-action+ const allButtons = Array.from(sheetMenu.querySelectorAll('button[data-action], .ldr-mobile-sheet-item'));+ const settingsItems = allButtons.filter(btn => {+ const action = btn.getAttribute('data-action') || '';+ const text = btn.textContent.toLowerCase();+ return action.includes('/settings') ||+ action.includes('/embedding') ||+ text.includes('settings') ||+ text.includes('embeddings') ||+ text.includes('configuration');+ });++ // Also check for Settings section title+ const sectionTitles = Array.from(sheetMenu.querySelectorAll('.ldr-mobile-sheet-title, [class*="sheet-title"]'));+ const settingsSectionTitle = sectionTitles.find(el =>+ el.textContent.toLowerCase().includes('settings')+ );++ return {+ exists: true,+ settingsFound: settingsItems.length > 0 || !!settingsSectionTitle,+ settingsItemsCount: settingsItems.length,+ totalItems: allButtons.length,+ sheetHeight: sheetMenu.getBoundingClientRect().height,+ maxHeight: window.getComputedStyle(sheetMenu).maxHeight+ };+ });++ if (!result.exists) {+ return { passed: true, message: 'Sheet menu not on page (may not be needed)' };+ }++ return {+ passed: result.settingsFound,+ message: result.settingsFound+ ? `Settings accessible in mobile sheet menu (${result.settingsItemsCount} items found)`+ : `Settings items NOT found in mobile sheet menu (${result.totalItems} total items, height=${result.sheetHeight}px)`+ };+ } else {+ // For desktop/tablet, check sidebar can show all items+ const result = await page.evaluate(() => {+ const sidebar = document.querySelector('.ldr-sidebar');+ if (!sidebar) {+ return { exists: false };+ }++ const nav = sidebar.querySelector('.ldr-sidebar-nav');+ if (!nav) {+ return { exists: true, navExists: false };+ }++ // Get all nav items+ const items = Array.from(nav.querySelectorAll('li a'));++ // Check if Settings section exists+ const settingsSection = Array.from(sidebar.querySelectorAll('.ldr-sidebar-section-label'))+ .find(el => el.textContent.toLowerCase().includes('settings'));++ // Check if any Settings items exist+ const settingsItems = items.filter(a =>+ a.href.includes('settings') ||+ a.href.includes('embeddings') ||+ a.href.includes('configuration')+ );++ // Check if last item is visible (within viewport)+ const sidebarRect = sidebar.getBoundingClientRect();+ const viewportHeight = window.innerHeight;++ // Find the bottom-most item+ let lastItemBottom = 0;+ items.forEach(item => {+ const rect = item.getBoundingClientRect();+ if (rect.bottom > lastItemBottom) {+ lastItemBottom = rect.bottom;+ }+ });++ const isScrollable = nav.scrollHeight > nav.clientHeight;+ const allItemsInView = lastItemBottom <= viewportHeight;++ return {+ exists: true,+ navExists: true,+ totalItems: items.length,+ settingsSectionFound: !!settingsSection,+ settingsItemsCount: settingsItems.length,+ sidebarBottom: sidebarRect.bottom,+ lastItemBottom,+ viewportHeight,+ isScrollable,+ allItemsInView: allItemsInView || isScrollable // Either all visible or can scroll to them+ };+ });++ if (!result.exists) {+ return { passed: true, message: 'Sidebar not on page' };+ }++ if (!result.navExists) {+ return { passed: false, message: 'Sidebar exists but nav not found' };+ }++ // We need either Settings items visible OR the section to be scrollable+ const hasSettingsAccess = result.settingsItemsCount > 0 || result.settingsSectionFound;+ const canAccessAll = result.allItemsInView;++ return {+ passed: hasSettingsAccess && canAccessAll,+ message: hasSettingsAccess && canAccessAll+ ? `All ${result.totalItems} nav items accessible (Settings section found)`+ : `Nav items may be cut off: lastItemBottom=${result.lastItemBottom}px, viewportHeight=${result.viewportHeight}px, settingsFound=${hasSettingsAccess}`+ };+ }+ },++ /**+ * Check main content is not overlapped by navigation elements+ * @param {Page} page - Puppeteer page+ * @param {object} viewportConfig - Viewport configuration+ * @param {boolean} isAuthenticatedPage - Whether this is an authenticated page+ */+ async noContentBehindNav(page, viewportConfig, isAuthenticatedPage = true) {+ // Unauthenticated pages don't have the navigation overlay issue+ if (!isAuthenticatedPage) {+ return { passed: true, message: 'Content overlap check skipped for unauthenticated page' };+ }++ const isMobileWidth = viewportConfig.width < 768;++ const result = await page.evaluate((isMobile) => {+ // For mobile, check if the content has proper padding-bottom to account for fixed nav+ // For desktop, check if content properly avoids sidebar+ const mainContent = document.querySelector('main, .main-content, [role="main"], .container');+ if (!mainContent) {+ return { mainExists: false };+ }++ const mainStyle = window.getComputedStyle(mainContent);+ const viewportHeight = window.innerHeight;++ if (isMobile) {+ const mobileNav = document.querySelector('.ldr-mobile-bottom-nav');+ if (!mobileNav) {+ return { mainExists: true, navExists: false };+ }+ const navRect = mobileNav.getBoundingClientRect();+ const navStyle = window.getComputedStyle(mobileNav);++ if (navStyle.display === 'none' || navRect.height === 0) {+ return { mainExists: true, navExists: false };+ }++ // The nav is fixed at bottom, check if main content has padding to avoid it+ // Content naturally scrolls behind fixed elements, so we check padding instead+ const paddingBottom = parseFloat(mainStyle.paddingBottom) || 0;+ const marginBottom = parseFloat(mainStyle.marginBottom) || 0;+ const navHeight = navRect.height;++ // Content should have at least ~50px padding/margin to clear the nav+ // This ensures the last content isn't hidden behind the nav+ const hasSufficientSpacing = (paddingBottom + marginBottom) >= (navHeight - 10);++ return {+ mainExists: true,+ navExists: true,+ navHeight,+ paddingBottom,+ marginBottom,+ totalSpacing: paddingBottom + marginBottom,+ passed: hasSufficientSpacing+ };+ } else {+ const sidebar = document.querySelector('.ldr-sidebar');+ if (!sidebar) {+ return { mainExists: true, navExists: false };+ }+ const sidebarRect = sidebar.getBoundingClientRect();+ const sidebarStyle = window.getComputedStyle(sidebar);+ const mainRect = mainContent.getBoundingClientRect();++ if (sidebarStyle.display === 'none' || sidebarRect.width === 0) {+ return { mainExists: true, navExists: false };+ }++ // Check horizontal overlap+ const overlap = mainRect.left < sidebarRect.right ? sidebarRect.right - mainRect.left : 0;++ return {+ mainExists: true,+ navExists: true,+ mainLeft: mainRect.left,+ sidebarRight: sidebarRect.right,+ overlap,+ passed: overlap <= 10+ };+ }+ }, isMobileWidth);++ if (!result.mainExists) {+ return { passed: true, message: 'Main content area not found (may be expected)' };+ }++ if (!result.navExists) {+ return { passed: true, message: 'No navigation overlap (nav not present)' };+ }++ if (isMobileWidth) {+ return {+ passed: result.passed,+ message: result.passed+ ? `Content has proper spacing for mobile nav (spacing=${result.totalSpacing}px, navHeight=${result.navHeight}px)`+ : `Content needs more bottom padding for mobile nav (spacing=${result.totalSpacing}px < navHeight=${result.navHeight}px)`+ };+ }++ return {+ passed: result.passed,+ message: result.passed+ ? 'No content overlap with sidebar'+ : `Content overlaps sidebar by ${result.overlap}px`+ };+ },++ /**+ * Check touch targets are adequate size on mobile (warning only)+ */+ async touchTargetsAdequate(page, viewportConfig) {+ if (!viewportConfig.isMobile) {+ return { passed: true, message: 'Touch target check skipped for non-mobile viewport' };+ }++ const result = await page.evaluate(() => {+ const interactiveElements = document.querySelectorAll('button, a, input, [role="button"], [onclick]');+ const smallTargets = [];+ const MIN_SIZE = 40; // 40px minimum for touch targets++ interactiveElements.forEach((el, index) => {+ const rect = el.getBoundingClientRect();+ const style = window.getComputedStyle(el);++ // Skip hidden elements+ if (style.display === 'none' || style.visibility === 'hidden') {+ return;+ }++ // Skip elements with no size+ if (rect.width === 0 || rect.height === 0) {+ return;+ }++ if (rect.width < MIN_SIZE || rect.height < MIN_SIZE) {+ smallTargets.push({+ tag: el.tagName.toLowerCase(),+ text: el.textContent?.slice(0, 30) || '',+ width: Math.round(rect.width),+ height: Math.round(rect.height),+ classes: el.className?.split(' ').slice(0, 3).join(' ') || ''+ });+ }+ });++ return {+ total: interactiveElements.length,+ smallCount: smallTargets.length,+ smallTargets: smallTargets.slice(0, 5) // Limit to first 5+ };+ });++ // This is a warning, not a failure+ const passed = result.smallCount === 0;+ const message = passed+ ? `All ${result.total} touch targets are adequate size (≥40px)`+ : `Warning: ${result.smallCount} touch targets under 40px: ${result.smallTargets.map(t => `${t.tag}(${t.width}x${t.height})`).join(', ')}`;++ return { passed, message, isWarning: !passed };+ }+};++// Main test runner+class LayoutBugTests {+ constructor() {+ this.results = new TestResults();+ this.browser = null;+ this.page = null;+ this.authHelper = null;+ }++ async setup() {+ this.browser = await puppeteer.launch({+ headless: HEADLESS ? 'new' : false,+ args: ['--no-sandbox', '--disable-setuid-sandbox']+ });+ this.page = await this.browser.newPage();++ // Set a large viewport for authentication+ await this.page.setViewport({ width: 1280, height: 800 });++ // Use AuthHelper for authentication+ this.authHelper = new AuthHelper(this.page, BASE_URL);+ await this.authHelper.ensureAuthenticated();++ console.log('Authentication complete');+ }++ async runAllTests() {+ console.log('\n========================================');+ console.log(' Layout Bug Tests for CI');+ console.log('========================================\n');+ console.log(`Base URL: ${BASE_URL}`);+ console.log(`Viewports: ${Object.keys(VIEWPORTS).length}`);+ console.log(`Pages: ${AUTHENTICATED_PAGES.length + UNAUTHENTICATED_PAGES.length}`);+ console.log('');++ // Test authenticated pages+ for (const [viewportName, viewportConfig] of Object.entries(VIEWPORTS)) {+ console.log(`\n--- Testing viewport: ${viewportName} (${viewportConfig.width}x${viewportConfig.height}) ---`);++ await this.page.setViewport({+ width: viewportConfig.width,+ height: viewportConfig.height,+ isMobile: viewportConfig.isMobile,+ hasTouch: viewportConfig.isMobile+ });++ for (const pageInfo of AUTHENTICATED_PAGES) {+ await this.testPage(viewportName, viewportConfig, pageInfo);+ }+ }++ // Test unauthenticated pages (login page)+ // Create new incognito context for unauthenticated tests+ const incognitoContext = await this.browser.createBrowserContext();+ const incognitoPage = await incognitoContext.newPage();++ for (const [viewportName, viewportConfig] of Object.entries(VIEWPORTS)) {+ await incognitoPage.setViewport({+ width: viewportConfig.width,+ height: viewportConfig.height,+ isMobile: viewportConfig.isMobile,+ hasTouch: viewportConfig.isMobile+ });++ for (const pageInfo of UNAUTHENTICATED_PAGES) {+ // Pass false for isAuthenticatedPage+ await this.testPageWithPage(incognitoPage, viewportName, viewportConfig, pageInfo, false);+ }+ }++ await incognitoContext.close();++ return this.results;+ }++ async testPage(viewportName, viewportConfig, pageInfo, isAuthenticatedPage = true) {+ return this.testPageWithPage(this.page, viewportName, viewportConfig, pageInfo, isAuthenticatedPage);+ }++ async testPageWithPage(page, viewportName, viewportConfig, pageInfo, isAuthenticatedPage = true) {+ const url = `${BASE_URL}${pageInfo.path}`;++ try {+ await page.goto(url, { waitUntil: 'networkidle2', timeout: 30000 });+ // Small delay to ensure CSS is fully applied+ await new Promise(resolve => setTimeout(resolve, 500));+ } catch (error) {+ this.results.addResult(viewportName, pageInfo.name, 'Page Load', false, `Failed to load: ${error.message}`);+ return;+ }++ // Run all assertions - pass isAuthenticatedPage to relevant checks+ const assertions = [+ { name: 'No Horizontal Overflow', fn: () => Assertions.noHorizontalOverflow(page) },+ { name: 'Sidebar State', fn: () => Assertions.sidebarCorrectState(page, viewportName, viewportConfig) },+ { name: 'Mobile Nav State', fn: () => Assertions.mobileNavCorrectState(page, viewportName, viewportConfig, isAuthenticatedPage) },+ { name: 'All Nav Items Accessible', fn: () => Assertions.allNavItemsAccessible(page, viewportConfig, isAuthenticatedPage) },+ { name: 'No Content Behind Nav', fn: () => Assertions.noContentBehindNav(page, viewportConfig, isAuthenticatedPage) },+ { name: 'Touch Targets', fn: () => Assertions.touchTargetsAdequate(page, viewportConfig) },+ ];++ for (const assertion of assertions) {+ const startTime = Date.now();+ try {+ const result = await assertion.fn();+ const duration = Date.now() - startTime;++ const icon = result.passed ? '✓' : (result.isWarning ? '⚠' : '✗');+ console.log(` ${icon} ${pageInfo.name} - ${assertion.name}: ${result.message}`);++ // Treat warnings as passes for CI+ this.results.addResult(+ viewportName,+ pageInfo.name,+ assertion.name,+ result.passed || result.isWarning,+ result.message,+ duration+ );+ } catch (error) {+ const duration = Date.now() - startTime;+ console.log(` ✗ ${pageInfo.name} - ${assertion.name}: Error - ${error.message}`);+ this.results.addResult(viewportName, pageInfo.name, assertion.name, false, `Error: ${error.message}`, duration);+ }+ }+ }++ async cleanup() {+ if (this.browser) {+ await this.browser.close();+ }+ }+}++// Output helpers+function writeResults(results) {+ const outputDir = path.join(__dirname, 'test-results');+ if (!fs.existsSync(outputDir)) {+ fs.mkdirSync(outputDir, { recursive: true });+ }++ // Always write JSON+ const jsonPath = path.join(outputDir, 'layout-tests.json');+ fs.writeFileSync(jsonPath, JSON.stringify(results.toJSON(), null, 2));+ console.log(`\nJSON results: ${jsonPath}`);++ // Write JUnit XML if requested+ if (OUTPUT_FORMAT === 'junit' || IS_CI) {+ const xmlPath = path.join(outputDir, 'layout-tests.xml');+ fs.writeFileSync(xmlPath, results.toJUnitXML());+ console.log(`JUnit XML: ${xmlPath}`);+ }+}++function printSummary(results) {+ const { summary } = results;++ console.log('\n========================================');+ console.log(' Test Summary');+ console.log('========================================');+ console.log(` Total: ${summary.total}`);+ console.log(` Passed: ${summary.passed} (${((summary.passed / summary.total) * 100).toFixed(1)}%)`);+ console.log(` Failed: ${summary.failed}`);+ console.log(` Time: ${(summary.duration / 1000).toFixed(2)}s`);+ console.log('========================================\n');++ if (summary.failed > 0) {+ console.log('Failed Tests:');+ for (const test of results.tests.filter(t => !t.passed)) {+ console.log(` ✗ [${test.viewport}] ${test.page} - ${test.testName}`);+ console.log(` ${test.message}`);+ }+ console.log('');+ }+}++// Main execution+async function main() {+ const tester = new LayoutBugTests();++ try {+ await tester.setup();+ const results = await tester.runAllTests();++ printSummary(results);+ writeResults(results);++ // Exit with error code if tests failed+ const exitCode = results.summary.failed > 0 ? 1 : 0;+ process.exit(exitCode);+ } catch (error) {+ console.error('Fatal error:', error);+ process.exit(1);+ } finally {+ await tester.cleanup();+ }+}++main();diff --git a/tests/ui_tests/mobile/test_mobile_all_pages_ci.js b/tests/ui_tests/mobile/test_mobile_all_pages_ci.jsnew file mode 100644index 0000000000..1e52154e6e--- /dev/null+++ b/tests/ui_tests/mobile/test_mobile_all_pages_ci.js@@ -0,0 +1,338 @@+#!/usr/bin/env node+/**+ * Comprehensive Mobile UI CI Test+ * Tests all pages for mobile UI issues with proper assertions+ *+ * Features:+ * - Tests all pages at multiple mobile viewports+ * - Checks for horizontal overflow, touch targets, mobile nav+ * - Verifies sheet menu shows all sections including Settings+ * - Generates JSON/JUnit reports for CI+ */++const puppeteer = require('puppeteer');+const AuthHelper = require('../auth_helper');+const { getPuppeteerLaunchOptions } = require('../puppeteer_config');+const path = require('path');+const fs = require('fs').promises;++// Test configuration+const CONFIG = {+ baseUrl: process.env.TEST_BASE_URL || 'http://127.0.0.1:5000',+ timeout: 30000,+ outputFormat: process.env.OUTPUT_FORMAT || 'json',+};++// Mobile viewports to test+const VIEWPORTS = {+ 'iPhone_SE': { width: 375, height: 667, isMobile: true, hasTouch: true },+ 'iPhone_14_Pro': { width: 430, height: 932, isMobile: true, hasTouch: true },+};++// Pages to test+const PAGES = [+ { path: '/', name: 'Research', requiresAuth: true },+ { path: '/history/', name: 'History', requiresAuth: true },+ { path: '/news/', name: 'News', requiresAuth: true },+ { path: '/news/subscriptions', name: 'Subscriptions', requiresAuth: true },+ { path: '/settings/', name: 'Settings', requiresAuth: true },+ { path: '/metrics/', name: 'Metrics', requiresAuth: true },+ { path: '/benchmark/', name: 'Benchmark', requiresAuth: true },+ { path: '/settings/collections', name: 'Collections', requiresAuth: true },+ { path: '/auth/login', name: 'Login', requiresAuth: false },+];++class MobileAllPagesTest {+ constructor() {+ this.results = {+ startTime: new Date(),+ tests: [],+ summary: { total: 0, passed: 0, failed: 0 }+ };+ }++ async run() {+ console.log('🚀 Mobile UI CI Test - All Pages');+ console.log('='.repeat(50));++ let browser;+ try {+ browser = await puppeteer.launch(getPuppeteerLaunchOptions());++ for (const [deviceName, viewport] of Object.entries(VIEWPORTS)) {+ await this.testDevice(browser, deviceName, viewport);+ }++ await this.outputResults();+ process.exit(this.results.summary.failed > 0 ? 1 : 0);++ } catch (error) {+ console.error('❌ Test suite failed:', error);+ process.exit(1);+ } finally {+ if (browser) await browser.close();+ }+ }++ async testDevice(browser, deviceName, viewport) {+ console.log(`\n📱 Testing ${deviceName} (${viewport.width}x${viewport.height})`);+ console.log('─'.repeat(50));++ const page = await browser.newPage();+ await page.setViewport(viewport);++ // Authenticate+ const authHelper = new AuthHelper(page, CONFIG.baseUrl);+ try {+ await authHelper.ensureAuthenticated();+ } catch (error) {+ console.log(' ⚠️ Authentication failed, testing unauthenticated pages only');+ }++ // Test each page+ for (const pageInfo of PAGES) {+ await this.testPage(page, deviceName, pageInfo);+ }++ // Test sheet menu specifically+ await this.testSheetMenu(page, deviceName);++ await page.close();+ }++ async testPage(page, deviceName, pageInfo) {+ const testName = `${deviceName}/${pageInfo.name}`;+ const startTime = Date.now();++ try {+ await page.goto(CONFIG.baseUrl + pageInfo.path, {+ waitUntil: 'networkidle2',+ timeout: CONFIG.timeout+ });++ // Wait for mobile nav to initialize+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Run all checks+ const checks = await page.evaluate(() => {+ const results = {+ horizontalOverflow: false,+ mobileNavExists: false,+ mobileNavVisible: false,+ sidebarHidden: true,+ smallTouchTargets: 0,+ errors: []+ };++ // Check horizontal overflow+ if (document.body.scrollWidth > window.innerWidth + 5) {+ results.horizontalOverflow = true;+ results.errors.push(`Horizontal overflow: ${document.body.scrollWidth}px > ${window.innerWidth}px`);+ }++ // Check mobile nav+ const mobileNav = document.querySelector('.ldr-mobile-bottom-nav');+ results.mobileNavExists = !!mobileNav;+ if (mobileNav) {+ const style = window.getComputedStyle(mobileNav);+ results.mobileNavVisible = style.display !== 'none' &&+ mobileNav.classList.contains('visible');+ }++ // Check sidebar is hidden on mobile+ const sidebar = document.querySelector('.ldr-sidebar');+ if (sidebar) {+ const style = window.getComputedStyle(sidebar);+ results.sidebarHidden = style.display === 'none' ||+ style.visibility === 'hidden';+ if (!results.sidebarHidden && window.innerWidth <= 768) {+ results.errors.push('Desktop sidebar visible on mobile');+ }+ }++ // Check touch targets (only count critical ones)+ document.querySelectorAll('button:not([disabled]), a:not([disabled]), input:not([type="hidden"])').forEach(el => {+ const rect = el.getBoundingClientRect();+ if (rect.width > 0 && rect.height > 0 && rect.width < 40 && rect.height < 40) {+ results.smallTouchTargets++;+ }+ });++ return results;+ });++ // Determine test result+ let passed = true;+ const issues = [];++ if (checks.horizontalOverflow) {+ passed = false;+ issues.push('Horizontal overflow detected');+ }++ // Only check mobile nav on authenticated pages (login page won't have it)+ if (pageInfo.requiresAuth && !checks.mobileNavVisible) {+ // Check if we're actually on the page (not redirected to login)+ const currentUrl = page.url();+ if (!currentUrl.includes('/auth/')) {+ passed = false;+ issues.push('Mobile navigation not visible');+ }+ }++ if (!checks.sidebarHidden) {+ passed = false;+ issues.push('Desktop sidebar visible on mobile');+ }++ // Warnings (don't fail test)+ if (checks.smallTouchTargets > 10) {+ issues.push(`${checks.smallTouchTargets} small touch targets (warning)`);+ }++ this.addResult(testName, passed, issues, Date.now() - startTime);++ const status = passed ? '✅' : '❌';+ console.log(` ${status} ${pageInfo.name} ${issues.length > 0 ? '- ' + issues.join(', ') : ''}`);++ } catch (error) {+ this.addResult(testName, false, [error.message], Date.now() - startTime);+ console.log(` ❌ ${pageInfo.name} - Error: ${error.message}`);+ }+ }++ async testSheetMenu(page, deviceName) {+ const testName = `${deviceName}/SheetMenu`;+ const startTime = Date.now();++ try {+ // Navigate to a page with mobile nav+ await page.goto(CONFIG.baseUrl + '/news/', {+ waitUntil: 'networkidle2',+ timeout: CONFIG.timeout+ });+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Click More button to open sheet+ const moreBtn = await page.$('.ldr-mobile-nav-tab[data-tab-id="more"]');+ if (!moreBtn) {+ this.addResult(testName, false, ['More button not found'], Date.now() - startTime);+ console.log(` ❌ SheetMenu - More button not found`);+ return;+ }++ await moreBtn.click();+ await new Promise(resolve => setTimeout(resolve, 500));++ // Check if sheet opened and Settings section is visible+ const sheetStatus = await page.evaluate(() => {+ const sheet = document.querySelector('.ldr-mobile-sheet-menu');+ if (!sheet || !sheet.classList.contains('active')) {+ return { opened: false, error: 'Sheet did not open' };+ }++ const sheetContent = document.querySelector('.ldr-mobile-sheet-content');+ const settingsTitle = Array.from(sheetContent?.querySelectorAll('.ldr-mobile-sheet-title') || [])+ .find(el => el.textContent.includes('Settings'));++ if (!settingsTitle) {+ return { opened: true, settingsVisible: false, error: 'Settings section not found' };+ }++ const titleRect = settingsTitle.getBoundingClientRect();+ const sheetRect = sheetContent.getBoundingClientRect();++ // Settings should be within the visible sheet area (or scrollable to)+ const isAccessible = titleRect.top < sheetRect.bottom + 200; // Allow some scroll++ return {+ opened: true,+ settingsVisible: isAccessible,+ settingsPosition: titleRect.top,+ sheetBottom: sheetRect.bottom+ };+ });++ if (!sheetStatus.opened) {+ this.addResult(testName, false, [sheetStatus.error], Date.now() - startTime);+ console.log(` ❌ SheetMenu - ${sheetStatus.error}`);+ } else if (!sheetStatus.settingsVisible) {+ this.addResult(testName, false, ['Settings section cut off/not accessible'], Date.now() - startTime);+ console.log(` ❌ SheetMenu - Settings section not accessible`);+ } else {+ this.addResult(testName, true, [], Date.now() - startTime);+ console.log(` ✅ SheetMenu - Settings section accessible`);+ }++ // Close sheet+ const overlay = await page.$('.ldr-mobile-sheet-overlay');+ if (overlay) await overlay.click();++ } catch (error) {+ this.addResult(testName, false, [error.message], Date.now() - startTime);+ console.log(` ❌ SheetMenu - Error: ${error.message}`);+ }+ }++ addResult(name, passed, issues, duration) {+ this.results.tests.push({+ name,+ status: passed ? 'passed' : 'failed',+ issues,+ duration: duration / 1000+ });+ this.results.summary.total++;+ this.results.summary[passed ? 'passed' : 'failed']++;+ }++ async outputResults() {+ this.results.endTime = new Date();+ this.results.duration = (this.results.endTime - this.results.startTime) / 1000;++ console.log('\n' + '='.repeat(50));+ console.log('TEST RESULTS');+ console.log('='.repeat(50));+ console.log(`Total: ${this.results.summary.total}`);+ console.log(`Passed: ${this.results.summary.passed}`);+ console.log(`Failed: ${this.results.summary.failed}`);+ console.log(`Duration: ${this.results.duration.toFixed(2)}s`);++ if (this.results.summary.failed > 0) {+ console.log('\n❌ FAILED TESTS:');+ this.results.tests.filter(t => t.status === 'failed').forEach(t => {+ console.log(` - ${t.name}: ${t.issues.join(', ')}`);+ });+ }++ // Save results+ if (CONFIG.outputFormat === 'json') {+ await fs.writeFile('./mobile-test-results.json', JSON.stringify(this.results, null, 2));+ console.log('\n📁 Results saved to mobile-test-results.json');+ } else if (CONFIG.outputFormat === 'junit') {+ await fs.writeFile('./mobile-test-results.xml', this.toJUnit());+ console.log('\n📁 Results saved to mobile-test-results.xml');+ }+ }++ toJUnit() {+ let xml = `<?xml version="1.0" encoding="UTF-8"?>\n`;+ xml += `<testsuites name="Mobile UI Tests" tests="${this.results.summary.total}" failures="${this.results.summary.failed}" time="${this.results.duration}">\n`;+ xml += ` <testsuite name="MobileAllPages" tests="${this.results.summary.total}" failures="${this.results.summary.failed}">\n`;++ for (const test of this.results.tests) {+ xml += ` <testcase name="${test.name}" time="${test.duration}">\n`;+ if (test.status === 'failed') {+ xml += ` <failure message="${test.issues.join('; ')}">${test.issues.join('\n')}</failure>\n`;+ }+ xml += ` </testcase>\n`;+ }++ xml += ` </testsuite>\n`;+ xml += `</testsuites>`;+ return xml;+ }+}++// Run+const test = new MobileAllPagesTest();+test.run();diff --git a/tests/ui_tests/mobile/test_mobile_diagnostic.js b/tests/ui_tests/mobile/test_mobile_diagnostic.jsnew file mode 100644index 0000000000..93fa555740--- /dev/null+++ b/tests/ui_tests/mobile/test_mobile_diagnostic.js@@ -0,0 +1,468 @@+#!/usr/bin/env node+/**+ * Mobile UI Diagnostic Screenshot Tool+ *+ * Purpose: Generate annotated screenshots for manual review (LOCAL ONLY - not for CI)+ *+ * Features:+ * - Takes screenshots at multiple mobile viewports+ * - Annotates problem areas visually+ * - Opens sheet menu and captures it+ * - Generates HTML report+ *+ * Usage: node test_mobile_diagnostic.js+ */++const puppeteer = require('puppeteer');+const AuthHelper = require('../auth_helper');+const path = require('path');+const fs = require('fs').promises;++// Skip in CI+if (process.env.CI) {+ console.log('⏭️ Skipping diagnostic tool in CI environment');+ process.exit(0);+}++// Test devices+const DEVICES = {+ 'iPhone_SE': {+ width: 375,+ height: 667,+ deviceScaleFactor: 2,+ isMobile: true,+ hasTouch: true+ },+ 'iPhone_14_Pro': {+ width: 430,+ height: 932,+ deviceScaleFactor: 3,+ isMobile: true,+ hasTouch: true+ },+ 'iPad_Mini': {+ width: 768,+ height: 1024,+ deviceScaleFactor: 2,+ isMobile: true,+ hasTouch: true+ }+};++// All pages to test+const PAGES = [+ { path: '/', name: 'Research', requiresAuth: true },+ { path: '/history/', name: 'History', requiresAuth: true },+ { path: '/news/', name: 'News', requiresAuth: true },+ { path: '/news/subscriptions', name: 'Subscriptions', requiresAuth: true },+ { path: '/settings/', name: 'Settings', requiresAuth: true },+ { path: '/metrics/', name: 'Metrics', requiresAuth: true },+ { path: '/metrics/context-overflow', name: 'Metrics_Context', requiresAuth: true },+ { path: '/metrics/costs', name: 'Metrics_Costs', requiresAuth: true },+ { path: '/benchmark/', name: 'Benchmark', requiresAuth: true },+ { path: '/settings/collections', name: 'Collections', requiresAuth: true },+ { path: '/library/', name: 'Library', requiresAuth: true },+ { path: '/auth/login', name: 'Login', requiresAuth: false },+ { path: '/auth/register', name: 'Register', requiresAuth: false },+];++class MobileDiagnosticTool {+ constructor() {+ this.baseUrl = process.env.TEST_BASE_URL || 'http://127.0.0.1:5000';+ this.timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, -5);+ this.outputDir = path.join(__dirname, 'diagnostic-screenshots', this.timestamp);+ this.results = [];+ }++ async run() {+ console.log('🔍 Mobile UI Diagnostic Tool');+ console.log('=' .repeat(60));+ console.log(`📁 Output: ${this.outputDir}`);+ console.log('=' .repeat(60));++ await fs.mkdir(this.outputDir, { recursive: true });++ let browser;+ try {+ browser = await puppeteer.launch({+ headless: process.env.HEADLESS !== 'false',+ args: ['--no-sandbox', '--disable-setuid-sandbox']+ });++ for (const [deviceName, viewport] of Object.entries(DEVICES)) {+ await this.testDevice(browser, deviceName, viewport);+ }++ await this.generateReport();+ console.log('\n✅ Diagnostic complete!');+ console.log(`📁 View report: file://${path.join(this.outputDir, 'report.html')}`);++ } finally {+ if (browser) await browser.close();+ }+ }++ async testDevice(browser, deviceName, viewport) {+ console.log(`\n📱 Testing ${deviceName} (${viewport.width}x${viewport.height})`);+ console.log('─'.repeat(50));++ const deviceDir = path.join(this.outputDir, deviceName);+ await fs.mkdir(deviceDir, { recursive: true });++ const page = await browser.newPage();+ await page.setViewport(viewport);++ // Authenticate+ const authHelper = new AuthHelper(page, this.baseUrl);+ try {+ await authHelper.ensureAuthenticated();+ console.log(' ✅ Authenticated');+ } catch (error) {+ console.log(' ⚠️ Authentication failed:', error.message);+ }++ for (const pageInfo of PAGES) {+ await this.testPage(page, deviceName, deviceDir, pageInfo);+ }++ // Test sheet menu+ await this.testSheetMenu(page, deviceName, deviceDir);++ await page.close();+ }++ async testPage(page, deviceName, deviceDir, pageInfo) {+ console.log(` 📄 ${pageInfo.name}...`);++ try {+ await page.goto(this.baseUrl + pageInfo.path, {+ waitUntil: 'networkidle2',+ timeout: 30000+ });++ // Wait for mobile nav to initialize+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Run diagnostic checks+ const diagnostics = await page.evaluate(() => {+ const issues = [];++ // Check for horizontal scroll+ if (document.body.scrollWidth > window.innerWidth) {+ issues.push({+ type: 'horizontal-scroll',+ severity: 'error',+ message: `Horizontal scroll detected: ${document.body.scrollWidth}px > ${window.innerWidth}px`+ });+ }++ // Check touch targets+ const smallTargets = [];+ document.querySelectorAll('button, a, input, select, textarea').forEach(el => {+ const rect = el.getBoundingClientRect();+ if (rect.width > 0 && rect.height > 0) {+ if (rect.width < 44 || rect.height < 44) {+ smallTargets.push({+ tag: el.tagName,+ text: el.textContent?.slice(0, 20) || el.placeholder || '',+ size: `${Math.round(rect.width)}x${Math.round(rect.height)}`,+ rect: { top: rect.top, left: rect.left, width: rect.width, height: rect.height }+ });+ }+ }+ });+ if (smallTargets.length > 0) {+ issues.push({+ type: 'small-touch-targets',+ severity: 'warning',+ message: `${smallTargets.length} elements smaller than 44x44px`,+ details: smallTargets.slice(0, 5)+ });+ }++ // Check small text+ const smallText = [];+ document.querySelectorAll('p, span, label, h1, h2, h3, h4, h5, h6, a, button').forEach(el => {+ const style = window.getComputedStyle(el);+ const fontSize = parseFloat(style.fontSize);+ if (fontSize > 0 && fontSize < 12 && el.textContent?.trim()) {+ smallText.push({+ tag: el.tagName,+ text: el.textContent.slice(0, 30),+ fontSize: Math.round(fontSize)+ });+ }+ });+ if (smallText.length > 0) {+ issues.push({+ type: 'small-text',+ severity: 'warning',+ message: `${smallText.length} elements with font size < 12px`,+ details: smallText.slice(0, 5)+ });+ }++ // Check mobile nav+ const mobileNav = document.querySelector('.ldr-mobile-bottom-nav');+ const mobileNavVisible = mobileNav &&+ window.getComputedStyle(mobileNav).display !== 'none' &&+ mobileNav.classList.contains('visible');++ // Check if content is hidden behind nav+ const mainContent = document.querySelector('.ldr-main-content, .ldr-page.active, main');+ let contentHiddenBehindNav = false;+ if (mainContent && mobileNav) {+ const contentRect = mainContent.getBoundingClientRect();+ const navRect = mobileNav.getBoundingClientRect();+ if (contentRect.bottom > navRect.top) {+ contentHiddenBehindNav = true;+ issues.push({+ type: 'content-behind-nav',+ severity: 'error',+ message: 'Content may be hidden behind mobile navigation'+ });+ }+ }++ // Check sidebar+ const sidebar = document.querySelector('.ldr-sidebar');+ const sidebarVisible = sidebar &&+ window.getComputedStyle(sidebar).display !== 'none';+ if (sidebarVisible && window.innerWidth <= 768) {+ issues.push({+ type: 'sidebar-visible-on-mobile',+ severity: 'error',+ message: 'Desktop sidebar is visible on mobile viewport'+ });+ }++ return {+ url: window.location.href,+ title: document.title,+ viewport: { width: window.innerWidth, height: window.innerHeight },+ mobileNav: {+ exists: !!mobileNav,+ visible: mobileNavVisible+ },+ sidebar: {+ exists: !!sidebar,+ visible: sidebarVisible+ },+ issues: issues+ };+ });++ // Annotate issues on page+ if (diagnostics.issues.length > 0) {+ await this.annotateIssues(page, diagnostics.issues);+ }++ // Take screenshot+ const screenshotPath = path.join(deviceDir, `${pageInfo.name}.png`);+ await page.screenshot({ path: screenshotPath, fullPage: false });++ // Store results+ this.results.push({+ device: deviceName,+ page: pageInfo.name,+ path: pageInfo.path,+ screenshot: path.relative(this.outputDir, screenshotPath),+ diagnostics: diagnostics+ });++ const issueCount = diagnostics.issues.length;+ const status = issueCount === 0 ? '✅' : issueCount > 2 ? '❌' : '⚠️';+ console.log(` ${status} ${issueCount} issues | Nav: ${diagnostics.mobileNav.visible ? '✅' : '❌'}`);++ } catch (error) {+ console.log(` ❌ Error: ${error.message}`);+ this.results.push({+ device: deviceName,+ page: pageInfo.name,+ path: pageInfo.path,+ error: error.message+ });+ }+ }++ async annotateIssues(page, issues) {+ await page.evaluate((issues) => {+ // Remove previous annotations+ document.querySelectorAll('.diagnostic-annotation').forEach(el => el.remove());++ issues.forEach(issue => {+ if (issue.type === 'small-touch-targets' && issue.details) {+ issue.details.forEach(target => {+ const annotation = document.createElement('div');+ annotation.className = 'diagnostic-annotation';+ annotation.style.cssText = `+ position: fixed;+ top: ${target.rect.top}px;+ left: ${target.rect.left}px;+ width: ${target.rect.width}px;+ height: ${target.rect.height}px;+ border: 2px dashed orange;+ background: rgba(255, 165, 0, 0.2);+ pointer-events: none;+ z-index: 99999;+ `;+ document.body.appendChild(annotation);+ });+ }+ });+ }, issues);+ }++ async testSheetMenu(page, deviceName, deviceDir) {+ console.log(' 📋 Testing sheet menu...');++ try {+ // Navigate to a page with mobile nav+ await page.goto(this.baseUrl + '/news/', {+ waitUntil: 'networkidle2',+ timeout: 30000+ });+ await new Promise(resolve => setTimeout(resolve, 1000));++ // Click More button to open sheet+ const moreBtn = await page.$('.ldr-mobile-nav-tab[data-tab-id="more"]');+ if (moreBtn) {+ await moreBtn.click();+ await new Promise(resolve => setTimeout(resolve, 500));++ // Check if sheet opened+ const sheetOpen = await page.evaluate(() => {+ const sheet = document.querySelector('.ldr-mobile-sheet-menu');+ return sheet && sheet.classList.contains('active');+ });++ if (sheetOpen) {+ // Check if Settings section is visible (the one that was getting cut off)+ const settingsVisible = await page.evaluate(() => {+ const sheet = document.querySelector('.ldr-mobile-sheet-content');+ const settingsSection = Array.from(sheet?.querySelectorAll('.ldr-mobile-sheet-title') || [])+ .find(el => el.textContent.includes('Settings'));++ if (!settingsSection) return { found: false };++ const rect = settingsSection.getBoundingClientRect();+ const sheetRect = sheet.getBoundingClientRect();++ return {+ found: true,+ visible: rect.top < sheetRect.bottom,+ position: { top: rect.top, sheetBottom: sheetRect.bottom }+ };+ });++ // Take screenshot of open sheet+ const screenshotPath = path.join(deviceDir, 'SheetMenu_Open.png');+ await page.screenshot({ path: screenshotPath, fullPage: false });++ this.results.push({+ device: deviceName,+ page: 'SheetMenu',+ path: 'N/A',+ screenshot: path.relative(this.outputDir, screenshotPath),+ diagnostics: {+ sheetMenu: {+ opened: true,+ settingsVisible: settingsVisible.visible,+ settingsDetails: settingsVisible+ }+ }+ });++ const status = settingsVisible.visible ? '✅' : '❌';+ console.log(` ${status} Settings section ${settingsVisible.visible ? 'visible' : 'CUT OFF!'}`);++ // Close sheet+ const overlay = await page.$('.ldr-mobile-sheet-overlay');+ if (overlay) await overlay.click();+ } else {+ console.log(' ⚠️ Sheet menu did not open');+ }+ } else {+ console.log(' ⚠️ More button not found');+ }+ } catch (error) {+ console.log(` ❌ Error testing sheet menu: ${error.message}`);+ }+ }++ async generateReport() {+ const reportPath = path.join(this.outputDir, 'report.html');++ const html = `<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Mobile UI Diagnostic Report - ${this.timestamp}</title>+ <style>+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; margin: 0; padding: 20px; background: #1a1a2e; color: #eee; }+ h1 { color: #6e4ff6; }+ h2 { color: #40bfff; border-bottom: 1px solid #333; padding-bottom: 10px; }+ .device-section { margin: 30px 0; }+ .page-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 20px; }+ .page-card { background: #252540; border-radius: 12px; overflow: hidden; }+ .page-card img { width: 100%; height: auto; border-bottom: 1px solid #333; }+ .page-info { padding: 15px; }+ .page-name { font-weight: bold; font-size: 16px; margin-bottom: 10px; }+ .issue { padding: 8px 12px; margin: 5px 0; border-radius: 6px; font-size: 13px; }+ .issue.error { background: rgba(250, 92, 124, 0.2); border-left: 3px solid #fa5c7c; }+ .issue.warning { background: rgba(249, 188, 11, 0.2); border-left: 3px solid #f9bc0b; }+ .status { display: inline-block; padding: 4px 8px; border-radius: 4px; font-size: 12px; }+ .status.ok { background: #0acf97; color: #000; }+ .status.error { background: #fa5c7c; }+ .status.warning { background: #f9bc0b; color: #000; }+ .nav-status { margin-top: 10px; font-size: 13px; }+ .summary { background: #252540; padding: 20px; border-radius: 12px; margin-bottom: 30px; }+ </style>+</head>+<body>+ <h1>📱 Mobile UI Diagnostic Report</h1>+ <p>Generated: ${new Date().toISOString()}</p>++ <div class="summary">+ <h2>Summary</h2>+ <p>Total pages tested: ${this.results.length}</p>+ <p>Pages with errors: ${this.results.filter(r => r.diagnostics?.issues?.some(i => i.severity === 'error')).length}</p>+ <p>Pages with warnings: ${this.results.filter(r => r.diagnostics?.issues?.some(i => i.severity === 'warning')).length}</p>+ </div>++ ${Object.entries(DEVICES).map(([deviceName]) => `+ <div class="device-section">+ <h2>📱 ${deviceName}</h2>+ <div class="page-grid">+ ${this.results.filter(r => r.device === deviceName).map(result => `+ <div class="page-card">+ ${result.screenshot ? `<img src="${result.screenshot}" alt="${result.page}">` : ''}+ <div class="page-info">+ <div class="page-name">${result.page}</div>+ ${result.error ? `<div class="issue error">Error: ${result.error}</div>` : ''}+ ${result.diagnostics?.issues?.map(issue => `+ <div class="issue ${issue.severity}">${issue.message}</div>+ `).join('') || ''}+ <div class="nav-status">+ Mobile Nav: ${result.diagnostics?.mobileNav?.visible ? '✅ Visible' : '❌ Hidden/Missing'}+ </div>+ </div>+ </div>+ `).join('')}+ </div>+ </div>+ `).join('')}+</body>+</html>`;++ await fs.writeFile(reportPath, html);+ }+}++// Run+const tool = new MobileDiagnosticTool();+tool.run().catch(error => {+ console.error('❌ Diagnostic tool failed:', error);+ process.exit(1);+});diff --git a/tests/ui_tests/mobile/test_mobile_nav_all_pages.js b/tests/ui_tests/mobile/test_mobile_nav_all_pages.jsindex e2ad340bec..908900682d 100644--- a/tests/ui_tests/mobile/test_mobile_nav_all_pages.js+++ b/tests/ui_tests/mobile/test_mobile_nav_all_pages.js@@ -122,10 +122,10 @@ async function testAllPages() {// Capture page infoconst pageAnalysis = await page.evaluate(() => {const getMobileNavInfo = () => {- const nav = document.querySelector('.mobile-bottom-nav');- const sheet = document.querySelector('.mobile-sheet-menu');+ const nav = document.querySelector('.ldr-mobile-bottom-nav');+ const sheet = document.querySelector('.ldr-mobile-sheet-menu');const tabBar = document.querySelector('.mobile-tab-bar');- const sidebar = document.querySelector('.sidebar');+ const sidebar = document.querySelector('.ldr-sidebar');return {hasMobileNav: !!nav,@@ -199,10 +199,10 @@ async function testAllPages() {// Analyze pageconst pageAnalysis = await page.evaluate(() => {const getMobileNavInfo = () => {- const nav = document.querySelector('.mobile-bottom-nav');- const sheet = document.querySelector('.mobile-sheet-menu');+ const nav = document.querySelector('.ldr-mobile-bottom-nav');+ const sheet = document.querySelector('.ldr-mobile-sheet-menu');const tabBar = document.querySelector('.mobile-tab-bar');- const sidebar = document.querySelector('.sidebar');+ const sidebar = document.querySelector('.ldr-sidebar');return {hasMobileNav: !!nav,diff --git a/tests/ui_tests/mobile/test_mobile_navigation_authenticated.js b/tests/ui_tests/mobile/test_mobile_navigation_authenticated.jsindex 6b5bd5011a..c409f5dd53 100644--- a/tests/ui_tests/mobile/test_mobile_navigation_authenticated.js+++ b/tests/ui_tests/mobile/test_mobile_navigation_authenticated.js@@ -47,8 +47,8 @@ async function testAuthenticatedPages() {// Check for mobile navigationconst mobileNavInfo = await page.evaluate(() => {const oldNav = document.querySelector('.mobile-tab-bar');- const newNav = document.querySelector('.mobile-bottom-nav');- const sidebar = document.querySelector('.sidebar');+ const newNav = document.querySelector('.ldr-mobile-bottom-nav');+ const sidebar = document.querySelector('.ldr-sidebar');// Check what's in the DOMconst allNavElements = document.querySelectorAll('[class*="mobile"]');@@ -67,7 +67,7 @@ async function testAuthenticatedPages() {console.log(' URL:', mobileNavInfo.url);console.log(' Old Nav (.mobile-tab-bar):', mobileNavInfo.hasOldNav ? 'YES' : 'NO');- console.log(' New Nav (.mobile-bottom-nav):', mobileNavInfo.hasNewNav ? 'YES' : 'NO');+ console.log(' New Nav (.ldr-mobile-bottom-nav):', mobileNavInfo.hasNewNav ? 'YES' : 'NO');console.log(' Sidebar visible:', mobileNavInfo.sidebarVisible ? 'YES' : 'NO');console.log(' Body classes:', mobileNavInfo.bodyClasses);if (mobileNavInfo.mobileElements.length > 0) {diff --git a/tests/ui_tests/mobile/test_mobile_ui_comprehensive.js b/tests/ui_tests/mobile/test_mobile_ui_comprehensive.jsindex f3f05a8d16..3943f84ceb 100644--- a/tests/ui_tests/mobile/test_mobile_ui_comprehensive.js+++ b/tests/ui_tests/mobile/test_mobile_ui_comprehensive.js@@ -90,7 +90,7 @@ class MobileUITester {// 1. Check duplicate navigation barstests.duplicateNavBars = {oldNav: !!document.querySelector('.mobile-tab-bar'),- newNav: !!document.querySelector('.mobile-bottom-nav'),+ newNav: !!document.querySelector('.ldr-mobile-bottom-nav'),hasDuplicates: false};tests.duplicateNavBars.hasDuplicates =@@ -152,7 +152,7 @@ class MobileUITester {}// Check for overlaps with navigation- const navBar = document.querySelector('.mobile-bottom-nav, .mobile-tab-bar');+ const navBar = document.querySelector('.ldr-mobile-bottom-nav, .mobile-tab-bar');if (navBar) {const navRect = navBar.getBoundingClientRect();if (rect.bottom > navRect.top && rect.top < navRect.bottom) {@@ -193,7 +193,7 @@ class MobileUITester {const mainContent = document.querySelector('.main-content, .page, main');if (mainContent) {const contentRect = mainContent.getBoundingClientRect();- const navBar = document.querySelector('.mobile-bottom-nav');+ const navBar = document.querySelector('.ldr-mobile-bottom-nav');tests.contentPadding = {hasBottomPadding: false,bottomSpace: 0