Skip to content

~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.

fix(settings): collapse settings sections by default on every viewport (#5425)

LearningCircuit2b346f6d6396
diff --git a/.github/workflows/playwright-webkit-tests.yml b/.github/workflows/playwright-webkit-tests.yml
index d8bc56fd77..09b80a0228 100644
--- a/.github/workflows/playwright-webkit-tests.yml
+++ b/.github/workflows/playwright-webkit-tests.yml
@@ -153,14 +153,14 @@ jobs:
# - settings-subpages-mobile: settings tab navigation and form layouts
# - mobile-ui-audit: comprehensive mobile UI quality checks
# - embedding-settings-dropdown: regression for #3863 (model dropdown reset)
- # - settings-mobile-collapse: sections collapse by default on mobile (#4032),
- # stay expanded on desktop, and search force-expands survivors
+ # - settings-section-collapse: sections collapse by default on EVERY
+ # viewport (#4032), and search force-expands survivors
# Full suite: run locally via `cd tests/ui_tests/playwright && npm test`
# When adding Safari-critical tests, update this filter pattern.
run: |
npx playwright test \
--project="Desktop Safari" \
- "all-pages-mobile|auth-pages-mobile|desktop-layout|interactive-states|settings-subpages-mobile|mobile-ui-audit|embedding-settings-dropdown|settings-mobile-collapse"
+ "all-pages-mobile|auth-pages-mobile|desktop-layout|interactive-states|settings-subpages-mobile|mobile-ui-audit|embedding-settings-dropdown|settings-section-collapse"
- name: Upload Playwright Report
if: always()
@@ -322,8 +322,9 @@ jobs:
# - interactive-states: advanced options, search, help panels, mobile menus
# - settings-subpages-mobile: settings tab navigation and form layouts
# - mobile-ui-audit: comprehensive mobile UI quality checks
- # - settings-mobile-collapse: sections collapse by default on mobile (#4032);
- # this is the viewport where the >16384px overflow regression bites
+ # - settings-section-collapse: sections collapse by default on EVERY
+ # viewport (#4032); this is the viewport where the >16384px overflow
+ # regression bites hardest
# Note: embedding-settings-dropdown is desktop-only (skips on isMobile),
# so it intentionally only appears in the Desktop Safari filter above.
# Full suite: run locally via `cd tests/ui_tests/playwright && npm test`
@@ -331,7 +332,7 @@ jobs:
run: |
npx playwright test \
--project="Mobile Safari" \
- "all-pages-mobile|auth-pages-mobile|desktop-layout|interactive-states|settings-subpages-mobile|mobile-ui-audit|settings-mobile-collapse"
+ "all-pages-mobile|auth-pages-mobile|desktop-layout|interactive-states|settings-subpages-mobile|mobile-ui-audit|settings-section-collapse"
- name: Upload Playwright Report
if: always()
diff --git a/changelog.d/5425.bugfix.md b/changelog.d/5425.bugfix.md
new file mode 100644
index 0000000000..081daababd
--- /dev/null
+++ b/changelog.d/5425.bugfix.md
@@ -0,0 +1,7 @@
+Settings sections now start collapsed on every viewport, not just on mobile —
+"All Settings" no longer renders as a single wall tens of thousands of pixels
+tall on desktop. Each section remembers whether you left it open, searching
+temporarily expands every matching section, and headers are keyboard-operable
+(Enter/Space) with their expanded state exposed to assistive technology. Deep
+links such as `/settings#setting-llm-model` and inline save-validation errors
+now open the section they point at.
diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.css
index a9bcd0da19..f021482970 100644
--- a/src/local_deep_research/web/static/css/settings.css
+++ b/src/local_deep_research/web/static/css/settings.css
@@ -208,6 +208,15 @@
background-color: rgba(var(--accent-primary-rgb), 0.1);
}
+/* The header is a role="button" with tabindex="0", so keyboard users need a
+ visible focus ring. `.ldr-settings-section` sets `overflow: hidden`, which
+ clips anything drawn outside the header's border box — hence the negative
+ offset, matching `.ldr-chat-steps-header:focus-visible` in chat.css. */
+.ldr-settings-section-header:focus-visible {
+ outline: 2px solid var(--accent-primary, #6e4ff6);
+ outline-offset: -2px;
+}
+
.ldr-settings-section-title {
font-weight: 600;
font-size: 1rem;
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index ef443837e8..aa3bedfa82 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -833,6 +833,12 @@
errorMsg.className = 'ldr-settings-error-message';
errorMsg.textContent = errorMessage;
settingsItem.appendChild(errorMsg);
+
+ // Sections start collapsed, so an inline error appended into a
+ // collapsed body would be invisible — the user would only see the
+ // banner and never the field-level reason. Reveal the owning
+ // section (transiently: the remembered preference is untouched).
+ expandSectionContaining(settingsItem);
} else {
// Remove error class
settingsItem.classList.remove('ldr-settings-error');
@@ -1002,6 +1008,15 @@
* Toggle the inline "no model selected" warning shown under the
* Language Model dropdown. The element itself lives in the settings
* template; this just flips its visibility.
+ *
+ * Nothing this file renders emits that element. The only
+ * `id="llm.model-empty-warning"` in the tree sits inside the
+ * `render_setting` macro (templates/components/settings_form.html), which
+ * is imported but never called — a property
+ * tests/security/test_injection_and_template_safety.py pins. So the guard
+ * below always fires on the dashboard, and there is deliberately no
+ * "reveal the owning section" step here: it could never run, and a dead
+ * call would only suggest the warning is reachable when it is not.
* @param {boolean} isEmpty - true when the model field is empty
*/
function updateModelEmptyWarning(isEmpty) {
@@ -1299,80 +1314,253 @@
}
/**
- * Mobile breakpoint (px). Kept as a constant so JS callers and the
- * Playwright spec read from one place; CSS still hardcodes 767 in its
- * own `@media` rules because CSS can't read JS values. If you change
- * this, also update the `@media (max-width: 767px)` blocks in
- * settings.css and settings-mobile-fix.css.
+ * localStorage key prefix for a section's remembered collapsed state.
+ * Mirrors the established pattern in services/help.js
+ * (`ldr_panel_collapsed_<panelId>`) — collapse/expand is UI state, not a
+ * user preference, so localStorage (not the backend SettingsManager) is
+ * the right store.
*/
- const MOBILE_BREAKPOINT_PX = 767;
- if (typeof window !== 'undefined') {
- window.__LDR_MOBILE_BREAKPOINT_PX = MOBILE_BREAKPOINT_PX;
+ const SECTION_COLLAPSE_STORAGE_PREFIX = 'ldr_settings_section_collapsed_';
+
+ /**
+ * Read a section's persisted collapsed state. Returns `true`/`false` when
+ * a preference was previously saved, or `null` when there is none yet
+ * (or localStorage is unavailable, e.g. private browsing).
+ */
+ function getStoredSectionCollapsed(sectionId) {
+ try {
+ const stored = localStorage.getItem(SECTION_COLLAPSE_STORAGE_PREFIX + sectionId);
+ if (stored === 'true') return true;
+ if (stored === 'false') return false;
+ } catch {
+ // Ignore localStorage errors (e.g. disabled/private browsing).
+ }
+ return null;
}
/**
- * Returns true when the viewport is in the mobile breakpoint that the rest
- * of the app uses (matches the `@media (max-width: 767px)` rules in CSS).
+ * Persist a section's collapsed state so it survives page reloads.
*/
- function isMobileSettingsViewport() {
- return typeof window !== 'undefined'
- && typeof window.matchMedia === 'function'
- && window.matchMedia('(max-width: ' + MOBILE_BREAKPOINT_PX + 'px)').matches;
+ function setStoredSectionCollapsed(sectionId, collapsed) {
+ try {
+ localStorage.setItem(SECTION_COLLAPSE_STORAGE_PREFIX + sectionId, collapsed ? 'true' : 'false');
+ } catch (e) {
+ SafeLogger.warn('Failed to save settings section collapse state:', e);
+ }
}
/**
- * Initialize accordion behavior.
+ * Apply (or clear) the collapsed state on a section's header/body pair
+ * and keep `aria-expanded` in sync. The `collapsed` class remains the
+ * single source of truth for visuals: on the header it drives chevron
+ * rotation via `.ldr-settings-section-header.collapsed
+ * .ldr-settings-toggle-icon` in settings.css, and on the body it drives
+ * panel visibility via `.ldr-settings-section-body.collapsed { display:
+ * none }` — no inline style.display. Do not toggle the icon transform
+ * inline; CSS owns the rotation, and setting transform on the inner <i>
+ * would compound with the container's rotation.
+ */
+ function applySectionCollapsedState(header, target, collapsed) {
+ header.classList.toggle('collapsed', collapsed);
+ target.classList.toggle('collapsed', collapsed);
+ header.setAttribute('aria-expanded', String(!collapsed));
+ }
+
+ /**
+ * Expand the settings section that contains `element`, if it is currently
+ * collapsed. Used for *programmatic* reveals — a deep link, an inline
+ * validation mark — where the app, not the user, decided the section
+ * must be open.
*
- * Settings has ~400 controls split across many categories. On mobile that
- * is unusable — the page renders past 16384px tall and the user has to
- * scroll forever. So on mobile we start every section collapsed; the user
- * taps a section header to drill in. Desktop keeps the previous "all
- * expanded" default so power-user workflows don't change.
+ * Deliberately calls `applySectionCollapsedState` rather than the
+ * header's own toggle handler, so nothing is written to localStorage: the
+ * user's remembered per-section preference must survive a transient
+ * reveal, exactly like the search override does.
*
- * Callers can override with `{ defaultCollapsed: false }` (e.g. the search
- * filter rebuild — when the user is actively searching, surviving matches
- * must be visible regardless of viewport).
+ * @param {Element|null} element - Any node inside the section.
+ * @returns {boolean} true when a collapsed section was expanded.
+ */
+ function expandSectionContaining(element) {
+ if (!element || typeof element.closest !== 'function') return false;
+
+ const body = element.closest('.ldr-settings-section-body');
+ if (!body || !body.classList.contains('collapsed')) return false;
+
+ // Resolve the header by node relationship / data-target equality
+ // rather than by building a selector out of body.id — the id is
+ // derived from a server-supplied category name.
+ let header = body.previousElementSibling;
+ if (!header || !header.classList || !header.classList.contains('ldr-settings-section-header')) {
+ header = Array.from(document.querySelectorAll('.ldr-settings-section-header'))
+ .find(candidate => candidate.dataset.target === body.id) || null;
+ }
+ if (!header) return false;
+
+ applySectionCollapsedState(header, body, false);
+ return true;
+ }
+
+ /**
+ * Initialize accordion behavior.
*
- * Chevron rotation is driven entirely by the `collapsed` class on the
- * header — see the `.ldr-settings-section-header.collapsed
- * .ldr-settings-toggle-icon` rule in settings.css. Do not toggle the
- * icon transform inline; CSS is the single source of truth for the
- * rotation, and setting transform on the inner <i> would compound
- * with the container's rotation.
+ * Settings has ~400 controls split across many categories. Rendered
+ * fully expanded, "All Settings" is tens of thousands of pixels tall on
+ * *any* viewport — this used to only get fixed for mobile (which starts
+ * every section collapsed), leaving desktop with the same unusable wall
+ * of expanded sections. Both viewports now default to collapsed; the
+ * user clicks/taps a section header (or presses Enter/Space on it) to
+ * drill in. A user's manual expand/collapse choice for a given section
+ * is remembered across reloads via localStorage (see
+ * `getStoredSectionCollapsed`/`setStoredSectionCollapsed` above).
+ *
+ * Callers can pin an explicit state with `{ defaultCollapsed: false }`
+ * (e.g. the search filter rebuild — when the user is actively searching,
+ * surviving matches must be visible regardless of viewport or any
+ * previously persisted per-section preference) or
+ * `{ defaultCollapsed: true }`. When an explicit value is passed, the
+ * persisted preference is neither read nor written for this call — the
+ * override is meant to be transient, not to clobber the user's normal
+ * browsing preference.
*/
function initAccordions(options) {
const opts = options || {};
- const defaultCollapsed = typeof opts.defaultCollapsed === 'boolean'
- ? opts.defaultCollapsed
- : isMobileSettingsViewport();
+ const hasExplicitDefault = typeof opts.defaultCollapsed === 'boolean';
+ const explicitDefault = opts.defaultCollapsed;
document.querySelectorAll('.ldr-settings-section-header').forEach(header => {
const targetId = header.dataset.target;
const target = document.getElementById(targetId);
if (target) {
- // Set initial state per viewport / caller override. The
- // `collapsed` class is the single source of truth: on the
- // header it drives chevron rotation, and on the body it
- // drives panel visibility via the
- // `.ldr-settings-section-body.collapsed { display: none }`
- // rule in settings.css — no inline style.display.
- if (defaultCollapsed) {
- header.classList.add('collapsed');
- target.classList.add('collapsed');
+ let collapsed;
+ if (hasExplicitDefault) {
+ collapsed = explicitDefault;
} else {
- header.classList.remove('collapsed');
- target.classList.remove('collapsed');
+ const stored = getStoredSectionCollapsed(targetId);
+ collapsed = stored === null ? true : stored;
}
- header.addEventListener('click', () => {
- header.classList.toggle('collapsed');
- target.classList.toggle('collapsed');
+ applySectionCollapsedState(header, target, collapsed);
+
+ // Whether a user toggle on THIS header persists is a property
+ // of the most recent init, not of the init that happened to
+ // attach the listener. Keep it on the node so the guard below
+ // cannot freeze a stale persistence mode into the closure.
+ header.dataset.accordionPersist = hasExplicitDefault ? 'false' : 'true';
+
+ // Attach the listeners at most once per header node (same
+ // guard shape as initAutoSaveHandlers' data-autosave-initialized).
+ // Every caller today replaces #settings-content's innerHTML
+ // first, so this never trips in practice — but a second init
+ // over the same nodes would otherwise attach a second
+ // listener, turning one user click into two toggles (a
+ // visible no-op) and writing the stale second value to
+ // localStorage.
+ if (header.hasAttribute('data-accordion-init')) return;
+ header.setAttribute('data-accordion-init', 'true');
+
+ const toggle = () => {
+ const nextCollapsed = !header.classList.contains('collapsed');
+ applySectionCollapsedState(header, target, nextCollapsed);
+ if (header.dataset.accordionPersist !== 'false') {
+ setStoredSectionCollapsed(targetId, nextCollapsed);
+ }
+ };
+
+ header.addEventListener('click', toggle);
+ header.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' || e.key === ' ' || e.key === 'Spacebar') {
+ // preventDefault runs before the repeat guard on
+ // purpose: while Space is held down the page must
+ // keep being stopped from scrolling, not just on the
+ // first event.
+ e.preventDefault();
+ // keydown auto-repeats while a key is held. Without
+ // this guard the section would flap open/closed at
+ // the OS repeat rate and write to localStorage on
+ // every repeat; a native <button> does not
+ // re-activate on repeat either.
+ if (e.repeat) {
+ return;
+ }
+ toggle();
+ }
});
}
});
}
+ /**
+ * The fragment revealHashTarget has already acted on, so a re-render does
+ * not re-open a section the user collapsed in the meantime. See the
+ * "at most once per fragment" note in revealHashTarget below.
+ */
+ let lastRevealedHash = null;
+
+ /**
+ * Make a deep-linked control reachable.
+ *
+ * The links of this shape that actually exist are the egress warnings in
+ * security/egress/warnings.py (the anchor built at :294 and emitted as
+ * `actionUrl` at :314, plus :453), which point at
+ * `/settings#setting-<key with dots as dashes>` — the id
+ * renderSettingItem assigns. (The other `/settings#…` links in the tree
+ * are a different shape: the library and download-manager pages link
+ * `#research-library`, the news subscription form links `#news_scheduler`.
+ * No element on the settings page carries either id at any revision, so
+ * this function cannot resolve them — those anchors were already inert
+ * before sections started collapsing.)
+ *
+ * Sections now start collapsed, so a `setting-<key>` element renders
+ * inside `display: none`: the browser's own fragment scroll lands nowhere
+ * and find-in-page cannot reach it either. Expand its section and scroll
+ * it into view.
+ *
+ * Three settings are rendered as custom dropdowns rather than plain
+ * inputs (`llm.model`, `llm.provider`, `search.tool` — see
+ * renderCustomDropdownHTML), so for those no element carries the bare
+ * `setting-<key>` id: the ids present are `setting-<key>-label` on the
+ * <label> and `setting-<key>-dropdown` on the dropdown container. Try
+ * those two in turn so a link like `/settings#setting-llm-model` resolves
+ * for them as well. Every candidate goes through getElementById; a
+ * selector is never built out of the fragment.
+ *
+ * At most once per fragment: renderSettingsByTab runs again on every tab
+ * click and whenever the search box is cleared, and revealing on each of
+ * those would re-open (and re-scroll to) a section the user had
+ * deliberately collapsed since following the link. A different fragment
+ * reveals again.
+ *
+ * The expansion is transient — expandSectionContaining writes no
+ * localStorage preference — so following a deep link does not silently
+ * change which sections the user finds open on their next visit.
+ */
+ function revealHashTarget() {
+ const rawHash = (window.location.hash || '').slice(1);
+ if (!rawHash) return;
+ if (rawHash === lastRevealedHash) return;
+
+ let targetId = rawHash;
+ try {
+ targetId = decodeURIComponent(rawHash);
+ } catch {
+ // Malformed percent-escape: fall back to the raw fragment.
+ }
+
+ const element = document.getElementById(targetId)
+ || document.getElementById(targetId + '-label')
+ || document.getElementById(targetId + '-dropdown');
+ // Not rendered (yet): leave lastRevealedHash alone so the fragment
+ // still gets its one reveal once the tab that owns it is rendered.
+ if (!element) return;
+ lastRevealedHash = rawHash;
+
+ expandSectionContaining(element);
+ if (typeof element.scrollIntoView === 'function') {
+ element.scrollIntoView({ block: 'center' });
+ }
+ }
+
/**
* Format JSON in textareas
*/
@@ -1848,7 +2036,7 @@
const html = `
<div class="ldr-settings-section ldr-data-location-section">
- <div class="ldr-settings-section-header" data-target="${sectionId}">
+ <div class="ldr-settings-section-header" data-target="${sectionId}" role="button" tabindex="0" aria-expanded="true" aria-controls="${sectionId}">
<div class="ldr-settings-section-title">
<i class="fas fa-database"></i> Database & Encryption
</div>
@@ -2232,7 +2420,7 @@
const html = `
<div class="ldr-settings-section ldr-backup-status-section">
- <div class="ldr-settings-section-header" data-target="${sectionId}">
+ <div class="ldr-settings-section-header" data-target="${sectionId}" role="button" tabindex="0" aria-expanded="true" aria-controls="${sectionId}">
<div class="ldr-settings-section-title">
<i class="fas fa-shield-alt"></i> Backup Status
</div>
@@ -2457,13 +2645,18 @@
for (const type of prefixTypes) {
// For each category in this type
for (const category in groupedSettings[type]) {
- const sectionId = `section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`;
+ // `category` is server-supplied text that is spliced into the
+ // innerHTML string below, so escape it — and the id derived
+ // from it — before interpolation. Hardening of a pre-existing
+ // template: `data-target`/`id` already carried the raw value.
+ const sectionId = escapeHtml(`section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`);
+ const safeCategory = escapeHtml(category);
html += `
<div class="ldr-settings-section">
- <div class="ldr-settings-section-header" data-target="${sectionId}">
- <div class="ldr-settings-section-title" title="${category}">
- ${category}
+ <div class="ldr-settings-section-header" data-target="${sectionId}" role="button" tabindex="0" aria-expanded="true" aria-controls="${sectionId}">
+ <div class="ldr-settings-section-title" title="${safeCategory}">
+ ${safeCategory}
</div>
<div class="ldr-settings-toggle-icon">
<i class="fas fa-chevron-down"></i>
@@ -2499,6 +2692,11 @@
// Initialize accordion behavior
initAccordions();
+ // The rendered content only exists now, so the browser has already
+ // given up on any #fragment in the URL. Resolve it against the fresh
+ // DOM and open the section it points into.
+ revealHashTarget();
+
// Initialize JSON handling
initJsonFormatting();
@@ -3672,13 +3870,18 @@
for (const type of prefixTypes) {
// For each category in this type
for (const category in groupedSettings[type]) {
- const sectionId = `section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`;
+ // `category` is server-supplied text that is spliced into the
+ // innerHTML string below, so escape it — and the id derived
+ // from it — before interpolation. Hardening of a pre-existing
+ // template: `data-target`/`id` already carried the raw value.
+ const sectionId = escapeHtml(`section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`);
+ const safeCategory = escapeHtml(category);
html += `
<div class="ldr-settings-section">
- <div class="ldr-settings-section-header" data-target="${sectionId}">
- <div class="ldr-settings-section-title" title="${category}">
- ${category}
+ <div class="ldr-settings-section-header" data-target="${sectionId}" role="button" tabindex="0" aria-expanded="true" aria-controls="${sectionId}">
+ <div class="ldr-settings-section-title" title="${safeCategory}">
+ ${safeCategory}
</div>
<div class="ldr-settings-toggle-icon">
<i class="fas fa-chevron-down"></i>
diff --git a/tests/js/components/settings-accordion.test.js b/tests/js/components/settings-accordion.test.js
new file mode 100644
index 0000000000..251df201c2
--- /dev/null
+++ b/tests/js/components/settings-accordion.test.js
@@ -0,0 +1,696 @@
+/**
+ * Settings accordion (collapse/expand) behavior in components/settings.js
+ *
+ * Context: "All Settings" rendered fully expanded on desktop at ~77,000px
+ * tall — every one of ~57 sections (search engine integrations, each with
+ * 10-15 fields, JSON textareas, etc.) rendered open at once. Mobile already
+ * fixed this by starting every section collapsed via `initAccordions()`;
+ * desktop kept the old "all expanded" default. This fix makes both
+ * viewports default to collapsed by reusing the same mechanism (no new
+ * parallel accordion implementation), and adds:
+ * - `role="button"`/`tabindex="0"`/`aria-expanded`/`aria-controls` on the
+ * section header (keyboard operable, matches the existing
+ * `role="button"` + `aria-expanded` convention already used by
+ * services/help.js's collapsible panels).
+ * - Per-section collapsed-state persistence via localStorage, matching
+ * the established `ldr_panel_collapsed_<id>` pattern in help.js.
+ * - An explicit-override escape hatch (`{ defaultCollapsed: false }`) that
+ * the search filter rebuild already relied on to force every surviving
+ * section open — this must keep working and must NOT read/write the
+ * persisted per-section preference (a forced-open search result must
+ * not permanently overwrite what the user chose while browsing).
+ *
+ * Strategy: settings.js is an unexported IIFE, so (like
+ * settings-fetch-error-handling.test.js) we dynamically import the real
+ * module into a happy-dom document, dispatch DOMContentLoaded to run its
+ * real bootstrapping, and assert against the real rendered DOM. Each test
+ * gets a fresh module instance via `vi.resetModules()` so localStorage
+ * seeded before import faithfully simulates "returning after a page load".
+ */
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const SETTINGS_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/settings.js',
+);
+const SETTINGS_SOURCE = readFileSync(SETTINGS_PATH, 'utf8');
+
+const SETTINGS_PAYLOAD = {
+ 'app.setting_one': {
+ name: 'Setting One', description: 'first setting', category: 'group_alpha',
+ value: 'a', ui_element: 'text', editable: true, visible: true,
+ },
+ 'app.setting_two': {
+ name: 'Setting Two', description: 'second setting', category: 'group_beta',
+ value: 'b', ui_element: 'text', editable: true, visible: true,
+ },
+ 'search.setting_three': {
+ name: 'Setting Three', description: 'iterations control', category: 'group_gamma',
+ value: 'c', ui_element: 'text', editable: true, visible: true,
+ },
+};
+
+function buildDom() {
+ document.head.innerHTML = '<meta name="csrf-token" content="test-csrf">';
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <div class="ldr-settings-tabs">
+ <div class="ldr-settings-tab active" data-tab="all">All Settings</div>
+ <div class="ldr-settings-tab" data-tab="app">Application</div>
+ </div>
+ <input type="text" id="settings-search">
+ <div id="settings-alert"></div>
+ <div id="settings-content"></div>
+ </form>
+ `;
+}
+
+/**
+ * The escaper the page really runs with: security/xss-protection.js installs
+ * this on `window.escapeHtml`, and settings.js captures whatever is on window
+ * at import time (`const escapeHtml = window.escapeHtml || escapeHtmlFallback;`).
+ * Kept byte-equivalent to that implementation, including the `/` escape.
+ */
+const HTML_ESCAPE_MAP = {
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;', '/': '&#x2F;',
+};
+const realEscapeHtml = (text) => (
+ text === null || text === undefined
+ ? ''
+ : String(text).replace(/[&<>"'/]/g, (match) => HTML_ESCAPE_MAP[match])
+);
+
+function stubFetch(payload = SETTINGS_PAYLOAD) {
+ return vi.fn((url) => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(new Response(
+ JSON.stringify({ status: 'success', settings: payload }),
+ { status: 200 },
+ ));
+ }
+ if (url === '/settings/api/data-location') {
+ return Promise.resolve(new Response(JSON.stringify({
+ data_directory: '/tmp/ldr',
+ security_notice: { encrypted: false },
+ }), { status: 200 }));
+ }
+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
+ return Promise.resolve(new Response(JSON.stringify({
+ enabled: false, count: 0, backups: [],
+ }), { status: 200 }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ return Promise.resolve(new Response(
+ '{"providers":{},"provider_options":[]}', { status: 200 },
+ ));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
+ return Promise.resolve(new Response(
+ '{"engine_options":[]}', { status: 200 },
+ ));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+/**
+ * Dynamically (re)import settings.js into a fresh DOM and drive its real
+ * bootstrapping until the initial "All Settings" render (and therefore
+ * `initAccordions()`) has run.
+ *
+ * @param {Function} [prepareDom] - Optional hook run after the base fixture
+ * is built but *before* settings.js is imported, for tests that need extra
+ * markup present at bootstrap time.
+ * @param {Object} [options]
+ * @param {Object} [options.payload] - Settings payload /settings/api returns,
+ * defaulting to SETTINGS_PAYLOAD.
+ * @param {Function} [options.escapeHtml] - What to install on
+ * `window.escapeHtml` *before* the import, since settings.js captures it
+ * once at import time. Defaults to the identity stub the DOM-shape tests
+ * want; the escaping test passes the real escaper.
+ */
+async function loadSettingsPage(prepareDom, options = {}) {
+ vi.resetModules();
+ vi.useFakeTimers();
+
+ buildDom();
+ if (prepareDom) prepareDom();
+ window.escapeHtml = options.escapeHtml || (value => String(value));
+ window.ui = null;
+ window.modelProvidersRequestInProgress = null;
+ window.searchEnginesRequestInProgress = null;
+
+ const fetchMock = stubFetch(options.payload);
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/settings.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await Promise.resolve();
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(151);
+
+ return fetchMock;
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ localStorage.clear();
+ // The deep-link test below sets a fragment; clear it so it cannot leak
+ // into another test's render. A no-op when the hash is already empty.
+ window.location.hash = '';
+});
+
+describe('settings.js source: accordion markup carries aria wiring', () => {
+ // Cheap source-level guard: every one of the four places that build a
+ // `.ldr-settings-section-header` string must carry the aria triad,
+ // independent of the heavier DOM tests below.
+ it('every section header template includes role/tabindex/aria-expanded/aria-controls', () => {
+ const headerOpenTags = SETTINGS_SOURCE.match(
+ /<div class="ldr-settings-section-header"[^>]*>/g,
+ ) || [];
+ expect(headerOpenTags.length).toBeGreaterThanOrEqual(4);
+ headerOpenTags.forEach(tag => {
+ expect(tag).toContain('role="button"');
+ expect(tag).toContain('tabindex="0"');
+ expect(tag).toContain('aria-expanded=');
+ // Regex (not a plain string) so eslint's no-template-curly-in-string
+ // rule doesn't mistake this literal-source-text assertion for an
+ // accidentally unwrapped template literal.
+ expect(tag).toMatch(/aria-controls="\$\{sectionId\}"/);
+ });
+ });
+});
+
+describe('settings accordion — default collapsed state (desktop and mobile alike)', () => {
+ it('renders multiple sections, all collapsed by default, with aria-expanded=false', async () => {
+ await loadSettingsPage();
+
+ const headers = Array.from(document.querySelectorAll('.ldr-settings-section-header'));
+ expect(headers.length).toBeGreaterThanOrEqual(4); // 3 setting groups + data-location + backup-status
+
+ headers.forEach(header => {
+ expect(header.classList.contains('collapsed')).toBe(true);
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+
+ const body = document.getElementById(header.dataset.target);
+ expect(body).not.toBeNull();
+ expect(body.classList.contains('collapsed')).toBe(true);
+ });
+ });
+
+ it('clicking a header expands only that section and flips its aria-expanded', async () => {
+ await loadSettingsPage();
+
+ const headers = Array.from(document.querySelectorAll('.ldr-settings-section-header'));
+ const [first, second] = headers;
+
+ first.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+ expect(first.classList.contains('collapsed')).toBe(false);
+ expect(first.getAttribute('aria-expanded')).toBe('true');
+ expect(document.getElementById(first.dataset.target).classList.contains('collapsed')).toBe(false);
+
+ // Unrelated sections are untouched.
+ expect(second.classList.contains('collapsed')).toBe(true);
+ expect(second.getAttribute('aria-expanded')).toBe('false');
+
+ // Clicking again re-collapses.
+ first.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(first.classList.contains('collapsed')).toBe(true);
+ expect(first.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('Enter and Space toggle a focused header (keyboard accessible)', async () => {
+ await loadSettingsPage();
+
+ const header = document.querySelector('.ldr-settings-section-header');
+ expect(header.getAttribute('tabindex')).toBe('0');
+ expect(header.getAttribute('role')).toBe('button');
+
+ const enterEvent = new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true });
+ header.dispatchEvent(enterEvent);
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(enterEvent.defaultPrevented).toBe(true);
+
+ const spaceEvent = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true });
+ header.dispatchEvent(spaceEvent);
+ expect(header.classList.contains('collapsed')).toBe(true);
+ expect(spaceEvent.defaultPrevented).toBe(true);
+
+ // A non-activation key does nothing.
+ const tabEvent = new KeyboardEvent('keydown', { key: 'Tab', bubbles: true, cancelable: true });
+ header.dispatchEvent(tabEvent);
+ expect(header.classList.contains('collapsed')).toBe(true);
+ expect(tabEvent.defaultPrevented).toBe(false);
+ });
+
+ it('ignores auto-repeat keydowns so a held key does not flap the section', async () => {
+ await loadSettingsPage();
+
+ const header = document.querySelector('.ldr-settings-section-header');
+ expect(header.classList.contains('collapsed')).toBe(true);
+
+ // First keydown of a held Space activates once...
+ const first = new KeyboardEvent('keydown', { key: ' ', bubbles: true, cancelable: true });
+ header.dispatchEvent(first);
+ expect(header.classList.contains('collapsed')).toBe(false);
+
+ // ...and the OS auto-repeats that follow must not toggle again,
+ // while still swallowing the key so the page doesn't scroll.
+ for (let i = 0; i < 5; i++) {
+ const repeat = new KeyboardEvent('keydown', {
+ key: ' ', repeat: true, bubbles: true, cancelable: true,
+ });
+ header.dispatchEvent(repeat);
+ expect(repeat.defaultPrevented).toBe(true);
+ }
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ });
+});
+
+describe('settings accordion — persistence across page loads', () => {
+ it('persists a manual expand/collapse choice to localStorage under a stable per-section key', async () => {
+ await loadSettingsPage();
+
+ const header = document.querySelector('.ldr-settings-section-header');
+ const sectionId = header.dataset.target;
+
+ header.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${sectionId}`)).toBe('false');
+
+ header.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${sectionId}`)).toBe('true');
+ });
+
+ it('honors a previously persisted "expanded" preference on the next page load', async () => {
+ // First load: discover the section id and its initial (collapsed)
+ // state, matching a real user's first visit.
+ await loadSettingsPage();
+ const targetId = document.querySelector('.ldr-settings-section-header').dataset.target;
+
+ // Simulate the user having expanded that one section previously —
+ // seed localStorage exactly the way a real click would have, then
+ // reload the page (fresh module import, fresh DOM).
+ localStorage.setItem(`ldr_settings_section_collapsed_${targetId}`, 'false');
+
+ await loadSettingsPage();
+
+ const headers = Array.from(document.querySelectorAll('.ldr-settings-section-header'));
+ const remembered = headers.find(h => h.dataset.target === targetId);
+ const others = headers.filter(h => h.dataset.target !== targetId);
+
+ expect(remembered.classList.contains('collapsed')).toBe(false);
+ expect(remembered.getAttribute('aria-expanded')).toBe('true');
+
+ // Sections with no stored preference still default to collapsed.
+ others.forEach(h => {
+ expect(h.classList.contains('collapsed')).toBe(true);
+ });
+ });
+});
+
+describe('settings accordion — search interaction', () => {
+ it('search expands the matching section and preserves its saved preference while toggling', async () => {
+ await loadSettingsPage();
+
+ const matchingInput = document.getElementById('setting-search-setting_three');
+ expect(matchingInput).not.toBeNull();
+ const matchingHeader = matchingInput.closest('.ldr-settings-section')
+ .querySelector('.ldr-settings-section-header');
+ const targetId = matchingHeader.dataset.target;
+ const storageKey = `ldr_settings_section_collapsed_${targetId}`;
+ localStorage.setItem(storageKey, 'true');
+
+ const searchInput = document.getElementById('settings-search');
+ searchInput.value = 'iterations'; // matches search.setting_three's description
+ searchInput.dispatchEvent(new Event('input', { bubbles: true }));
+
+ // handleSearchInput is debounced 250ms.
+ await vi.advanceTimersByTimeAsync(260);
+
+ const headers = Array.from(document.querySelectorAll('.ldr-settings-section-header'));
+ expect(headers.length).toBeGreaterThan(0);
+ headers.forEach(header => {
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ const body = document.getElementById(header.dataset.target);
+ expect(body.classList.contains('collapsed')).toBe(false);
+ });
+
+ const matchedInput = document.getElementById('setting-search-setting_three');
+ expect(matchedInput).not.toBeNull();
+ expect(matchedInput.closest('.ldr-settings-section-body').id).toBe(targetId);
+ expect(localStorage.getItem(storageKey)).toBe('true');
+
+ const searchHeader = matchedInput.closest('.ldr-settings-section')
+ .querySelector('.ldr-settings-section-header');
+ for (const collapsed of [true, false]) {
+ searchHeader.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(searchHeader.classList.contains('collapsed')).toBe(collapsed);
+ expect(searchHeader.getAttribute('aria-expanded')).toBe(String(!collapsed));
+ expect(localStorage.getItem(storageKey)).toBe('true');
+ }
+ });
+
+ it('clearing search restores a saved expanded section and defaults the others to collapsed', async () => {
+ await loadSettingsPage();
+
+ const expandedHeader = document.querySelector('.ldr-settings-section-header');
+ const expandedId = expandedHeader.dataset.target;
+ expandedHeader.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${expandedId}`)).toBe('false');
+
+ const searchInput = document.getElementById('settings-search');
+ searchInput.value = 'iterations';
+ searchInput.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(260);
+
+ searchInput.value = '';
+ searchInput.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(260); // handleSearchInput is debounced 250ms
+
+ const headers = Array.from(document.querySelectorAll('.ldr-settings-section-header'));
+ expect(headers.length).toBeGreaterThan(0);
+ expect(headers.some(header => header.dataset.target === expandedId)).toBe(true);
+ headers.forEach(header => {
+ const collapsed = header.dataset.target !== expandedId;
+ expect(header.classList.contains('collapsed')).toBe(collapsed);
+ expect(header.getAttribute('aria-expanded')).toBe(String(!collapsed));
+ });
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${expandedId}`)).toBe('false');
+ });
+});
+
+describe('settings accordion — programmatic reveals and repeated init', () => {
+ it('expands the section a #hash deep link points into, without persisting a preference', async () => {
+ // /settings#setting-<key> links are emitted by
+ // security/egress/warnings.py and the library/download-manager pages.
+ // With every section collapsed by default the target renders inside
+ // `display: none`, so the browser's own fragment scroll (and
+ // find-in-page) land nowhere. On the unedited head nothing reads
+ // location.hash at any revision, so the deep-linked section stays
+ // collapsed and the first expect below fails.
+ window.location.hash = '#setting-search-setting_three';
+
+ await loadSettingsPage();
+
+ const deepLinked = document.getElementById('setting-search-setting_three');
+ expect(deepLinked).not.toBeNull();
+
+ const body = deepLinked.closest('.ldr-settings-section-body');
+ const header = deepLinked.closest('.ldr-settings-section')
+ .querySelector('.ldr-settings-section-header');
+
+ expect(body.classList.contains('collapsed')).toBe(false);
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+
+ // Transient: following a deep link must not silently rewrite which
+ // sections the user finds open on their next visit.
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${body.id}`)).toBeNull();
+
+ // ...and it expands only that one section.
+ Array.from(document.querySelectorAll('.ldr-settings-section-header'))
+ .filter(other => other.dataset.target !== body.id)
+ .forEach(other => {
+ expect(other.classList.contains('collapsed')).toBe(true);
+ });
+ });
+
+ it('resolves a deep link to a dropdown-rendered setting through its label id', async () => {
+ // `llm.model`, `llm.provider` and `search.tool` are rendered by
+ // renderCustomDropdownHTML, not as a plain input: NO element ends up
+ // carrying the bare `setting-llm-model` id the /settings#setting-<key>
+ // links are built from. The ids that do exist are
+ // `setting-llm-model-label` (the <label>) and
+ // `setting-llm-model-dropdown` (the container), so revealHashTarget
+ // falls back to those. Without the fallback getElementById returns
+ // null and the function returns before expanding anything.
+ window.location.hash = '#setting-llm-model';
+
+ await loadSettingsPage(undefined, {
+ payload: {
+ 'llm.model': {
+ name: 'Model', description: 'The model to use', category: 'llm_general',
+ value: 'gpt-4', ui_element: 'select', editable: true, visible: true,
+ },
+ },
+ });
+
+ // The premise: the id the link names is genuinely absent...
+ expect(document.getElementById('setting-llm-model')).toBeNull();
+ const label = document.getElementById('setting-llm-model-label');
+ expect(label).not.toBeNull();
+
+ // ...and the section it lives in was opened anyway.
+ const body = label.closest('.ldr-settings-section-body');
+ const header = body.previousElementSibling;
+ expect(header.classList.contains('ldr-settings-section-header')).toBe(true);
+ expect(body.classList.contains('collapsed')).toBe(false);
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+
+ // Still transient: no preference was stored for it.
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${body.id}`)).toBeNull();
+ });
+
+ it('reveals a given #hash once, not again on every later render', async () => {
+ // renderSettingsByTab re-runs on a tab click and whenever the search
+ // box is cleared, with the fragment still sitting in the URL. Revealing
+ // again there would undo a collapse the user made after following the
+ // link (and scroll them back to it).
+ window.location.hash = '#setting-search-setting_three';
+
+ await loadSettingsPage();
+
+ const deepLinked = document.getElementById('setting-search-setting_three');
+ expect(deepLinked).not.toBeNull();
+ const revealedId = deepLinked.closest('.ldr-settings-section-body').id;
+ expect(document.getElementById(revealedId).classList.contains('collapsed')).toBe(false);
+
+ // The user closes the section they were sent to. That persists 'true'.
+ const header = document.getElementById(revealedId).previousElementSibling;
+ header.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(document.getElementById(revealedId).classList.contains('collapsed')).toBe(true);
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${revealedId}`)).toBe('true');
+
+ // Search, then clear it — clearing goes through renderSettingsByTab,
+ // which calls revealHashTarget again. handleSearchInput is debounced
+ // 250ms. Every node below is rebuilt, so re-query rather than reusing
+ // the handles above.
+ const searchInput = document.getElementById('settings-search');
+ searchInput.value = 'iterations';
+ searchInput.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(260);
+ searchInput.value = '';
+ searchInput.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(260);
+
+ const reRenderedBody = document.getElementById(revealedId);
+ expect(reRenderedBody).not.toBeNull();
+ expect(reRenderedBody.classList.contains('collapsed')).toBe(true);
+ expect(reRenderedBody.previousElementSibling.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('marking an input invalid opens its collapsed section, writing no preference', async () => {
+ // An inline validation message appended into a collapsed body is
+ // invisible: the user sees the banner and never the field-level
+ // reason. markInvalidInput therefore reveals the owning section.
+ await loadSettingsPage(undefined, {
+ payload: {
+ 'search.iterations': {
+ name: 'Iterations', description: 'search iterations',
+ category: 'search_parameters', value: 3, ui_element: 'number',
+ min_value: 1, max_value: 10, step: 1, editable: true, visible: true,
+ },
+ },
+ });
+ // The auto-save listeners are attached synchronously by
+ // setupCustomDropdowns() at the end of the render; the 300ms timer is
+ // only a second, idempotent pass. Advance past it so the test does not
+ // depend on which of the two got there first.
+ await vi.advanceTimersByTimeAsync(300);
+
+ const input = document.getElementById('setting-search-iterations');
+ expect(input).not.toBeNull();
+ expect(input.getAttribute('max')).toBe('10');
+ const body = input.closest('.ldr-settings-section-body');
+ const header = body.previousElementSibling;
+ expect(body.classList.contains('collapsed')).toBe(true);
+
+ // Out of the rendered range -> handleInputChange -> markInvalidInput.
+ input.value = '999';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+
+ const message = input.closest('.ldr-settings-item')
+ .querySelector('.ldr-settings-error-message');
+ expect(message).not.toBeNull();
+ expect(message.textContent).toContain('Value must be between');
+
+ expect(body.classList.contains('collapsed')).toBe(false);
+ expect(header.classList.contains('collapsed')).toBe(false);
+ expect(header.getAttribute('aria-expanded')).toBe('true');
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${body.id}`)).toBeNull();
+ });
+
+ it('initializes a header exactly once even when initAccordions runs over it twice', async () => {
+ // initAccordions() queries the whole document, but only
+ // #settings-content is replaced by a render. A section header living
+ // outside that container is therefore seen by BOTH the bootstrap call
+ // in initializeSettings() and the post-render call in
+ // renderSettingsByTab() — the same nodes, initialized twice.
+ //
+ // On the unedited head that attaches two click listeners, so one user
+ // click toggles twice: the section snaps shut again (a visible no-op)
+ // and localStorage ends up holding the stale second value ('true').
+ const STATIC_SECTION_ID = 'section-static-outside-content';
+
+ await loadSettingsPage(() => {
+ const section = document.createElement('div');
+ section.className = 'ldr-settings-section';
+
+ const header = document.createElement('div');
+ header.className = 'ldr-settings-section-header';
+ header.dataset.target = STATIC_SECTION_ID;
+ header.setAttribute('role', 'button');
+ header.setAttribute('tabindex', '0');
+ header.setAttribute('aria-expanded', 'true');
+ header.setAttribute('aria-controls', STATIC_SECTION_ID);
+
+ const sectionBody = document.createElement('div');
+ sectionBody.id = STATIC_SECTION_ID;
+ sectionBody.className = 'ldr-settings-section-body';
+
+ section.appendChild(header);
+ section.appendChild(sectionBody);
+ document.getElementById('settings-form').appendChild(section);
+ });
+
+ const staticHeader = document.querySelector(
+ `.ldr-settings-section-header[data-target="${STATIC_SECTION_ID}"]`,
+ );
+ const staticBody = document.getElementById(STATIC_SECTION_ID);
+ expect(staticHeader).not.toBeNull();
+ // Both init passes have run over this node by now.
+ expect(staticHeader.classList.contains('collapsed')).toBe(true);
+
+ staticHeader.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+ expect(staticHeader.classList.contains('collapsed')).toBe(false);
+ expect(staticHeader.getAttribute('aria-expanded')).toBe('true');
+ expect(staticBody.classList.contains('collapsed')).toBe(false);
+ expect(
+ localStorage.getItem(`ldr_settings_section_collapsed_${STATIC_SECTION_ID}`),
+ ).toBe('false');
+ });
+});
+
+describe('settings accordion — the section header escapes its category', () => {
+ // The tests above install `value => String(value)` as window.escapeHtml,
+ // which cannot tell an escaped render from an unescaped one — and
+ // eslint's no-unsanitized reports nothing either way, because the value is
+ // interpolated into a variable that is assigned to innerHTML later. This
+ // test installs the production escaper BEFORE the import (settings.js
+ // captures window.escapeHtml exactly once, at import time), so reverting
+ // `escapeHtml(category)` to a bare `${category}` fails it.
+ //
+ // `category` reaches renderSettingsByTab from /settings/api, i.e. from the
+ // server, via organizeSettings.
+ const HOSTILE_CATEGORY = '<img src=x onerror=alert(1)> & "quoted"';
+ // organizeSettings runs every category through formatCategoryName first,
+ // which upper-cases the first letter of each space-separated word. That
+ // (not the raw payload value) is what the header has to round-trip.
+ const RENDERED_CATEGORY = '<img Src=x Onerror=alert(1)> & "quoted"';
+
+ // `sectionId` (settings.js) is built from the *same* category string and
+ // spliced into two unquoted-looking-but-quoted attributes,
+ // `data-target="${sectionId}"` and `aria-controls="${sectionId}"` (and
+ // the body's `id="${sectionId}"`). A category carrying both a `"` and a
+ // `/` breaks out of `data-target`'s value early (the `"` closes the
+ // attribute) and turns the remainder into a *new* attribute on the
+ // header (the `/` is swallowed as an inter-attribute separator, not
+ // glued onto data-target). HOSTILE_CATEGORY above has no `/`, so it
+ // cannot exercise this — it only ever lands inside an attribute value it
+ // can't escape. This one is a single word (no spaces), so
+ // formatCategoryName only capitalizes its first letter.
+ const HOSTILE_CATEGORY_ATTR_BREAKOUT = 'x"/onmouseover="alert(1)';
+ const RENDERED_CATEGORY_ATTR_BREAKOUT = 'X"/onmouseover="alert(1)';
+
+ it('renders the category as text and keeps data-target === body.id === aria-controls', async () => {
+ await loadSettingsPage(undefined, {
+ escapeHtml: realEscapeHtml,
+ payload: {
+ 'app.hostile_category_setting': {
+ name: 'Hostile', description: 'a setting in a hostile category',
+ category: HOSTILE_CATEGORY, value: 'a', ui_element: 'text',
+ editable: true, visible: true,
+ },
+ 'app.hostile_attr_breakout_setting': {
+ name: 'Hostile Attr Breakout', description: 'a category that breaks out of data-target',
+ category: HOSTILE_CATEGORY_ATTR_BREAKOUT, value: 'a', ui_element: 'text',
+ editable: true, visible: true,
+ },
+ },
+ });
+
+ const titles = Array.from(document.querySelectorAll('.ldr-settings-section-title'));
+ expect(titles.map(node => node.textContent.trim())).toContain(RENDERED_CATEGORY);
+
+ const title = titles.find(node => node.textContent.trim() === RENDERED_CATEGORY);
+ // Round-trips in both contexts, and is not double-escaped (the `&`
+ // would show up as a literal `&amp;` if it were).
+ expect(title.getAttribute('title')).toBe(RENDERED_CATEGORY);
+ // Nothing was parsed as markup.
+ expect(title.children.length).toBe(0);
+ expect(document.querySelector('#settings-content img')).toBeNull();
+ expect(document.querySelector('#settings-content script')).toBeNull();
+
+ // The id derived from the same string still agrees in all three
+ // places, so the accordion (and the localStorage key built from
+ // data-target) is wired to the body it claims.
+ const header = title.closest('.ldr-settings-section-header');
+ const body = header.nextElementSibling;
+ expect(body.classList.contains('ldr-settings-section-body')).toBe(true);
+ expect(header.dataset.target).toBe(body.id);
+ expect(header.getAttribute('aria-controls')).toBe(body.id);
+ expect(document.getElementById(header.dataset.target)).toBe(body);
+
+ // ...and it is still an operable accordion.
+ expect(body.classList.contains('collapsed')).toBe(true);
+ header.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(body.classList.contains('collapsed')).toBe(false);
+ expect(localStorage.getItem(`ldr_settings_section_collapsed_${body.id}`)).toBe('false');
+
+ // The `"`/`/` category: same text round-trip and id triple...
+ const breakoutTitles = titles.filter(
+ node => node.textContent.trim() === RENDERED_CATEGORY_ATTR_BREAKOUT,
+ );
+ expect(breakoutTitles.length).toBe(1);
+ const breakoutTitle = breakoutTitles[0];
+ expect(breakoutTitle.getAttribute('title')).toBe(RENDERED_CATEGORY_ATTR_BREAKOUT);
+ expect(breakoutTitle.children.length).toBe(0);
+
+ const breakoutHeader = breakoutTitle.closest('.ldr-settings-section-header');
+ const breakoutBody = breakoutHeader.nextElementSibling;
+ expect(breakoutBody.classList.contains('ldr-settings-section-body')).toBe(true);
+ expect(breakoutHeader.dataset.target).toBe(breakoutBody.id);
+ expect(breakoutHeader.getAttribute('aria-controls')).toBe(breakoutBody.id);
+ expect(document.getElementById(breakoutHeader.dataset.target)).toBe(breakoutBody);
+
+ // ...and, the point of this case: the category's `"` did not close
+ // data-target early and hand its `/onmouseover="alert(1)` tail to
+ // the parser as a live event-handler attribute on the header. This
+ // is the assertion `escapeHtml(sectionId)` alone is responsible
+ // for — it still passes if only `escapeHtml(category)` is reverted.
+ expect(breakoutHeader.hasAttribute('onmouseover')).toBe(false);
+ });
+});
diff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.js
index 3ceda5ba0e..b0ab5930c3 100644
--- a/tests/js/components/settings-fetch-error-handling.test.js
+++ b/tests/js/components/settings-fetch-error-handling.test.js
@@ -21,7 +21,6 @@ const WINDOW_KEYS = [
'searchEnginesRequestInProgress',
'modelDropdownsInitialized',
'searchEngineDropdownInitialized',
- '__LDR_MOBILE_BREAKPOINT_PX',
'setupSettingsDropdowns',
];
const ORIGINAL_WINDOW_STATE = new Map(WINDOW_KEYS.map(key => [key, {
diff --git a/tests/puppeteer/test_deep_functionality.js b/tests/puppeteer/test_deep_functionality.js
index f72cd12557..51f3219dba 100644
--- a/tests/puppeteer/test_deep_functionality.js
+++ b/tests/puppeteer/test_deep_functionality.js
@@ -49,6 +49,78 @@ function isCdpSessionFlake(err) {
);
}
+/**
+ * Expand the settings section that owns a control, so a real mouse
+ * interaction can reach it.
+ *
+ * Settings sections start collapsed on every viewport (settings.js
+ * `initAccordions()`), and `.ldr-settings-section-body.collapsed { display:
+ * none }` in settings.css takes the body out of the layout. A control inside
+ * one is still in the DOM — `page.$` / `waitForSelector` resolve, since
+ * neither requires visibility — but it has no box, so `click()` / `hover()`
+ * throw "not clickable" and `type()` types into nothing. This suite has its
+ * own package.json and cannot import tests/ui_tests/test_lib, so the expand
+ * step lives here.
+ *
+ * Not equivalent to tests/ui_tests/test_lib/test_utils.js's
+ * `expandSettingsSectionFor`: a string `target` here is resolved once via
+ * `page.$(target)` into a handle and reused, with no `waitForSelector` first
+ * and no re-query — unlike test_utils.js, which `await
+ * page.waitForSelector(target, { timeout })`s and then `page.$eval(target,
+ * expandFor)`s the live element.
+ *
+ * Deliberately total: a target that is already visible, is not inside a
+ * section, or is not on the page at all is left alone, so it is safe to call
+ * before any interaction on /settings.
+ *
+ * @param {object} page - Puppeteer page
+ * @param {object|string} target - ElementHandle for the control, or a CSS selector
+ * @returns {Promise<string>} 'expanded' | 'already-expanded' | 'no-section' |
+ * 'no-header' | 'no-target'
+ */
+async function expandSettingsSectionFor(page, target) {
+ // Runs in page context with the target element as its argument.
+ const expandFor = (el) => {
+ if (!el) return 'no-target';
+ const body = el.closest('.ldr-settings-section-body');
+ if (!body) return 'no-section';
+ if (!body.classList.contains('collapsed')) return 'already-expanded';
+
+ // Resolve the header by node relationship / data-target equality
+ // instead of building a selector out of body.id, which is derived
+ // from a server-supplied category name.
+ let header = body.previousElementSibling;
+ if (!header || !header.classList.contains('ldr-settings-section-header')) {
+ header = Array.from(document.querySelectorAll('.ldr-settings-section-header'))
+ .find(candidate => candidate.dataset.target === body.id) || null;
+ }
+ if (!header) return 'no-header';
+ header.click();
+ return 'expanded';
+ };
+
+ const handle = typeof target === 'string' ? await page.$(target) : target;
+ if (!handle) return 'no-target';
+
+ const outcome = await page.evaluate(expandFor, handle);
+
+ // The click handler applies the class synchronously, but poll rather than
+ // race the DOM update.
+ if (outcome === 'expanded') {
+ await page.waitForFunction(
+ (el) => {
+ if (!el) return false;
+ const body = el.closest('.ldr-settings-section-body');
+ return !body || !body.classList.contains('collapsed');
+ },
+ { timeout: 10000 },
+ handle
+ );
+ }
+
+ return outcome;
+}
+
// Generate unique username for this test run - ensures fresh state each time
const TEST_RUN_ID = generateTestRunId();
const TEST_USERNAME = `test_user_${TEST_RUN_ID}`;
@@ -120,6 +192,9 @@ describe('Deep Functionality Tests', function() {
// Change it
const newValue = currentValue === '3' ? '5' : '3';
+ // The input lives inside a section body that starts collapsed,
+ // so page.$ finds it but it has no box to click.
+ await expandSettingsSectionFor(page, iterationsInput);
await iterationsInput.click({ clickCount: 3 });
await page.keyboard.press('Backspace');
await iterationsInput.type(newValue);
@@ -1505,6 +1580,16 @@ describe('Deep Functionality Tests', function() {
// Try to hover over a help icon to trigger tooltip
if (helpElements.length > 0) {
+ // helpElements[0] is whatever matches that broad selector
+ // first in document order — today the sidebar's first nav
+ // link (components/sidebar.html:11, `title="New Research
+ // (Ctrl+Shift+1)"`, included into base.html ahead of the
+ // topbar's theme selector), which sits outside every
+ // settings section, so this is a no-op. But `[title]` /
+ // `[class*="help"]` also match per-setting help text inside
+ // a collapsed section body, where hover() would have no box
+ // to aim at.
+ await expandSettingsSectionFor(page, helpElements[0]);
await helpElements[0].hover();
await delay(500);
await takeScreenshot(page, 'settings-tooltip');
@@ -1522,6 +1607,7 @@ describe('Deep Functionality Tests', function() {
console.log(` Original value: ${originalValue}`);
// Try to enter invalid value
+ await expandSettingsSectionFor(page, numericInput);
await numericInput.click({ clickCount: 3 });
await numericInput.type('-999999');
await delay(1000);
@@ -1532,7 +1618,9 @@ describe('Deep Functionality Tests', function() {
console.log(' ✓ Validation message shown');
}
- // Restore original
+ // Restore original (already expanded above; a no-op unless
+ // something re-rendered the section in between)
+ await expandSettingsSectionFor(page, numericInput);
await numericInput.click({ clickCount: 3 });
await numericInput.type(originalValue || '5');
await delay(500);
diff --git a/tests/puppeteer/test_openai_api_key_ui.js b/tests/puppeteer/test_openai_api_key_ui.js
index 770b5cfec4..40daaae0b1 100644
--- a/tests/puppeteer/test_openai_api_key_ui.js
+++ b/tests/puppeteer/test_openai_api_key_ui.js
@@ -18,6 +18,68 @@ const TEST_USERNAME = 'test_openai_user';
const TEST_PASSWORD = 'Test_password_123';
const TEST_OPENAI_KEY = 'sk-test-1234567890abcdef';
+/**
+ * Expand the settings section that owns a control, so a real mouse
+ * interaction can reach it.
+ *
+ * Settings sections start collapsed on every viewport, and
+ * `.ldr-settings-section-body.collapsed { display: none }` takes the body out
+ * of the layout: `page.$` still finds the control (it does not require
+ * visibility) but `click()` has no clickable point. Same helper as the one in
+ * test_deep_functionality.js — this file, like loginUser below, keeps its own
+ * copy rather than reaching across suites.
+ *
+ * Not equivalent to tests/ui_tests/test_lib/test_utils.js's
+ * `expandSettingsSectionFor`: a string `target` here is resolved once via
+ * `page.$(target)` into a handle and reused, with no `waitForSelector` first
+ * and no re-query — unlike test_utils.js, which `await
+ * page.waitForSelector(target, { timeout })`s and then `page.$eval(target,
+ * expandFor)`s the live element.
+ *
+ * A target that is already visible, is not inside a section, or is not on the
+ * page is left alone.
+ *
+ * @param {object} page - Puppeteer page
+ * @param {object|string} target - ElementHandle for the control, or a CSS selector
+ * @returns {Promise<string>} outcome, for logging
+ */
+async function expandSettingsSectionFor(page, target) {
+ const expandFor = (el) => {
+ if (!el) return 'no-target';
+ const body = el.closest('.ldr-settings-section-body');
+ if (!body) return 'no-section';
+ if (!body.classList.contains('collapsed')) return 'already-expanded';
+
+ // Resolve the header by node relationship / data-target equality
+ // instead of building a selector out of the server-derived body.id.
+ let header = body.previousElementSibling;
+ if (!header || !header.classList.contains('ldr-settings-section-header')) {
+ header = Array.from(document.querySelectorAll('.ldr-settings-section-header'))
+ .find(candidate => candidate.dataset.target === body.id) || null;
+ }
+ if (!header) return 'no-header';
+ header.click();
+ return 'expanded';
+ };
+
+ const handle = typeof target === 'string' ? await page.$(target) : target;
+ if (!handle) return 'no-target';
+
+ const outcome = await page.evaluate(expandFor, handle);
+ if (outcome === 'expanded') {
+ await page.waitForFunction(
+ (el) => {
+ if (!el) return false;
+ const body = el.closest('.ldr-settings-section-body');
+ return !body || !body.classList.contains('collapsed');
+ },
+ { timeout: 10000 },
+ handle
+ );
+ }
+ return outcome;
+}
+
describe('OpenAI API Key Configuration UI Test', function() {
this.timeout(60000); // 60 second timeout for UI tests
@@ -155,7 +217,11 @@ describe('OpenAI API Key Configuration UI Test', function() {
await page.click('[data-provider="openai"], .provider-option[data-value="openai"]');
}
- // Wait for OpenAI settings to appear
+ // Wait for OpenAI settings to appear. The control renders
+ // inside a section body that starts collapsed, so expand it first
+ // or the `visible: true` wait can never be satisfied.
+ await page.waitForSelector('input[name="llm.openai.api_key"], #openai-api-key');
+ await expandSettingsSectionFor(page, 'input[name="llm.openai.api_key"], #openai-api-key');
await page.waitForSelector('input[name="llm.openai.api_key"], #openai-api-key', { visible: true });
// Clear and enter API key
@@ -245,6 +311,7 @@ describe('OpenAI API Key Configuration UI Test', function() {
// Set invalid API key
const apiKeyInput = await page.$('input[name="llm.openai.api_key"], #openai-api-key');
+ await expandSettingsSectionFor(page, apiKeyInput);
await apiKeyInput.click({ clickCount: 3 });
await apiKeyInput.type('sk-invalid-key');
@@ -280,6 +347,7 @@ describe('OpenAI API Key Configuration UI Test', function() {
// Configure OpenAI
await page.goto(`${BASE_URL}/settings`, { waitUntil: 'domcontentloaded' });
await page.select('select[name="llm.provider"], #llm-provider', 'openai');
+ await expandSettingsSectionFor(page, 'input[name="llm.openai.api_key"], #openai-api-key');
await page.type('input[name="llm.openai.api_key"], #openai-api-key', TEST_OPENAI_KEY);
await page.click('button[type="submit"], .save-settings, #save-settings');
diff --git a/tests/ui_tests/playwright/tests/settings-filter-behavior.spec.js b/tests/ui_tests/playwright/tests/settings-filter-behavior.spec.js
index 088864db29..5336f92172 100644
--- a/tests/ui_tests/playwright/tests/settings-filter-behavior.spec.js
+++ b/tests/ui_tests/playwright/tests/settings-filter-behavior.spec.js
@@ -40,10 +40,10 @@ const NONSENSE_QUERY = 'zzz_no_such_setting_xyz';
async function gotoSettings(page) {
await page.goto('/settings/');
- // Use `state: 'attached'` because on mobile the section bodies are collapsed
- // by default — the rows are in the DOM but `display: none`, which makes the
- // default `state: 'visible'` wait time out. We're asserting on counts, not
- // pixel visibility, so DOM-attached is the right gate.
+ // Use `state: 'attached'` because section bodies are collapsed by default
+ // on every viewport — the rows are in the DOM but `display: none`, which
+ // makes the default `state: 'visible'` wait time out. We're asserting on
+ // counts, not pixel visibility, so DOM-attached is the right gate.
await page.waitForSelector(SETTING_ROW, { state: 'attached', timeout: 15000 });
// The settings page fetches its content asynchronously; allSettings is
// populated after the initial render. Wait until at least the first burst
diff --git a/tests/ui_tests/playwright/tests/settings-mobile-collapse.spec.js b/tests/ui_tests/playwright/tests/settings-section-collapse.spec.js
similarity index 55%
rename from tests/ui_tests/playwright/tests/settings-mobile-collapse.spec.js
rename to tests/ui_tests/playwright/tests/settings-section-collapse.spec.js
index 199b823ba0..6863bf9082 100644
--- a/tests/ui_tests/playwright/tests/settings-mobile-collapse.spec.js
+++ b/tests/ui_tests/playwright/tests/settings-section-collapse.spec.js
@@ -1,27 +1,31 @@
/**
- * Settings Mobile Collapse Behavior
+ * Settings Collapse Behavior
*
- * The Settings page renders ~400 controls across ~57 sections. Before this
- * change the page on mobile rendered taller than 16,384 px — Puppeteer's
- * screenshot ceiling and a real UX disaster for the user, who would scroll
- * for what felt like forever. `initAccordions()` now starts every section
- * collapsed at the `(max-width: 767px)` breakpoint; desktop keeps the old
- * "all expanded" default.
+ * The Settings page renders ~400 controls across ~57 sections. Fully
+ * expanded, "All Settings" rendered past 77,000px tall at desktop widths
+ * (and past Puppeteer's 16,384px screenshot ceiling on mobile) — a real UX
+ * disaster, since the user has to scroll forever to find anything.
+ * `initAccordions()` now starts every section collapsed on EVERY viewport;
+ * the user clicks/taps a section header to drill in. This used to only be
+ * true on mobile (`(max-width: 767px)`), leaving desktop with the same wall
+ * of expanded sections — that desktop/mobile inconsistency is exactly what
+ * this spec now pins down as fixed.
*
- * Search filtering must override the collapse: when the user is actively
- * filtering, every surviving section needs to be visible.
+ * Search filtering must still override the collapse: when the user is
+ * actively filtering, every surviving section needs to be visible.
*
- * Three cases worth pinning down:
+ * Cases covered:
*
- * 1. Mobile (small viewport): sections start collapsed; page height
- * drops well below the 16,384 px ceiling.
- * 2. Desktop: sections start expanded — same as the previous behavior,
- * so power-user workflows aren't disrupted.
- * 3. Mobile + active search: surviving sections are force-expanded so
- * matches aren't hidden behind a tap.
+ * 1. Every viewport (mobile through desktop): sections start collapsed;
+ * page height drops well below the old ~77,000px / 16,384px disaster.
+ * 2. Active search: surviving sections are force-expanded so matches
+ * aren't hidden behind a click/tap.
+ * 3. Clicking/tapping a collapsed header expands it; doing so again
+ * collapses it again — on every viewport, since both now start from
+ * the same collapsed default.
*
- * This spec runs on a small mobile (Pixel 5) and a desktop project; the
- * Playwright project routing keeps each assertion paired with its viewport.
+ * This spec runs across the full device/browser project matrix (see
+ * playwright.config.js) — small mobile through desktop browsers.
*/
import { test, expect } from '@playwright/test';
@@ -42,55 +46,38 @@ async function gotoSettings(page) {
).toBeGreaterThan(5);
}
-async function isMobileViewport(page) {
- // Read the breakpoint from the same constant settings.js uses, so a
- // future change to the threshold doesn't desync the test from production.
- const breakpoint = await page.evaluate(
- () => window.__LDR_MOBILE_BREAKPOINT_PX ?? 767,
- );
- return page.evaluate(
- (bp) => window.matchMedia(`(max-width: ${bp}px)`).matches,
- breakpoint,
- );
-}
-
-test.describe('Settings Mobile Collapse', () => {
- test('sections start collapsed on mobile, expanded on desktop', async ({ page }) => {
+test.describe('Settings Collapse', () => {
+ test('every section starts collapsed, on every viewport', async ({ page }) => {
await gotoSettings(page);
- const mobile = await isMobileViewport(page);
const stats = await page.evaluate(([headerSel, bodySel]) => {
const headers = Array.from(document.querySelectorAll(headerSel));
const bodies = Array.from(document.querySelectorAll(bodySel));
return {
total: headers.length,
collapsed: headers.filter((h) => h.classList.contains('collapsed')).length,
+ ariaCollapsed: headers.filter((h) => h.getAttribute('aria-expanded') === 'false').length,
visibleBodies: bodies.filter((b) => getComputedStyle(b).display !== 'none').length,
};
}, [SECTION_HEADER, SECTION_BODY]);
expect(stats.total, 'should render multiple sections').toBeGreaterThan(5);
-
- if (mobile) {
- expect(stats.collapsed, 'every section should start collapsed on mobile').toBe(stats.total);
- expect(stats.visibleBodies, 'no section body visible on mobile').toBe(0);
- } else {
- expect(stats.collapsed, 'no section should start collapsed on desktop').toBe(0);
- expect(stats.visibleBodies, 'every section body visible on desktop').toBe(stats.total);
- }
+ expect(stats.collapsed, 'every section should start collapsed').toBe(stats.total);
+ expect(stats.ariaCollapsed, 'aria-expanded should be false on every collapsed header').toBe(stats.total);
+ expect(stats.visibleBodies, 'no section body should be visible by default').toBe(0);
});
- test('mobile page height drops below the 16384px screenshot ceiling', async ({ page }) => {
+ test('page height drops well below the old expanded-by-default height', async ({ page }) => {
await gotoSettings(page);
- const mobile = await isMobileViewport(page);
- test.skip(!mobile, 'page-height assertion is only meaningful at the mobile breakpoint');
const pageHeight = await page.evaluate(() => document.documentElement.scrollHeight);
- // The bug we're fixing rendered the page > 16,384px tall. Pick a
- // comfortable bound below that (10,000px) — a regression that
- // re-expands sections by default would blow past 16,384 again.
- expect(pageHeight, 'collapsed Settings should be well under 16384px tall').toBeLessThan(10000);
+ // The bug we're fixing rendered the page tens of thousands of pixels
+ // tall on every viewport (77,097px measured at 1440px desktop width;
+ // >16,384px on mobile, blowing past the screenshot ceiling). Pick a
+ // comfortable bound (10,000px) well under either — a regression that
+ // re-expands sections by default would blow past it again.
+ expect(pageHeight, 'collapsed Settings should be well under 10000px tall').toBeLessThan(10000);
});
test('active search forces surviving sections to expand', async ({ page }) => {
@@ -124,12 +111,10 @@ test.describe('Settings Mobile Collapse', () => {
expect(post.total, 'search should still return matching sections').toBeGreaterThan(0);
});
- test('tapping a collapsed header expands it; tapping again collapses', async ({ page }) => {
+ test('clicking/tapping a collapsed header expands it; doing so again collapses it', async ({ page }) => {
await gotoSettings(page);
- const mobile = await isMobileViewport(page);
- test.skip(!mobile, 'desktop sections start expanded; the toggle starting state differs there');
- // First tap: expand
+ // First activation: expand
await page.locator(SECTION_HEADER).first().click();
await expect.poll(
async () => page.evaluate((sel) => {
@@ -137,13 +122,14 @@ test.describe('Settings Mobile Collapse', () => {
const body = document.getElementById(h.getAttribute('data-target'));
return {
collapsed: h.classList.contains('collapsed'),
+ ariaExpanded: h.getAttribute('aria-expanded'),
bodyDisplay: body ? getComputedStyle(body).display : null,
};
}, SECTION_HEADER),
- { timeout: 2000, message: 'first tap should expand the section' },
- ).toEqual({ collapsed: false, bodyDisplay: 'block' });
+ { timeout: 2000, message: 'first activation should expand the section' },
+ ).toEqual({ collapsed: false, ariaExpanded: 'true', bodyDisplay: 'block' });
- // Second tap: collapse again
+ // Second activation: collapse again
await page.locator(SECTION_HEADER).first().click();
await expect.poll(
async () => page.evaluate((sel) => {
@@ -151,10 +137,11 @@ test.describe('Settings Mobile Collapse', () => {
const body = document.getElementById(h.getAttribute('data-target'));
return {
collapsed: h.classList.contains('collapsed'),
+ ariaExpanded: h.getAttribute('aria-expanded'),
bodyDisplay: body ? getComputedStyle(body).display : null,
};
}, SECTION_HEADER),
- { timeout: 2000, message: 'second tap should collapse the section again' },
- ).toEqual({ collapsed: true, bodyDisplay: 'none' });
+ { timeout: 2000, message: 'second activation should collapse the section again' },
+ ).toEqual({ collapsed: true, ariaExpanded: 'false', bodyDisplay: 'none' });
});
});
diff --git a/tests/ui_tests/test_lib/index.js b/tests/ui_tests/test_lib/index.js
index 91cbd87d16..8d41972a4d 100644
--- a/tests/ui_tests/test_lib/index.js
+++ b/tests/ui_tests/test_lib/index.js
@@ -48,6 +48,8 @@ const {
getInputValue,
clearAndType,
findActionButton,
+ expandSettingsSectionFor,
+ expandAllSettingsSections,
log,
} = require('./test_utils');
@@ -73,6 +75,8 @@ module.exports = {
getInputValue,
clearAndType,
findActionButton,
+ expandSettingsSectionFor,
+ expandAllSettingsSections,
// Logging
log,
diff --git a/tests/ui_tests/test_lib/test_utils.js b/tests/ui_tests/test_lib/test_utils.js
index 4a588f4327..a41447fde8 100644
--- a/tests/ui_tests/test_lib/test_utils.js
+++ b/tests/ui_tests/test_lib/test_utils.js
@@ -325,6 +325,142 @@ async function findActionButton(page, options = {}) {
}, selectors, keywords, click);
}
+/**
+ * Expand the Settings section that owns a control, so it can be clicked.
+ *
+ * Settings sections start collapsed on EVERY viewport now (not just mobile):
+ * `initAccordions()` puts `.collapsed` on the section body and
+ * `.ldr-settings-section-body.collapsed { display: none }` in settings.css
+ * takes it out of the layout. A control inside one is present in the DOM —
+ * so `waitForSelector` (whose `visible` option defaults to false) still
+ * resolves — but it has no box, so `page.click()` / `elementHandle.click()`
+ * throws or lands on whatever is actually at those coordinates.
+ *
+ * Call this before interacting with any settings control. It finds the
+ * closest `.ldr-settings-section-body.collapsed` ancestor of the target and
+ * clicks that section's `.ldr-settings-section-header`, then waits for the
+ * body to lose `collapsed`. A target that is already visible, or that is not
+ * inside a section at all, is left alone.
+ *
+ * @param {import('puppeteer').Page} page
+ * @param {string|import('puppeteer').ElementHandle} target - CSS selector for
+ * the control, or an ElementHandle for it.
+ * @param {Object} [options]
+ * @param {number} [options.timeout] - Wait budget for the target and for the
+ * section to open. Defaults to the shared config timeout.
+ * @returns {Promise<string>} One of 'already-expanded' | 'expanded' |
+ * 'no-section' | 'no-header' | 'no-target' — for logging; callers that just
+ * want the control clickable can ignore it.
+ */
+async function expandSettingsSectionFor(page, target, options = {}) {
+ const timeout = options.timeout || config.timeout;
+
+ // Runs in page context with the target element as its argument.
+ const expandFor = (el) => {
+ if (!el) return 'no-target';
+ const body = el.closest('.ldr-settings-section-body');
+ if (!body) return 'no-section';
+ if (!body.classList.contains('collapsed')) return 'already-expanded';
+
+ // Resolve the header by node relationship / data-target equality
+ // instead of building a selector from body.id, which is derived from
+ // a server-supplied category name.
+ let header = body.previousElementSibling;
+ if (!header || !header.classList.contains('ldr-settings-section-header')) {
+ header = Array.from(document.querySelectorAll('.ldr-settings-section-header'))
+ .find(candidate => candidate.dataset.target === body.id) || null;
+ }
+ if (!header) return 'no-header';
+ header.click();
+ return 'expanded';
+ };
+
+ let outcome;
+ if (typeof target === 'string') {
+ await page.waitForSelector(target, { timeout });
+ outcome = await page.$eval(target, expandFor);
+ } else {
+ outcome = await page.evaluate(expandFor, target);
+ }
+
+ // Wait for the section to actually open. The click handler applies the
+ // class synchronously, but polling beats racing the DOM swap.
+ if (outcome === 'expanded') {
+ if (typeof target === 'string') {
+ await page.waitForFunction(
+ (sel) => {
+ const el = document.querySelector(sel);
+ if (!el) return false;
+ const body = el.closest('.ldr-settings-section-body');
+ return !body || !body.classList.contains('collapsed');
+ },
+ { timeout },
+ target
+ );
+ } else {
+ await page.waitForFunction(
+ (el) => {
+ if (!el) return false;
+ const body = el.closest('.ldr-settings-section-body');
+ return !body || !body.classList.contains('collapsed');
+ },
+ { timeout },
+ target
+ );
+ }
+ }
+
+ return outcome;
+}
+
+/**
+ * Expand every collapsed Settings section on the page.
+ *
+ * Sections start collapsed on every viewport now, and
+ * `.ldr-settings-section-body.collapsed { display: none }` hides everything
+ * inside them. Any check that filters by visibility — `offsetParent === null`,
+ * `getComputedStyle(el).display` — is therefore blind to whatever those
+ * bodies contain, so a suite that means "nothing on the settings page shows an
+ * error" has to open the sections before it counts, or it passes vacuously.
+ *
+ * Clicks each collapsed header in page context, i.e. the same gesture a user
+ * makes, so the accordion's own handler runs (and, as for a user, the
+ * expanded state is remembered in localStorage). A page with no settings
+ * sections is left alone.
+ *
+ * @param {import('puppeteer').Page} page
+ * @param {Object} [options]
+ * @param {number} [options.timeout] - Wait budget for the sections to open.
+ * Defaults to the shared config timeout.
+ * @returns {Promise<number>} How many sections were expanded.
+ */
+async function expandAllSettingsSections(page, options = {}) {
+ const timeout = options.timeout || config.timeout;
+
+ const expanded = await page.evaluate(() => {
+ let clicked = 0;
+ document.querySelectorAll('.ldr-settings-section-header').forEach(header => {
+ // Resolve the body the way initAccordions does, by id, rather than
+ // building a selector out of a server-derived category name.
+ const body = document.getElementById(header.dataset.target);
+ if (body && body.classList.contains('collapsed')) {
+ header.click();
+ clicked++;
+ }
+ });
+ return clicked;
+ });
+
+ if (expanded > 0) {
+ await page.waitForFunction(
+ () => document.querySelectorAll('.ldr-settings-section-body.collapsed').length === 0,
+ { timeout }
+ );
+ }
+
+ return expanded;
+}
+
// Console logging with colors (works in terminal)
const log = {
info: (msg) => console.log(`\x1b[36m[INFO] ${msg}\x1b[0m`),
@@ -354,5 +490,7 @@ module.exports = {
getInputValue,
clearAndType,
findActionButton,
+ expandSettingsSectionFor,
+ expandAllSettingsSections,
log,
};
diff --git a/tests/ui_tests/test_settings_errors.js b/tests/ui_tests/test_settings_errors.js
index b160d68013..2c86f9505f 100644
--- a/tests/ui_tests/test_settings_errors.js
+++ b/tests/ui_tests/test_settings_errors.js
@@ -20,6 +20,7 @@
const puppeteer = require('puppeteer');
const AuthHelper = require('./auth_helper');
const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
+const { expandAllSettingsSections } = require('./test_lib');
async function testSettingsChange() {
const browser = await puppeteer.launch(getPuppeteerLaunchOptions());
@@ -106,6 +107,20 @@ async function testSettingsChange() {
// of visibility, so failing on mere presence would fail every run
// whatever the page did — swapping a test that could never fail for
// one that could never pass, which is no better.
+ // ...and "visible" is only meaningful once the sections are open.
+ // Field-level errors are created on demand by settings.js's
+ // `markInvalidInput`, which already reveals the section it just
+ // wrote into, and a top-level `showAlert` banner writes into
+ // `#settings-alert` / `#filtered-settings-alert`, both outside every
+ // `.ldr-settings-section-body`. So neither real error source
+ // strictly depends on this expand to be visible. It is defensive:
+ // without it, an error container that does end up inside a
+ // collapsed body could still be hidden from the filter below by
+ // `offsetParent === null`, letting the suite pass no matter what the
+ // page did.
+ const expandedSections = await expandAllSettingsSections(page);
+ console.log(`🔓 Expanded ${expandedSections} collapsed settings section(s) before checking`);
+
const errorElements = await page.$$('.error, .alert-danger, .text-danger, [class*="error"]');
const shownErrors = [];
for (const el of errorElements) {
diff --git a/tests/ui_tests/test_settings_interactions_ci.js b/tests/ui_tests/test_settings_interactions_ci.js
index bb2c387683..d37d90f881 100644
--- a/tests/ui_tests/test_settings_interactions_ci.js
+++ b/tests/ui_tests/test_settings_interactions_ci.js
@@ -8,7 +8,15 @@
* Run: node test_settings_interactions_ci.js
*/
-const { setupTest, teardownTest, TestResults, log, navigateTo, withTimeout } = require('./test_lib');
+const {
+ setupTest,
+ teardownTest,
+ TestResults,
+ log,
+ navigateTo,
+ withTimeout,
+ expandSettingsSectionFor,
+} = require('./test_lib');
// ============================================================================
// Settings Page Structure Tests
@@ -321,6 +329,9 @@ const SettingsControlsTests = {
await navigateTo(page, `${baseUrl}/settings`);
const sel = '#settings-content input.ldr-settings-checkbox[name]:not([disabled])';
await page.waitForSelector(sel, { timeout: 15000 });
+ // Sections start collapsed on every viewport, so the checkbox is in
+ // the DOM but `display: none` until its section is opened.
+ await expandSettingsSectionFor(page, sel, { timeout: 15000 });
const before = await page.$eval(sel, el => el.checked);
await page.click(sel);
@@ -410,6 +421,8 @@ const SettingsSaveTests = {
await navigateTo(page, `${baseUrl}/settings`);
const sel = '#settings-content input.ldr-settings-checkbox[name]:not([disabled])';
await page.waitForSelector(sel, { timeout: 15000 });
+ // Collapsed-by-default sections hide the checkbox; open its section.
+ await expandSettingsSectionFor(page, sel, { timeout: 15000 });
await page.click(sel);
diff --git a/tests/ui_tests/test_settings_persistence_ci.js b/tests/ui_tests/test_settings_persistence_ci.js
index 6889f82613..64bc2053d1 100644
--- a/tests/ui_tests/test_settings_persistence_ci.js
+++ b/tests/ui_tests/test_settings_persistence_ci.js
@@ -73,6 +73,7 @@ const crypto = require('crypto');
const puppeteer = require('puppeteer');
const AuthHelper = require('./auth_helper');
const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
+const { expandSettingsSectionFor } = require('./test_lib');
const { capture, captureOnFailure } = require('./screenshot_helper');
const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:5000';
@@ -141,6 +142,10 @@ async function run() {
timeout: TIMEOUTS.navigation,
});
await workingPage.waitForSelector(SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
+ // Settings sections start collapsed on every viewport, so the
+ // checkbox renders inside a `display: none` body. Open its section
+ // before any click — page.click() needs a real box to hit.
+ await expandSettingsSectionFor(workingPage, SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
await capture(workingPage, SCREENSHOT_PREFIX, 'before_toggle', { fullPage: true });
// -----------------------------------------------------------------
@@ -169,6 +174,7 @@ async function run() {
await workingPage.reload({ waitUntil: 'domcontentloaded', timeout: TIMEOUTS.navigation });
await workingPage.waitForSelector(SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
+ await expandSettingsSectionFor(workingPage, SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
const afterReload = await workingPage.$eval(SETTING_SELECTOR, (el) => el.checked);
if (afterReload === originalValue) {
@@ -364,6 +370,8 @@ async function run() {
if (changeWasApplied && originalValue !== null) {
await workingPage.bringToFront().catch(() => {});
await workingPage.waitForSelector(SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
+ // The cleanup click needs the owning section open too.
+ await expandSettingsSectionFor(workingPage, SETTING_SELECTOR, { timeout: TIMEOUTS.selector });
const currentValue = await workingPage.$eval(SETTING_SELECTOR, (el) => el.checked);
if (currentValue !== originalValue) {
diff --git a/tests/ui_tests/test_settings_save.js b/tests/ui_tests/test_settings_save.js
index 16da5ac46c..b540137446 100644
--- a/tests/ui_tests/test_settings_save.js
+++ b/tests/ui_tests/test_settings_save.js
@@ -19,7 +19,7 @@
* Usage: node tests/ui_tests/test_settings_save.js
*/
-const { setupTest, teardownTest, navigateTo } = require('./test_lib');
+const { setupTest, teardownTest, navigateTo, expandSettingsSectionFor } = require('./test_lib');
async function testSettingsSave() {
const ctx = await setupTest({ authenticate: true });
@@ -58,7 +58,13 @@ async function testSettingsSave() {
throw new Error('Save All Settings button should not be present');
}
- const checkbox = await page.$('.ldr-settings-checkbox:not([disabled])');
+ // Settings sections start collapsed on every viewport now, so the
+ // checkbox is rendered inside a `display: none` body. Open its
+ // section before clicking, or the click has no box to land on.
+ const checkboxSelector = '.ldr-settings-checkbox:not([disabled])';
+ await expandSettingsSectionFor(page, checkboxSelector, { timeout: 15000 });
+
+ const checkbox = await page.$(checkboxSelector);
const responsePromise = page.waitForResponse(
r => r.url().includes('/save_all_settings'),
{ timeout: 15000 }
diff --git a/tests/ui_tests/test_settings_save_error_ci.js b/tests/ui_tests/test_settings_save_error_ci.js
index 6b339a2f75..7cb955bd1f 100644
--- a/tests/ui_tests/test_settings_save_error_ci.js
+++ b/tests/ui_tests/test_settings_save_error_ci.js
@@ -1,5 +1,12 @@
#!/usr/bin/env node
-const { setupTest, teardownTest, TestResults, log, navigateTo } = require('./test_lib');
+const {
+ setupTest,
+ teardownTest,
+ TestResults,
+ log,
+ navigateTo,
+ expandSettingsSectionFor,
+} = require('./test_lib');
const checkboxSelector = 'input.ldr-settings-checkbox:not([disabled])';
const errorBannerSelector = '#notification-banner-assertive';
@@ -120,6 +127,13 @@ async function captureCheckboxBaseline(page, baseUrl) {
}
async function getTargetCheckbox(page, baseline) {
+ // Settings sections start collapsed on every viewport now, so the
+ // checkbox is in the DOM but inside a `display: none` body — a click on
+ // it would have no box to land on. Open its section first. Every
+ // .click() in this suite goes through the handle returned here, so this
+ // one call covers the fresh-navigation and post-reload paths alike.
+ await expandSettingsSectionFor(page, checkboxSelector, { timeout: 15000 });
+
const checkbox = await page.$(checkboxSelector);
assertCondition(checkbox, `Checkbox ${baseline.key} was not found`);
const identity = await checkbox.evaluate(input => ({ id: input.id, key: input.name }));
diff --git a/tests/ui_tests/test_settings_validation.js b/tests/ui_tests/test_settings_validation.js
index 6bdf08c72e..c141228024 100644
--- a/tests/ui_tests/test_settings_validation.js
+++ b/tests/ui_tests/test_settings_validation.js
@@ -8,6 +8,7 @@ const puppeteer = require('puppeteer');
const AuthHelper = require('./auth_helper');
const { Timer, CI_TEST_USER } = require('./auth_helper');
const { getPuppeteerLaunchOptions } = require('./puppeteer_config');
+const { expandSettingsSectionFor } = require('./test_lib');
const fs = require('fs');
const path = require('path');
@@ -146,6 +147,11 @@ async function testSettingsValidation() {
// Try to toggle a checkbox
try {
const firstCheckbox = checkboxInputs[0];
+ // Settings sections start collapsed on every viewport, so a
+ // checkbox inside one is `display: none` and click() throws.
+ // Open its section first (a no-op for checkboxes that live
+ // outside a settings section).
+ await expandSettingsSectionFor(page, firstCheckbox);
const initialState = await page.evaluate(el => el.checked, firstCheckbox);
await firstCheckbox.click();
await new Promise(resolve => setTimeout(resolve, 500));
@@ -161,7 +167,12 @@ async function testSettingsValidation() {
// Toggle back
await firstCheckbox.click();
} catch (e) {
- console.log(`⚠️ Could not test checkbox interaction: ${e.message}`);
+ // Counted as a failure, not warned about: a checkbox that
+ // cannot be clicked is exactly how a collapsed-section
+ // regression shows up here, and swallowing it silently
+ // degraded this suite's coverage to nothing.
+ console.log(`❌ Could not test checkbox interaction: ${e.message}`);
+ testsFailed++;
}
} else {
console.log('⚠️ No checkboxes found');