~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 light theme readability and control visibility (#6684)
LearningCircuiteaed30807071
diff --git a/.github/workflows/docker-tests.yml b/.github/workflows/docker-tests.ymlindex a38457603b..bf7e1513c8 100644--- a/.github/workflows/docker-tests.yml+++ b/.github/workflows/docker-tests.yml@@ -112,6 +112,10 @@ jobs:- 'src/local_deep_research/web/**'- '.github/workflows/docker-tests.yml'accessibility:+ # Theme palettes (and the loader/schema that validate them) are+ # what theme-contrast.spec.js renders; without this a theme-only+ # PR would skip the rendered contrast gate entirely.+ - 'src/local_deep_research/web/themes/**'- 'src/local_deep_research/web/templates/**'- 'src/local_deep_research/web/static/css/**'- 'src/local_deep_research/web/static/js/**'@@ -1155,7 +1159,7 @@ jobs:# Run accessibility tests (Playwright a11y + Lighthouse)accessibility-tests:runs-on: ubuntu-latest- timeout-minutes: 15+ timeout-minutes: 25name: Accessibility Testsneeds: [build-test-image, detect-changes]if: needs.detect-changes.outputs.accessibility == 'true' || github.event_name == 'workflow_dispatch' || inputs.strict-mode == true@@ -1251,7 +1255,9 @@ jobs:node register_ci_user.js http://localhost:5000- name: Run Playwright accessibility tests- timeout-minutes: 5+ # Eight light palettes across desktop/mobile pages run on one CI worker+ # (about 6 minutes on the PR run); leave headroom for slower runners.+ timeout-minutes: 15run: |docker run --rm \-v "$PWD":/app \diff --git a/changelog.d/6684.bugfix.md b/changelog.d/6684.bugfix.mdnew file mode 100644index 0000000000..82ac50527e--- /dev/null+++ b/changelog.d/6684.bugfix.md@@ -0,0 +1 @@+Improve readability and control visibility in Sepia and the other light themes, including form outlines, close icons, dropdown arrows and status labels and alerts. The redrawn dropdown arrows and close icons remain visible in Windows High Contrast mode. Keep Create Collection visible on phones and improve collection-card text and status readability. Some changes apply to every theme: search-match highlights in model/engine dropdowns and the note link picker use the regular text color on a lighter tint, the benchmark search-count warning badge uses the theme's warning ink (dark in dark themes, white in light themes), text on controls and badges filled with the theme's primary or secondary accent color (primary buttons, outline buttons on hover and keyboard focus, active filters, tabs, pagination and time-range selectors, the skip link, the selected settings tab, the Chat send button, Notes buttons and the selected search mode, settings checkbox ticks, Link Analytics, Journal Quality and Zotero buttons, Metrics icons, and accent badges and counters) uses black in dark themes, where white was unreadable on their light accents, accent-filled links (Create Collection, Upload, View Collection, the Library's RAG Indexed badge and the skip link) keep that label colour on hover instead of turning the accent colour, and in High Contrast accent-filled links no longer take the cyan or green link colour on their yellow fill, the Library filter selects show their dropdown arrow again, inline code no longer uses Bootstrap's pink, outline buttons follow the theme accent, and privacy-panel headers, collection cards, sidebar links and chat hints use flat theme colors. Every control and badge filled with the theme's error red, including the log panel's error-count badge, now uses a label colour chosen for that red: black in most dark themes and the default Hashed theme, white in the light themes and Kanagawa. Badges filled with the warning colour use the theme's warning label colour (dark in dark themes, white in light themes). Buttons and badges filled with the success green that had white labels now use a new per-theme success label colour (black in dark themes, including Hashed, where white was unreadable on most of their greens; white in light themes). The Metrics page's search-engine health badges use these label colours, the Journal Quality data-source pills are filled with the status colour, and Benchmark Results notifications use darker fills behind their white text.diff --git a/src/local_deep_research/web/static/css/benchmark.css b/src/local_deep_research/web/static/css/benchmark.cssindex 9b3d58fad3..6a15abf093 100644--- a/src/local_deep_research/web/static/css/benchmark.css+++ b/src/local_deep_research/web/static/css/benchmark.css@@ -220,7 +220,7 @@.ldr-result-card .ldr-dataset-badge,.ldr-question-card .ldr-dataset-badge {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);padding: 2px 8px;border-radius: 12px;font-size: 0.8rem;@@ -238,14 +238,17 @@.ldr-search-count-badge.ldr-critical {background: var(--error-color);+ color: var(--text-on-error);}.ldr-search-count-badge.ldr-warning {background: var(--warning-color);+ color: var(--text-on-warning);}.ldr-search-count-badge.ldr-good {background: var(--success-color);+ color: var(--text-on-success);}.ldr-processing-status {@@ -874,6 +877,7 @@.ldr-pagination button:hover {background: var(--primary-color);+ color: var(--text-on-accent);}.ldr-pagination button:disabled {@@ -892,7 +896,7 @@.ldr-delete-btn:hover:not(:disabled) {background: var(--error-color) !important;- color: white !important;+ color: var(--text-on-error) !important;}.ldr-delete-btn:disabled {@@ -913,7 +917,7 @@.ldr-download-btn:hover {background: var(--success-color) !important;- color: white !important;+ color: var(--text-on-success) !important;}.ldr-filters {diff --git a/src/local_deep_research/web/static/css/chat.css b/src/local_deep_research/web/static/css/chat.cssindex 2515c8407c..dcf36b3cee 100644--- a/src/local_deep_research/web/static/css/chat.css+++ b/src/local_deep_research/web/static/css/chat.css@@ -642,7 +642,7 @@.ldr-chat-stop-btn:hover:not(:disabled) {background: var(--error-color, #fa5c7c);- color: white;+ color: var(--text-on-error);}.ldr-chat-stop-btn:disabled {@@ -740,7 +740,7 @@border-radius: 10px;background: var(--accent-primary, #6e4ff6);border: none;- color: white;+ color: var(--text-on-accent);cursor: pointer;display: flex;align-items: center;@@ -786,16 +786,16 @@gap: 1rem;margin-top: 0.5rem;padding: 0 0.5rem;- font-size: 0.6875rem;+ font-size: 0.75rem;color: var(--text-muted, #8a8aa0);- opacity: 0.7;}.ldr-chat-input-hints kbd {+ color: var(--text-primary);background: var(--bg-tertiary, #2a2a3a);padding: 0.0625rem 0.3125rem;border-radius: 3px;- font-size: 0.625rem;+ font-size: inherit;font-family: inherit;}diff --git a/src/local_deep_research/web/static/css/collection_details.css b/src/local_deep_research/web/static/css/collection_details.cssindex a6dcb03116..31529eaeb5 100644--- a/src/local_deep_research/web/static/css/collection_details.css+++ b/src/local_deep_research/web/static/css/collection_details.css@@ -141,7 +141,7 @@.ldr-btn-primary {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-btn-primary:hover {@@ -174,10 +174,12 @@.ldr-btn-danger {background: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-btn-danger:hover {+ /* Keeps the ink if the button is ever a link (a:hover is 0,1,1). */+ color: var(--text-on-error);filter: brightness(1.1);transform: translateY(-2px);box-shadow: 0 8px 25px rgba(var(--error-color-rgb), 0.3);@@ -276,7 +278,7 @@.ldr-filter-controls .btn.active {background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -286,7 +288,7 @@}.ldr-filter-controls .btn.active:hover {- color: white;+ color: var(--text-on-accent);}/* Documents List */@@ -495,7 +497,7 @@.ldr-badge-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-badge-warning {@@ -982,7 +984,7 @@.ldr-btn-collections-primary {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);- color: white;+ color: var(--text-on-accent);box-shadow: 0 4px 15px rgba(var(--accent-primary-rgb), 0.3);border: 3px solid var(--accent-primary);}@@ -1011,6 +1013,22 @@}}+/* Upload and the View Collection links are anchors; a:hover (0,1,1) would+ draw the accent on the accent fill, so the hover rule (0,2,0) restates+ the ink. */+.ldr-btn-collections-primary:hover,+.ldr-btn-collections-primary:focus {+ color: var(--text-on-accent);+}++/* The create/upload result links sit in an .ldr-alert, whose link colours+ (.ldr-alert a, 0,1,1; .ldr-alert a:hover, 0,2,1) outrank the button. */+.ldr-alert a.ldr-btn-collections-primary,+.ldr-alert a.ldr-btn-collections-primary:hover,+.ldr-alert a.ldr-btn-collections-primary:focus-visible {+ color: var(--text-on-accent);+}+.ldr-btn-collections-primary:hover {transform: translateY(-2px);box-shadow: 0 6px 20px rgba(var(--accent-primary-rgb), 0.4);@@ -1031,7 +1049,7 @@.ldr-btn-collections-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);box-shadow: 0 4px 15px rgba(var(--success-color-rgb), 0.3);}@@ -1053,7 +1071,7 @@.ldr-btn-collections-danger {background: var(--error-color);- color: white;+ color: var(--text-on-error);box-shadow: 0 4px 15px rgba(var(--error-color-rgb), 0.3);}@@ -1076,7 +1094,7 @@.ldr-btn-outline-primary:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);}.ldr-btn-outline-success {@@ -1087,7 +1105,7 @@.ldr-btn-outline-success:hover {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-btn-outline-warning {@@ -1103,7 +1121,7 @@.ldr-active {background: var(--accent-primary) !important;- color: white !important;+ color: var(--text-on-accent) !important;}/* Embedding Settings Card - Optimized */diff --git a/src/local_deep_research/web/static/css/collections.css b/src/local_deep_research/web/static/css/collections.cssindex b0302161f2..4d9044bcce 100644--- a/src/local_deep_research/web/static/css/collections.css+++ b/src/local_deep_research/web/static/css/collections.css@@ -86,6 +86,8 @@display: flex;justify-content: space-between;align-items: center;+ flex-wrap: wrap;+ gap: 1rem;margin-bottom: 2rem;padding: 1rem 0;border-bottom: 2px solid var(--border-color);@@ -106,10 +108,40 @@font-size: 1.6rem;}+/* Keep the primary action separate from settings that appear after loading. */+.ldr-collection-settings {+ display: flex;+ flex-wrap: wrap;+ gap: 0.5rem 2rem;+ width: 100%;+}++.ldr-collection-settings .ldr-checkbox-label {+ display: flex;+ align-items: center;+ gap: 0.75rem;+ min-height: 44px;+ min-width: 0;+ font-size: 0.875rem;+ cursor: pointer;+}++/* The whole label provides the touch target; the native checkbox stays compact. */+.ldr-collection-settings input[type="checkbox"] {+ flex: 0 0 1rem;+ width: 1rem;+ height: 1rem;+ min-width: 1rem;+ min-height: 1rem;+ margin: 0;+ padding: 0;+ accent-color: var(--accent-primary);+}+/* Collections Grid */.ldr-collections-grid {display: grid;- grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));+ grid-template-columns: repeat(auto-fill, minmax(min(350px, 100%), 1fr));gap: 2rem;margin-bottom: 2rem;}@@ -120,7 +152,7 @@.ldr-collection-card-wrapper {display: flex;flex-direction: column;- background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);+ background: var(--bg-secondary);border-radius: 16px;border: 1px solid var(--border-color);transition: border-color 0.3s ease, transform 0.3s ease, box-shadow 0.3s ease;@@ -146,22 +178,6 @@cursor: pointer;}-.ldr-collection-card-wrapper::before {- content: '';- position: absolute;- top: 0;- left: -100%;- width: 100%;- height: 100%;- background: linear-gradient(90deg, transparent, rgba(var(--accent-primary-rgb), 0.1), transparent);- transition: left 0.6s ease;- pointer-events: none;-}--.ldr-collection-card-wrapper:hover::before {- left: 100%;-}-.ldr-collection-header {margin-bottom: 1.5rem;}@@ -174,6 +190,7 @@display: flex;align-items: center;gap: 0.5rem;+ overflow-wrap: anywhere;}.ldr-collection-header h3::before {@@ -195,9 +212,9 @@gap: 1rem;margin-bottom: 1.5rem;padding: 1rem;- background: rgba(var(--shadow-color-rgb), 0.2);+ background: var(--bg-tertiary);border-radius: 12px;- border: 1px solid rgba(var(--highlight-color-rgb), 0.05);+ border: 1px solid var(--border-color);}.ldr-stat-item {@@ -207,18 +224,22 @@font-size: 0.9rem;color: var(--text-secondary);padding: 0.5rem 0.75rem;- background: rgba(var(--accent-primary-rgb), 0.1);+ background: var(--bg-secondary);border-radius: 8px;- border: 1px solid rgba(var(--accent-primary-rgb), 0.2);+ border: 1px solid var(--border-color);+ min-width: 0;+ max-width: 100%;+ overflow-wrap: anywhere;transition: all 0.2s ease;}.ldr-stat-item:hover {- background: rgba(var(--accent-primary-rgb), 0.2);+ background: var(--bg-primary);transform: translateY(-2px);}.ldr-stat-item i {+ flex-shrink: 0;color: var(--accent-primary);font-size: 1rem;}@@ -290,7 +311,6 @@color: var(--text-secondary);font-size: 0.9rem;font-weight: 500;- opacity: 0.7;transition: all 0.3s ease;}@@ -300,7 +320,6 @@}.ldr-collection-card-wrapper:hover .ldr-collection-view-link {- opacity: 1;color: var(--accent-primary);}@@ -528,10 +547,17 @@.ldr-btn-collections-primary {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);- color: white;+ color: var(--text-on-accent);box-shadow: 0 4px 15px rgba(var(--accent-primary-rgb), 0.3);}+/* Create Collection is a link; a:hover (0,1,1) would draw the accent on+ the accent fill, so the hover rule (0,2,0) restates the ink. */+.ldr-btn-collections-primary:hover,+.ldr-btn-collections-primary:focus {+ color: var(--text-on-accent);+}+.ldr-btn-collections-primary:hover {transform: translateY(-2px);box-shadow: 0 6px 20px rgba(var(--accent-primary-rgb), 0.4);@@ -576,7 +602,7 @@.ldr-btn-collections-danger {background: var(--error-color);- color: var(--bg-primary);+ color: var(--text-on-error);box-shadow: 0 4px 15px rgba(var(--error-color-rgb), 0.3);}@@ -599,7 +625,7 @@.ldr-btn-outline-primary:hover {background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);transform: translateY(-2px);}@@ -629,7 +655,7 @@.ldr-active {background-color: var(--accent-primary) !important;- color: white !important;+ color: var(--text-on-accent) !important;border-color: var(--accent-primary) !important;}@@ -654,7 +680,7 @@}.ldr-collections-grid {- grid-template-columns: 1fr;+ grid-template-columns: minmax(0, 1fr);gap: 1.5rem;}@@ -664,6 +690,14 @@gap: 1rem;}+ .ldr-section-header > .ldr-btn-collections {+ align-self: stretch;+ }++ .ldr-collection-settings {+ flex-direction: column;+ }+.ldr-collection-stats {flex-direction: column;gap: 0.75rem;@@ -708,10 +742,6 @@/* Dark theme enhancements */@media (prefers-color-scheme: dark) {- .ldr-collection-card-wrapper::before {- background: linear-gradient(90deg, transparent, rgba(var(--accent-primary-rgb), 0.15), transparent);- }-.ldr-modal {background-color: rgba(var(--shadow-color-rgb), 0.8);}diff --git a/src/local_deep_research/web/static/css/components/pagination.css b/src/local_deep_research/web/static/css/components/pagination.cssindex 5f814e24bf..921b10086a 100644--- a/src/local_deep_research/web/static/css/components/pagination.css+++ b/src/local_deep_research/web/static/css/components/pagination.css@@ -31,13 +31,13 @@.ldr-page-link:hover:not(.disabled):not(.active) {background: var(--primary-color);border-color: var(--primary-color);- color: #fff;+ color: var(--text-on-accent);}.ldr-page-link.active {background: var(--primary-color);border-color: var(--primary-color);- color: #fff;+ color: var(--text-on-accent);font-weight: 600;}diff --git a/src/local_deep_research/web/static/css/context_overflow.css b/src/local_deep_research/web/static/css/context_overflow.cssindex 4bc9417831..cadde0cd15 100644--- a/src/local_deep_research/web/static/css/context_overflow.css+++ b/src/local_deep_research/web/static/css/context_overflow.css@@ -47,7 +47,7 @@align-items: center;justify-content: center;background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-radius: 0.375rem;margin-bottom: 1rem;}@@ -95,7 +95,7 @@.ldr-truncation-badge {background: var(--error-color);- color: white;+ color: var(--text-on-error);padding: 2px 8px;border-radius: 12px;font-size: 0.75rem;@@ -175,7 +175,7 @@.ldr-time-range-btn.active {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-color: var(--primary-color);}@@ -237,7 +237,7 @@.ldr-context-limit-badge {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);padding: 2px 6px;border-radius: 4px;font-size: 0.75rem;@@ -319,7 +319,7 @@.ldr-pagination-btn:hover:not(:disabled) {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-color: var(--primary-color);}diff --git a/src/local_deep_research/web/static/css/cost_analytics.css b/src/local_deep_research/web/static/css/cost_analytics.cssindex 429a9d4a19..89344982ab 100644--- a/src/local_deep_research/web/static/css/cost_analytics.css+++ b/src/local_deep_research/web/static/css/cost_analytics.css@@ -72,7 +72,7 @@.ldr-time-range-btn:hover,.ldr-time-range-btn.active {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-color: var(--primary-color);}@@ -109,7 +109,7 @@align-items: center;justify-content: center;background: var(--success-color);- color: white;+ color: var(--text-on-success);border-radius: 50%;font-size: 1.25rem;}diff --git a/src/local_deep_research/web/static/css/custom_dropdown.css b/src/local_deep_research/web/static/css/custom_dropdown.cssindex 18aca18216..361947b821 100644--- a/src/local_deep_research/web/static/css/custom_dropdown.css+++ b/src/local_deep_research/web/static/css/custom_dropdown.css@@ -108,7 +108,8 @@ body.ldr-dropdown-active {}.ldr-custom-dropdown-item .ldr-highlight {- background-color: rgba(var(--accent-primary-rgb), 0.3);+ /* Stacks on the 0.1 hover/active tint; 0.2 keeps text-primary at 4.5:1. */+ background-color: rgba(var(--accent-primary-rgb), 0.2);border-radius: 2px;padding: 0 2px;}diff --git a/src/local_deep_research/web/static/css/document_details.css b/src/local_deep_research/web/static/css/document_details.cssindex 8e723ccf56..fd86c59efd 100644--- a/src/local_deep_research/web/static/css/document_details.css+++ b/src/local_deep_research/web/static/css/document_details.css@@ -127,20 +127,26 @@.ldr-btn-success {background: var(--success-color);- color: var(--bg-primary);+ color: var(--text-on-success);}+/* The View Text button is a link: styles.css a:hover (0,1,1) would+ otherwise recolour it. */.ldr-btn-success:hover {+ color: var(--text-on-success);filter: brightness(1.1);box-shadow: 0 8px 25px rgba(var(--success-color-rgb), 0.3);}.ldr-btn-danger {background: var(--error-color);- color: white;+ color: var(--text-on-error);}+/* The View PDF button is a link: styles.css a:hover (0,1,1) would+ otherwise recolour it. */.ldr-btn-danger:hover {+ color: var(--text-on-error);filter: brightness(1.1);box-shadow: 0 8px 25px rgba(var(--error-color-rgb), 0.3);}diff --git a/src/local_deep_research/web/static/css/download_manager.css b/src/local_deep_research/web/static/css/download_manager.cssindex ae593a162e..b29e2c5b03 100644--- a/src/local_deep_research/web/static/css/download_manager.css+++ b/src/local_deep_research/web/static/css/download_manager.css@@ -40,7 +40,7 @@.ldr-download-buttons .btn.btn-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);border: 1px solid var(--success-color);}@@ -212,6 +212,12 @@background: var(--bg-tertiary);}+/* Bootstrap's form-control removes the native arrow; these filters do not+ provide a custom replacement. Restore the dropdown affordance. */+.ldr-filter-group select.form-control {+ appearance: auto;+}+.ldr-filter-group select.form-control option {background: var(--bg-tertiary);color: var(--text-primary, #e4e4e4);@@ -257,7 +263,7 @@font-size: 14px;}-.ldr-search-wrapper input {+.ldr-search-wrapper input.form-control {padding-left: 36px;width: 100%;}@@ -439,7 +445,7 @@.ldr-research-actions .btn:hover {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-color: var(--primary-color);}@@ -451,7 +457,7 @@/* Colored button variants for research actions */.ldr-research-actions .btn.btn-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);border-color: var(--success-color);}@@ -508,7 +514,7 @@.ldr-bulk-actions .ldr-btn-bulk:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);transform: translateY(-1px);box-shadow: 0 2px 4px rgba(0,0,0,0.1);@@ -576,7 +582,7 @@.modal-footer .btn:hover {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);}.modal-footer .btn.btn-secondary {@@ -594,14 +600,17 @@.modal-footer .btn-danger {background: var(--error-color);- color: white;+ color: var(--text-on-error);border-color: var(--error-color);}+/* Keep the danger ink: .modal-footer .btn:hover has the same specificity+ and would otherwise draw the accent ink on the error fill. */.modal-footer .btn-danger:hover {background: var(--error-color);border-color: var(--error-color);filter: brightness(0.85);+ color: var(--text-on-error);}/* Progress Modal */@@ -650,7 +659,7 @@display: flex;align-items: center;justify-content: center;- color: white;+ color: var(--text-on-success);font-weight: bold;position: relative;}@@ -659,7 +668,9 @@content: attr(data-percent);position: absolute;right: 10px;- color: white;+ /* The fill's own ink: --text-on-success, or --text-on-error once+ cancelled. */+ color: inherit;font-size: 14px;}@@ -711,6 +722,7 @@/* Cancelled progress state */.ldr-progress-fill.ldr-cancelled {background: var(--error-color) !important;+ color: var(--text-on-error);filter: none;}diff --git a/src/local_deep_research/web/static/css/embedding_settings.css b/src/local_deep_research/web/static/css/embedding_settings.cssindex f9f6bea197..0bb0c37bce 100644--- a/src/local_deep_research/web/static/css/embedding_settings.css+++ b/src/local_deep_research/web/static/css/embedding_settings.css@@ -328,7 +328,7 @@.ldr-badge-indexed {background: var(--success-color);- color: white;+ color: var(--text-on-success);padding: 4px 8px;border-radius: 4px;font-size: 0.85em;@@ -336,7 +336,7 @@.ldr-badge-unindexed {background: var(--btn-secondary-bg);- color: var(--text-on-accent);+ color: white;padding: 4px 8px;border-radius: 4px;font-size: 0.85em;diff --git a/src/local_deep_research/web/static/css/help-system.css b/src/local_deep_research/web/static/css/help-system.cssindex d22f58b6e8..b031fc0580 100644--- a/src/local_deep_research/web/static/css/help-system.css+++ b/src/local_deep_research/web/static/css/help-system.css@@ -274,7 +274,7 @@height: 26px;min-width: 26px;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-radius: 50%;display: flex;align-items: center;diff --git a/src/local_deep_research/web/static/css/library.css b/src/local_deep_research/web/static/css/library.cssindex 0e4f2906d1..cbb5a36533 100644--- a/src/local_deep_research/web/static/css/library.css+++ b/src/local_deep_research/web/static/css/library.css@@ -74,12 +74,12 @@.ldr-library-status-bar .badge-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-library-status-bar .badge-warning {background: var(--warning-color);- color: white;+ color: var(--text-on-warning);}.ldr-library-status-bar .ldr-status-hint {@@ -241,6 +241,12 @@box-shadow: 0 0 0 3px rgba(var(--accent-primary-rgb), 0.2);}+/* Bootstrap's form-control removes the native arrow; these filters do not+ provide a custom replacement. Restore the dropdown affordance. */+.ldr-filter-group select.form-control {+ appearance: auto;+}+.ldr-filter-group select.form-control option {background: var(--bg-secondary);color: var(--text-primary);@@ -263,7 +269,7 @@.ldr-view-toggle button.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -295,7 +301,7 @@.ldr-badge-arxiv {background: var(--error-color);- color: white;+ color: var(--text-on-error);padding: 2px 8px;border-radius: 4px;font-size: 12px;@@ -341,14 +347,14 @@.ldr-action-btn-pdf {background: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-action-btn-pdf:hover {background: var(--error-color);transform: translateY(-2px);box-shadow: 0 4px 12px rgba(var(--error-color-rgb), 0.4);- color: white;+ color: var(--text-on-error);filter: brightness(0.9);}@@ -367,10 +373,16 @@.ldr-action-btn-rag {background: var(--accent-secondary);- color: white;+ color: var(--text-on-accent);cursor: default;}+/* The badge is a link; a:hover (0,1,1) would draw the accent on itself. */+.ldr-action-btn-rag:hover,+.ldr-action-btn-rag:focus {+ color: var(--text-on-accent);+}+.ldr-action-btn-none {background: var(--text-muted);color: white;diff --git a/src/local_deep_research/web/static/css/link_analytics.css b/src/local_deep_research/web/static/css/link_analytics.cssindex a9962110ea..0ee79ad523 100644--- a/src/local_deep_research/web/static/css/link_analytics.css+++ b/src/local_deep_research/web/static/css/link_analytics.css@@ -162,7 +162,7 @@.ldr-metric-badge.ldr-frequency {background: linear-gradient(135deg, var(--accent-primary), var(--accent-secondary));- color: white;+ color: var(--text-on-accent);border: none;}@@ -191,7 +191,10 @@letter-spacing: 0.05em;}-.ldr-research-link {+/* The chip class, not .ldr-research-link: cost_analytics.css gives that+ class to a plain text link, and a theme rule keyed on the chip's fill+ (high-contrast.css) must not reach it. */+.ldr-research-chip {display: inline-block;margin: 0.25rem 0.5rem 0.25rem 0;padding: 0.25rem 0.5rem;@@ -204,9 +207,9 @@transition: all 0.2s;}-.ldr-research-link:hover {+.ldr-research-chip:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);transform: translateY(-1px);}@@ -478,7 +481,7 @@display: flex;align-items: center;justify-content: center;- color: white;+ color: var(--text-on-accent);font-weight: 500;}@@ -513,7 +516,7 @@display: inline-block;padding: 0.2rem 0.5rem;background: var(--success-color);- color: white;+ color: var(--text-on-success);border-radius: 0.25rem;font-size: 0.75rem;font-weight: 500;diff --git a/src/local_deep_research/web/static/css/metrics.css b/src/local_deep_research/web/static/css/metrics.cssindex bd4ca51808..6820fb0dee 100644--- a/src/local_deep_research/web/static/css/metrics.css+++ b/src/local_deep_research/web/static/css/metrics.css@@ -51,7 +51,7 @@align-items: center;justify-content: center;background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-radius: 0.375rem;margin-bottom: 1rem;}@@ -302,7 +302,7 @@ details[open] summary {.ldr-time-range-btn.active {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);border-color: var(--primary-color);}@@ -432,6 +432,30 @@ canvas {max-width: 100% !important;}+/* Engine health badge on the rate-limiting cards: each status fill takes+ the ink chosen for it (unknown statuses keep a neutral chip). */+.ldr-engine-health-badge {+ padding: 2px 8px;+ border-radius: 12px;+ font-size: 0.75rem;+ font-weight: 600;+ text-transform: uppercase;+ background: var(--bg-tertiary);+ color: var(--text-primary);+}+.ldr-engine-health-badge--healthy {+ background: var(--success-color);+ color: var(--text-on-success);+}+.ldr-engine-health-badge--degraded {+ background: var(--warning-color);+ color: var(--text-on-warning);+}+.ldr-engine-health-badge--poor {+ background: var(--error-color);+ color: var(--text-on-error);+}+/* Navigation link buttons */.ldr-nav-link-btn {color: white;@@ -447,12 +471,15 @@ canvas {}.ldr-nav-link-btn.ldr-nav-accent {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);+ color: var(--text-on-accent);}.ldr-nav-link-btn.ldr-nav-success {background: var(--success-color);+ color: var(--text-on-success);}.ldr-nav-link-btn.ldr-nav-warning {background: linear-gradient(135deg, var(--warning-color) 0%, var(--error-color) 100%);+ color: var(--text-on-error);}.ldr-nav-link-btn.ldr-nav-info {background: linear-gradient(135deg, var(--accent-tertiary) 0%, var(--accent-primary) 100%);diff --git a/src/local_deep_research/web/static/css/mobile-navigation.css b/src/local_deep_research/web/static/css/mobile-navigation.cssindex e56e804271..5a70d02a3d 100644--- a/src/local_deep_research/web/static/css/mobile-navigation.css+++ b/src/local_deep_research/web/static/css/mobile-navigation.css@@ -549,7 +549,7 @@[data-theme="light"] {--mobile-nav-bg: #f5f5f5;--mobile-nav-border: #ddd;- --mobile-nav-text: #4a4a4a;+ --mobile-nav-text: var(--text-secondary);--mobile-sheet-bg: #fff;--mobile-sheet-handle: #ccc;}@@ -557,9 +557,9 @@[data-theme="sepia"] {--mobile-nav-bg: #f4ecd8;--mobile-nav-border: #d4c4a8;- --mobile-nav-text: #5c5244;- --mobile-nav-active: #8b6914;- --mobile-nav-text-active: #8b6914;+ --mobile-nav-text: var(--text-secondary);+ --mobile-nav-active: var(--accent-primary);+ --mobile-nav-text-active: var(--accent-primary);--mobile-sheet-bg: #faf6ed;--mobile-sheet-handle: #c4b89a;}@@ -677,9 +677,9 @@[data-theme="solarized-light"] {--mobile-nav-bg: #eee8d5;--mobile-nav-border: #ddd6c3;- --mobile-nav-text: #657b83;- --mobile-nav-active: #268bd2;- --mobile-nav-text-active: #268bd2;+ --mobile-nav-text: var(--text-secondary);+ --mobile-nav-active: var(--accent-primary);+ --mobile-nav-text-active: var(--accent-primary);--mobile-sheet-bg: #fdf6e3;--mobile-sheet-handle: #ccc6b3;}@@ -697,9 +697,9 @@[data-theme="gruvbox-light"] {--mobile-nav-bg: #f2e5bc;--mobile-nav-border: #e2d5ac;- --mobile-nav-text: #7c6f64;- --mobile-nav-active: #b57614;- --mobile-nav-text-active: #b57614;+ --mobile-nav-text: var(--text-secondary);+ --mobile-nav-active: var(--accent-primary);+ --mobile-nav-text-active: var(--accent-primary);--mobile-sheet-bg: #fbf1c7;--mobile-sheet-handle: #d2c59c;}diff --git a/src/local_deep_research/web/static/css/news-enhanced.css b/src/local_deep_research/web/static/css/news-enhanced.cssindex 50772b6f47..b2e8433016 100644--- a/src/local_deep_research/web/static/css/news-enhanced.css+++ b/src/local_deep_research/web/static/css/news-enhanced.css@@ -87,7 +87,7 @@.ldr-news-category {background: var(--news-gradient-1);- color: white;+ color: var(--text-on-accent);padding: 0.4rem 1rem;border-radius: 20px;font-size: 0.85rem;@@ -232,7 +232,7 @@.ldr-vote-btn.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -245,7 +245,7 @@.btn-primary {background: var(--news-gradient-1);border: none;- color: white;+ color: var(--text-on-accent);padding: 0.75rem 1.5rem;border-radius: 8px;font-weight: 600;@@ -260,7 +260,7 @@.btn-primary:hover {transform: translateY(-2px);box-shadow: 0 6px 20px rgba(var(--accent-primary-rgb), 0.4);- color: white;+ color: var(--text-on-accent);text-decoration: none;}@@ -291,7 +291,7 @@.ldr-subscription-item.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -334,7 +334,7 @@.ldr-topic-pill:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);transform: scale(1.05);box-shadow: 0 4px 15px rgba(var(--accent-primary-rgb), 0.3);}diff --git a/src/local_deep_research/web/static/css/news.css b/src/local_deep_research/web/static/css/news.cssindex a71898eba0..943f55615b 100644--- a/src/local_deep_research/web/static/css/news.css+++ b/src/local_deep_research/web/static/css/news.css@@ -516,6 +516,7 @@#search-btn {background: var(--accent-primary);+ color: var(--text-on-accent);border: none;padding: 0.75rem 1.5rem;border-radius: 0 8px 8px 0;@@ -598,7 +599,7 @@.ldr-subscriptions-horizontal .ldr-subscription-item.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -632,7 +633,7 @@.ldr-filter-btn.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -665,7 +666,7 @@.ldr-priority-alert {padding: 1rem;background: var(--warning-color);- color: #000; /* Black text on warning background */+ color: var(--text-on-warning);border-radius: 6px;display: flex;align-items: center;@@ -673,6 +674,29 @@font-weight: 500;}+/* The progress link shares the alert's ink; the underline marks it as a link.+ The state rules match a theme's a:hover (0,2,1; High Contrast's green would+ sit on the yellow fill) and load after it. High Contrast's yellow focus+ outline (*:focus, !important) would vanish on the warning fill, so the+ focus outline takes the link ink instead. */+.ldr-priority-alert a {+ color: inherit;+ text-decoration: underline;+}++.ldr-priority-alert a:hover,+.ldr-priority-alert a:focus-visible,+.ldr-priority-alert a:active {+ color: inherit;+ text-decoration-thickness: 2px;+}++.ldr-priority-alert a:focus,+.ldr-priority-alert a:focus-visible {+ outline: 2px solid currentColor !important;+ outline-offset: 2px;+}+/* News Items */.ldr-news-items-card {flex: 1;@@ -1292,7 +1316,7 @@.ldr-vote-btn.ldr-voted {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -1400,17 +1424,17 @@.ldr-impact-high {background: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-impact-medium {background: var(--warning-color);- color: #000; /* Black text on warning background */+ color: var(--text-on-warning);}.ldr-impact-low {background: var(--success-color);- color: white;+ color: var(--text-on-success);}/* Subscriptions */@@ -1448,7 +1472,7 @@.ldr-subscription-item.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);}.ldr-subscription-type {@@ -1677,13 +1701,13 @@ button[onclick="refreshFeed()"]:hover i {.ldr-topic-tag:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}.ldr-topic-tag.active {background: var(--accent-primary) !important;- color: white !important;+ color: var(--text-on-accent) !important;border-color: var(--accent-primary) !important;}@@ -1753,7 +1777,7 @@ button[onclick="refreshFeed()"]:hover i {.ldr-source-link:hover {background: var(--accent-primary);- color: white !important;+ color: var(--text-on-accent) !important;border-color: var(--accent-primary);transform: translateY(-1px);}@@ -1806,7 +1830,7 @@ button[onclick="refreshFeed()"]:hover i {.ldr-news-item .btn-primary {padding: 0.5rem 1rem;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border: none;border-radius: 4px;cursor: pointer;@@ -1920,18 +1944,18 @@ button[onclick="refreshFeed()"]:hover i {.ldr-history-status.ldr-status-completed {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-history-status.ldr-status-in_progress {background: var(--warning-color);- color: #000;+ color: var(--text-on-warning);}.ldr-history-status.ldr-status-failed,.ldr-history-status.ldr-status-error {background: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-history-time {@@ -2000,7 +2024,7 @@ button[onclick="refreshFeed()"]:hover i {.ldr-template-btn:hover {background: var(--primary-color);- color: white;+ color: var(--text-on-accent);transform: translateX(5px);}@@ -2022,7 +2046,7 @@ button[onclick="refreshFeed()"]:hover i {.ldr-news-card.ldr-active-research-card .btn-outline-primary:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}diff --git a/src/local_deep_research/web/static/css/notes.css b/src/local_deep_research/web/static/css/notes.cssindex 281cdb66d7..ad07c14993 100644--- a/src/local_deep_research/web/static/css/notes.css+++ b/src/local_deep_research/web/static/css/notes.css@@ -88,7 +88,7 @@.ldr-notes-ask-btn {background: linear-gradient(135deg, var(--accent-primary, #6e4ff6) 0%, var(--accent-secondary, #8b5cf6) 100%);- color: #fff;+ color: var(--text-on-accent);border: none;border-radius: 8px;padding: 0.4rem 0.9rem;@@ -158,7 +158,7 @@/* Create Button */.ldr-create-note-btn {background: linear-gradient(135deg, var(--accent-primary, #6e4ff6) 0%, var(--accent-secondary, #8b5cf6) 100%);- color: white;+ color: var(--text-on-accent);border: none;padding: 0.75rem 1.5rem;border-radius: 10px;@@ -176,7 +176,7 @@.ldr-create-note-btn:hover {transform: translateY(-2px);box-shadow: 0 6px 20px rgba(var(--accent-primary-rgb), 0.4);- color: white;+ color: var(--text-on-accent);}/* Notes Grid */@@ -426,12 +426,12 @@.ldr-notes-search-mode .dropdown-item.active,.ldr-notes-search-mode .dropdown-item:active {background: var(--accent-primary, #6e4ff6);- color: #fff;+ color: var(--text-on-accent);}.ldr-notes-search-mode .dropdown-item.active small,.ldr-notes-search-mode .dropdown-item:active small {- color: rgba(255, 255, 255, 0.8) !important;+ color: var(--text-on-accent) !important;}/* Search notice (e.g. AI search unavailable → keyword-only) */@@ -636,7 +636,7 @@ a.ldr-ai-result-card:hover {.ldr-suggest-link-accept {margin-left: auto;background: linear-gradient(135deg, var(--accent-primary, #6e4ff6) 0%, var(--accent-secondary, #8b5cf6) 100%);- color: #fff;+ color: var(--text-on-accent);border: none;border-radius: 8px;padding: 0.2rem 0.6rem;@@ -756,9 +756,47 @@ a.ldr-ai-result-card:hover {margin-top: 0.25rem;}-/* White close button for dark modals (replaces Bootstrap btn-close-white) */+/* Keep the modal close icon visible on both light and dark surfaces. */.ldr-btn-close-white {- filter: invert(1) grayscale(100%) brightness(200%);+ /* Bootstrap's :hover rule re-reads --bs-btn-close-color (#000) and lowers+ opacity, so theme the variables rather than only the resting color. */+ --bs-btn-close-color: var(--text-primary);+ --bs-btn-close-opacity: 1;+ --bs-btn-close-hover-opacity: 1;+ --bs-btn-close-focus-opacity: 1;+ --bs-btn-close-filter: none;+ position: relative;+ background: none;+ color: var(--bs-btn-close-color);+ filter: none;+ opacity: 1;+}++.ldr-btn-close-white::before,+.ldr-btn-close-white::after {+ content: "";+ position: absolute;+ top: 50%;+ left: 50%;+ width: 1em;+ height: 2px;+ background: currentColor;+ transform: translate(-50%, -50%) rotate(45deg);+}++.ldr-btn-close-white::after {+ transform: translate(-50%, -50%) rotate(-45deg);+}++/* Forced-colors mode (Windows High Contrast) repaints background-color with+ Canvas, which would erase the bars above. Paint them in the system text+ color instead. */+@media (forced-colors: active) {+ .ldr-btn-close-white::before,+ .ldr-btn-close-white::after {+ forced-color-adjust: none;+ background: CanvasText;+ }}/* Editor hint bar */@@ -830,7 +868,8 @@ a.ldr-ai-result-card:hover {}.ldr-wiki-link-item-title .ldr-highlight {- background: rgba(var(--accent-primary-rgb), 0.3);+ /* Stacks on the 0.1 hover/active tint; 0.2 keeps text-primary at 4.5:1. */+ background: rgba(var(--accent-primary-rgb), 0.2);border-radius: 2px;padding: 0 1px;}@@ -997,7 +1036,7 @@ a.ldr-ai-result-card:hover {}.ldr-select-mode-btn.active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}diff --git a/src/local_deep_research/web/static/css/settings-mobile-fix.css b/src/local_deep_research/web/static/css/settings-mobile-fix.cssindex 0ffd7feb2d..48e3c9d75e 100644--- a/src/local_deep_research/web/static/css/settings-mobile-fix.css+++ b/src/local_deep_research/web/static/css/settings-mobile-fix.css@@ -296,7 +296,7 @@.ldr-support-note a:hover,.ldr-support-note a:active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);}/* Settings tabs touch targets */diff --git a/src/local_deep_research/web/static/css/settings.css b/src/local_deep_research/web/static/css/settings.cssindex a84d1f29de..e0e74674ea 100644--- a/src/local_deep_research/web/static/css/settings.css+++ b/src/local_deep_research/web/static/css/settings.css@@ -119,7 +119,7 @@}.ldr-settings-tab.active {- color: var(--text-primary);+ color: var(--text-on-accent);background-color: var(--accent-primary);box-shadow: 0 0 10px rgba(var(--accent-primary-rgb), 0.3);border-color: var(--accent-primary);@@ -382,13 +382,24 @@.ldr-settings-select {appearance: none;- background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='16' height='16' fill='%236b7280' viewBox='0 0 16 16'%3E%3Cpath d='M8 11l-6-6 1.5-1.5L8 8l4.5-4.5L14 5l-6 6z'/%3E%3C/svg%3E");+ background-image: linear-gradient(45deg, transparent 50%, currentColor 50%),+ linear-gradient(135deg, currentColor 50%, transparent 50%);background-repeat: no-repeat;- background-position: right 0.75rem center;- background-size: 16px 12px;+ background-position: right 1rem center, right 0.65rem center;+ background-size: 0.35rem 0.35rem;padding-right: 2.5rem;}+/* Forced-colors mode (Windows High Contrast) drops non-url() background+ images, which would leave the gradient chevron above invisible on an+ appearance:none select. Hand the arrow back to the platform there. */+@media (forced-colors: active) {+ .ldr-settings-select {+ appearance: auto;+ background-image: none;+ }+}+.ldr-settings-checkbox-container {margin: 0.5rem 0;}@@ -425,7 +436,7 @@margin-left: 1rem;padding: 0.25rem 0.5rem;background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-radius: 0.25rem;text-align: center;font-size: 0.85rem;@@ -811,7 +822,7 @@.btn-primary {background-color: var(--accent-primary);- color: var(--text-primary);+ color: var(--text-on-accent);box-shadow: 0 0 10px rgba(var(--accent-primary-rgb), 0.3);}@@ -1043,7 +1054,7 @@.ldr-checkbox-label input[type="checkbox"]:checked::after {content: '✓';- color: white;+ color: var(--text-on-accent);font-size: 12px;position: absolute;top: 50%;@@ -1130,7 +1141,7 @@#reset-to-defaults-button {margin-left: 10px;background-color: var(--error-color);- color: var(--bg-primary);+ color: var(--text-on-error);border: none;}@@ -1321,7 +1332,7 @@.ldr-data-location-details .ldr-badge-info {background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);padding: 0.25rem 0.75rem;border-radius: 1rem;font-size: 0.75rem;diff --git a/src/local_deep_research/web/static/css/styles.css b/src/local_deep_research/web/static/css/styles.cssindex dfb7c54fe0..696e42cbe1 100644--- a/src/local_deep_research/web/static/css/styles.css+++ b/src/local_deep_research/web/static/css/styles.css@@ -69,7 +69,18 @@--card-bg: var(--bg-secondary);/* Aliased to --text-muted for backward compat; theme authors can override */--btn-secondary-bg: var(--text-muted);+ /* Ink on filled accent-primary/-secondary controls. Each theme sets its+ own next to its accent (dark ink on the light dark-theme accents). */--text-on-accent: #ffffff;+ --text-on-warning: #1a1a00;+ /* Ink on a filled --error-color. Dark ink reads on the light error reds+ of the dark palettes; light palettes (and kanagawa's deep red) set+ white. */+ --text-on-error: #000000;+ /* Ink on a filled --success-color: dark on the light greens of the dark+ palettes; light palettes darken their green and set white. */+ --text-on-success: #000000;+ --control-border: var(--border-color);}/* Reset and Base Styles */@@ -106,7 +117,7 @@ a:hover {z-index: 10000;padding: 12px 24px;background-color: var(--accent-primary);- color: var(--text-primary);+ color: var(--text-on-accent);font-weight: 600;border-radius: 0 0 8px 8px;text-decoration: none;@@ -115,10 +126,16 @@ a:hover {.ldr-skip-link:focus {top: 0;+ color: var(--text-on-accent);outline: 2px solid var(--accent-secondary);outline-offset: 2px;}+/* a:hover (0,1,1) outranks .ldr-skip-link; keep the accent ink. */+.ldr-skip-link:hover {+ color: var(--text-on-accent);+}+/* Badge Styles */.ldr-badge {display: inline-block;@@ -132,17 +149,17 @@ a:hover {.ldr-badge-success {background: var(--success-color);- color: white;+ color: var(--text-on-success);}.ldr-badge-warning {background: var(--warning-color);- color: #1a1a00;+ color: var(--text-on-warning);}.ldr-badge-danger {background: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-badge-info {@@ -155,6 +172,48 @@ a:hover {color: white;}+/* Inline code follows the reading surface instead of Bootstrap's pink. */+:not(pre) > code {+ color: var(--text-primary);+}++/* Code inside a link keeps the link colour, as Bootstrap intends. */+a > code {+ color: inherit;+}++/* Bootstrap outline controls use the selected theme in every state. */+.btn-outline-primary {+ --bs-btn-color: var(--accent-primary);+ --bs-btn-border-color: var(--accent-primary);+ --bs-btn-hover-color: var(--text-on-accent);+ --bs-btn-hover-bg: var(--accent-primary);+ --bs-btn-hover-border-color: var(--accent-primary);+ --bs-btn-active-color: var(--text-on-accent);+ --bs-btn-active-bg: var(--accent-primary);+ --bs-btn-active-border-color: var(--accent-primary);+}++.btn-outline-secondary {+ --bs-btn-color: var(--text-secondary);+ --bs-btn-border-color: var(--text-secondary);+ --bs-btn-hover-color: var(--text-primary);+ --bs-btn-hover-bg: var(--bg-tertiary);+ --bs-btn-hover-border-color: var(--text-secondary);+ --bs-btn-active-color: var(--text-primary);+ --bs-btn-active-bg: var(--bg-tertiary);+ --bs-btn-active-border-color: var(--text-secondary);+}++/* Controls need stronger edges than decorative card/divider borders. Scope the+ existing border token so component and inline styles share the same contrast,+ while their focus, error and selected-state colors still take precedence. */+:where(input, textarea, select, button, [role="combobox"],+ .ldr-theme-selector, .ldr-notes-ask, .ldr-chat-input-wrapper,+ .ldr-markdown-editor-container, .ldr-news-search-box) {+ --border-color: var(--control-border);+}+/* Screen reader only - visually hidden but accessible */.sr-only {position: absolute !important;@@ -532,7 +591,7 @@ a:hover {.ldr-logout-btn:hover {background-color: var(--error-color);- color: white;+ color: var(--text-on-error);border-color: var(--error-color);text-decoration: none;}@@ -698,13 +757,25 @@ textarea:focus, input[type="text"]:focus {.btn-primary {background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);+ /* Bootstrap's own state rules (.btn:focus-visible, .btn:active, .btn.active,+ .btn.disabled; 0,2,0 and up) outrank the rule above and draw these+ variables, which bootstrap.css sets to its blue and white: keep the+ accent fill and the accent ink together in every state. */+ --bs-btn-color: var(--text-on-accent);+ --bs-btn-bg: var(--accent-primary);+ --bs-btn-hover-color: var(--text-on-accent);+ --bs-btn-hover-bg: var(--accent-primary);+ --bs-btn-active-color: var(--text-on-accent);+ --bs-btn-active-bg: var(--accent-primary);+ --bs-btn-disabled-color: var(--text-on-accent);+ --bs-btn-disabled-bg: var(--accent-primary);}.btn-primary:hover {background-color: var(--accent-secondary);box-shadow: var(--glow-effect);- color: white;+ color: var(--text-on-accent);}.ldr-btn-outline {@@ -782,14 +853,17 @@ textarea:focus, input[type="text"]:focus {.ldr-nav-link-btn.ldr-nav-accent {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);+ color: var(--text-on-accent);}.ldr-nav-link-btn.ldr-nav-success {background: var(--success-color);+ color: var(--text-on-success);}.ldr-nav-link-btn.ldr-nav-warning {background: linear-gradient(135deg, var(--warning-color) 0%, var(--error-color) 100%);+ color: var(--text-on-error);}.ldr-nav-link-btn.ldr-nav-info {@@ -828,7 +902,7 @@ textarea:focus, input[type="text"]:focus {width: 40px;height: 40px;background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-radius: 50%;display: flex;align-items: center;@@ -857,7 +931,7 @@ textarea:focus, input[type="text"]:focus {font-weight: 600;text-transform: uppercase;background-color: var(--warning-color);- color: #1a1a00;+ color: var(--text-on-warning);padding: 0.15rem 0.4rem;border-radius: 4px;margin-left: 0.5rem;@@ -2059,7 +2133,7 @@ textarea:focus, input[type="text"]:focus {.ldr-log-indicator {margin-left: auto;background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-radius: 12px;padding: 0.1rem 0.5rem;font-size: 0.75rem;@@ -2072,9 +2146,9 @@ textarea:focus, input[type="text"]:focus {error badge), so failures are visible without expanding the panel.Colour is NOT the only channel. --error-color and --accent-primary are- similar-luminance mid-tones both carrying white text, so the swap alone- is invisible to a red/purple-confusing viewer (and to anyone who never- saw the un-alerted badge to compare against). The state therefore also+ similar-luminance mid-tones, so the swap alone is invisible to a+ red/purple-confusing viewer (and to anyone who never saw the un-alerted+ badge to compare against). The state therefore alsochanges TEXT and WEIGHT: a trailing "!" glyph in bold. (No colouredring — a ring in --error-color would be invisible against the badge itsits on.) The glyph is a ::after pseudo-element, so it never enters@@ -2084,6 +2158,9 @@ textarea:focus, input[type="text"]:focus {the state is not hover-only for assistive tech. */.ldr-log-indicator--has-error {background-color: var(--error-color, #e74c3c);+ /* The base ink is --text-on-accent, which need not read on the error+ fill (black on kanagawa's red is 4.13:1). */+ color: var(--text-on-error);font-weight: 700;}@@ -2190,22 +2267,22 @@ textarea:focus, input[type="text"]:focus {.ldr-console-log-entry.ldr-log-milestone .ldr-log-badge {background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);}.ldr-console-log-entry.ldr-log-error .ldr-log-badge {background-color: var(--error-color);- color: white;+ color: var(--text-on-error);}.ldr-console-log-entry.ldr-log-warning .ldr-log-badge {background-color: var(--warning-color);- color: #1a1a00;+ color: var(--text-on-warning);}.ldr-console-log-entry.ldr-log-debug .ldr-log-badge {background-color: var(--btn-secondary-bg);- color: var(--text-on-accent);+ color: white;}.ldr-console-log-entry.ldr-log-info .ldr-log-badge {@@ -2277,7 +2354,7 @@ textarea:focus, input[type="text"]:focus {.ldr-small-btn.ldr-selected {background-color: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -2544,13 +2621,24 @@ textarea:focus, input[type="text"]:focus {select.ldr-form-control {appearance: none;- background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='%238a8aa0' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e");+ background-image: linear-gradient(45deg, transparent 50%, currentColor 50%),+ linear-gradient(135deg, currentColor 50%, transparent 50%);background-repeat: no-repeat;- background-position: right 0.75rem center;- background-size: 1rem;+ background-position: right 1rem center, right 0.65rem center;+ background-size: 0.35rem 0.35rem;padding-right: 2.5rem;}+/* Forced-colors mode (Windows High Contrast) drops non-url() background+ images, which would leave the gradient chevron above invisible on an+ appearance:none select. Hand the arrow back to the platform there. */+@media (forced-colors: active) {+ select.ldr-form-control {+ appearance: auto;+ background-image: none;+ }+}+input[type="number"].ldr-form-control {appearance: textfield;-moz-appearance: textfield;@@ -2645,12 +2733,16 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {background-color: var(--bg-tertiary);}+/* Same tint as custom_dropdown.css, so load order cannot change it; the+ search-match highlight stacks on it (test_light_theme_contrast.py). */.ldr-custom-dropdown-item.active {- background-color: rgba(var(--accent-primary-rgb), 0.2);+ background-color: rgba(var(--accent-primary-rgb), 0.1);}+/* The match is marked by the tint in custom_dropdown.css; accent-primary+ ink on that tint of itself fell below 4.5:1 in every light palette. */.ldr-custom-dropdown-item .ldr-highlight {- color: var(--accent-primary);+ color: var(--text-primary);font-weight: 500;}@@ -2831,7 +2923,7 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {gap: 0.25rem;padding: 0.125rem 0.5rem;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-radius: 12px;font-size: 0.75rem;font-weight: 500;@@ -2934,14 +3026,14 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {.ldr-subscribe-btn:hover {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);transform: translateY(-1px);}.ldr-subscribe-btn.ldr-subscribed {background: var(--success-color);border-color: var(--success-color);- color: white;+ color: var(--text-on-success);cursor: default;}@@ -3003,8 +3095,7 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {.ldr-sidebar-links a {color: var(--text-muted);font-size: 1rem;- opacity: 0.6;- transition: opacity 0.2s, color 0.2s;+ transition: color 0.2s;}.ldr-sidebar-links a:hover {@@ -3018,8 +3109,7 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {color: inherit;text-decoration: none;border-bottom: 1px dotted currentColor;- opacity: 0.75;- transition: opacity 0.2s, color 0.2s;+ transition: color 0.2s;}.ldr-sidebar-footer a.ldr-sidebar-version-link:hover,@@ -3077,16 +3167,22 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {font-size: 14px;}+/* The alert fill is a 10% tint of the page background, so white would+ vanish in the light themes: hover and focus keep the link ink (the global+ a:hover would otherwise recolour it) and mark the state with a thicker+ underline and an outline in that ink, which also rings the accent-filled+ buttons some alerts hold (their own ink would vanish on the tint). */.ldr-alert a:hover,.ldr-alert a:focus-visible,.ldr-alert .ldr-alert-action:hover,.ldr-alert .ldr-alert-action:focus-visible {- color: #ffffff;+ color: var(--text-primary);+ text-decoration-thickness: 2px;}.ldr-alert a:focus-visible,.ldr-alert .ldr-alert-action:focus-visible {- outline: 2px solid #ffffff;+ outline: 2px solid var(--text-primary);outline-offset: 2px;border-radius: 2px;}@@ -3111,7 +3207,7 @@ input[type="number"].ldr-form-control::-webkit-inner-spin-button {padding: 1px 5px;margin-left: 6px;background: var(--warning-color);- color: #000;+ color: var(--text-on-warning);border-radius: 3px;font-weight: 600;vertical-align: middle;diff --git a/src/local_deep_research/web/static/css/subscriptions.css b/src/local_deep_research/web/static/css/subscriptions.cssindex 5bb2be4af4..d0d96440d8 100644--- a/src/local_deep_research/web/static/css/subscriptions.css+++ b/src/local_deep_research/web/static/css/subscriptions.css@@ -189,7 +189,7 @@.ldr-folder-item.active .ldr-folder-count {background: var(--accent-primary);- color: var(--bg-primary);+ color: var(--text-on-accent);}/* Main Content Area */@@ -465,7 +465,7 @@.ldr-topic-badge {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);padding: 2px 8px;border-radius: 12px;font-size: 0.75rem;diff --git a/src/local_deep_research/web/static/js/components/context-overflow.js b/src/local_deep_research/web/static/js/components/context-overflow.jsindex e3b4026451..449025ab28 100644--- a/src/local_deep_research/web/static/js/components/context-overflow.js+++ b/src/local_deep_research/web/static/js/components/context-overflow.js@@ -237,7 +237,7 @@<div class="ldr-card-content"><div class="ldr-overflow-grid"><div class="ldr-overflow-card">- <div class="ldr-metric-icon" style="background: var(--warning-color);">+ <div class="ldr-metric-icon" style="background: var(--warning-color); color: var(--text-on-warning);"><i aria-hidden="true" class="fas fa-percentage"></i></div><div class="ldr-metric-label">Truncation Rate</div>@@ -247,7 +247,7 @@</div></div><div class="ldr-overflow-card">- <div class="ldr-metric-icon" style="background: var(--error-color);">+ <div class="ldr-metric-icon" style="background: var(--error-color); color: var(--text-on-error);"><i aria-hidden="true" class="fas fa-cut"></i></div><div class="ldr-metric-label">Avg Tokens Lost</div>diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.jsindex a9710651f8..f78fdfcb0d 100644--- a/src/local_deep_research/web/static/js/components/details.js+++ b/src/local_deep_research/web/static/js/components/details.js@@ -114,7 +114,7 @@<div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid var(--border-color);"><span style="font-weight: 500;">${escapeHtml(domain.domain)}</span><div style="display: flex; gap: 1rem; align-items: center;">- <span style="background: var(--primary-color); color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.875rem;">+ <span style="background: var(--primary-color); color: var(--text-on-accent); padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.875rem;">${escapeHtml(domain.count)} links</span><span style="color: var(--text-secondary); font-size: 0.875rem;">diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.jsindex 4738fcbc15..1b5af55074 100644--- a/src/local_deep_research/web/static/js/components/settings.js+++ b/src/local_deep_research/web/static/js/components/settings.js@@ -2381,7 +2381,6 @@.ldr-env-info {color: var(--text-secondary);font-size: 0.85rem;- opacity: 0.8;}.ldr-env-info code {@@ -2577,7 +2576,6 @@margin-top: 0.75rem;color: var(--text-secondary);font-size: 0.85rem;- opacity: 0.8;}`;document.head.appendChild(style);diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.jsindex cd179fab5c..5b175fe551 100644--- a/src/local_deep_research/web/static/js/followup.js+++ b/src/local_deep_research/web/static/js/followup.js@@ -199,8 +199,41 @@ class FollowUpResearch {#followUpModal .modal-footer {border-top: 1px solid var(--border-color);}+ /* Draw the close X in the theme's text color: Bootstrap's+ icon is black, and inverting it hides it on light+ themes. Theme the variables so :hover keeps it. */#followUpModal .btn-close {- filter: invert(1);+ --bs-btn-close-color: var(--text-primary);+ --bs-btn-close-opacity: 1;+ --bs-btn-close-hover-opacity: 1;+ --bs-btn-close-focus-opacity: 1;+ --bs-btn-close-filter: none;+ position: relative;+ background: none;+ color: var(--bs-btn-close-color);+ filter: none;+ opacity: 1;+ }+ #followUpModal .btn-close::before,+ #followUpModal .btn-close::after {+ content: "";+ position: absolute;+ top: 50%;+ left: 50%;+ width: 1em;+ height: 2px;+ background: currentColor;+ transform: translate(-50%, -50%) rotate(45deg);+ }+ #followUpModal .btn-close::after {+ transform: translate(-50%, -50%) rotate(-45deg);+ }+ @media (forced-colors: active) {+ #followUpModal .btn-close::before,+ #followUpModal .btn-close::after {+ forced-color-adjust: none;+ background: CanvasText;+ }}#followUpModal .ldr-form-control,#followUpModal .form-select {diff --git a/src/local_deep_research/web/static/js/pages/link_analytics_render.js b/src/local_deep_research/web/static/js/pages/link_analytics_render.jsindex 223b49cd5b..f6b0f9c186 100644--- a/src/local_deep_research/web/static/js/pages/link_analytics_render.js+++ b/src/local_deep_research/web/static/js/pages/link_analytics_render.js@@ -73,7 +73,7 @@<div class="ldr-research-links"><div class="ldr-research-links-title">Recent Researches (${Number(researchDiversity) || 0} total)</div>${domain.recent_researches.map(r => `- <a href="/results/${encodeURIComponent(r.id)}" class="ldr-research-link" title="${escapeHtml(r.query)}">+ <a href="/results/${encodeURIComponent(r.id)}" class="ldr-research-link ldr-research-chip" title="${escapeHtml(r.query)}">${escapeHtml(r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query)}</a>`).join('')}diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 4aa8d4fd1f..9acf1f7fd1 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -1746,7 +1746,7 @@ async function checkPriorityStatus() {// bearer:disable javascript_lang_dangerous_insert_htmlmessage.innerHTML = `<strong>Research in progress:</strong> "${escapeHtml(research.query.substring(0, 50))}..."- <a href="/progress/${escapeHtml(research.id)}" class="ms-2 text-white">View Progress →</a>+ <a href="/progress/${escapeHtml(research.id)}" class="ms-2">View Progress →</a>`;} else {statusDiv.style.display = 'none';diff --git a/src/local_deep_research/web/templates/auth/login.html b/src/local_deep_research/web/templates/auth/login.htmlindex 1079d89239..d3101b2aad 100644--- a/src/local_deep_research/web/templates/auth/login.html+++ b/src/local_deep_research/web/templates/auth/login.html@@ -250,7 +250,7 @@gap: 0.5rem;padding: 0.875rem 2rem;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border: none;border-radius: 8px;font-size: 1rem;diff --git a/src/local_deep_research/web/templates/auth/register.html b/src/local_deep_research/web/templates/auth/register.htmlindex 62c7e59476..9b0d4e01d4 100644--- a/src/local_deep_research/web/templates/auth/register.html+++ b/src/local_deep_research/web/templates/auth/register.html@@ -294,7 +294,7 @@gap: 0.75rem;padding: 1.25rem 2.5rem;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border: none;border-radius: 10px;font-size: 1.15rem;diff --git a/src/local_deep_research/web/templates/components/delete_confirmation_modal.html b/src/local_deep_research/web/templates/components/delete_confirmation_modal.htmlindex ee6f921448..e593d1b6e9 100644--- a/src/local_deep_research/web/templates/components/delete_confirmation_modal.html+++ b/src/local_deep_research/web/templates/components/delete_confirmation_modal.html@@ -40,6 +40,8 @@/* Delete confirmation modal specific styles */#deleteConfirmModal .modal-header.bg-danger {background: var(--error-color) !important;+ /* Outranks Bootstrap's .text-white utility. */+ color: var(--text-on-error) !important;}#deleteConfirmModal .ldr-btn-close-white {diff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.htmlindex 95be2615e5..f02cfa220f 100644--- a/src/local_deep_research/web/templates/pages/benchmark_results.html+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html@@ -819,12 +819,13 @@ function showAlert(message, type) {box-shadow: 0 4px 12px rgba(0,0,0,0.3);`;- // Set background color based on type+ // Set background color based on type: shades dark enough for the white+ // label (5.0:1 or more), whatever the theme.const colors = {- success: '#4caf50',- error: '#f44336',- warning: '#ff9800',- info: '#2196f3'+ success: '#2e7d32',+ error: '#c62828',+ warning: '#b45309',+ info: '#1565c0'};alertDiv.style.backgroundColor = colors[type] || colors.info;diff --git a/src/local_deep_research/web/templates/pages/collections.html b/src/local_deep_research/web/templates/pages/collections.htmlindex 061952e5ac..6f779c08cf 100644--- a/src/local_deep_research/web/templates/pages/collections.html+++ b/src/local_deep_research/web/templates/pages/collections.html@@ -29,31 +29,30 @@<div class="ldr-rag-section"><div class="ldr-section-header"><h2><i aria-hidden="true" class="fas fa-folder"></i> My Collections</h2>- <div style="display: flex; align-items: center; gap: 20px;">+ <a href="/library/collections/create" id="create-collection-btn" class="ldr-btn-collections ldr-btn-collections-primary">+ <i aria-hidden="true" class="fas fa-plus"></i> Create Collection+ </a>+ <div class="ldr-collection-settings"><!-- Auto-Index Toggle -->- <label class="ldr-checkbox-label" style="display: flex; align-items: center; cursor: pointer; gap: 8px; font-size: 14px;">+ <label class="ldr-checkbox-label"><input type="checkbox"id="auto-index-toggle"- class="ldr-settings-checkbox"- style="width: 16px; height: 16px;">+ class="ldr-settings-checkbox"><span><i aria-hidden="true" class="fas fa-magic"></i> {{ tooltip("Auto-index new documents", "When enabled, documents uploaded or downloaded to any collection are automatically indexed for semantic search.") }}</span></label><!-- Background-Sweep Toggle (scheduled reconciler, #4627).Hidden until the backend setting is registered (seeloadBackgroundSweepSetting): the wrapper starts hidden andis only revealed once the GET confirms the setting exists. -->- <label id="background-sweep-toggle-row" class="ldr-checkbox-label" style="display: none; align-items: center; cursor: pointer; gap: 8px; font-size: 14px;">+ <label id="background-sweep-toggle-row" class="ldr-checkbox-label" style="display: none;"><input type="checkbox"id="background-sweep-toggle"class="ldr-settings-checkbox"- aria-describedby="background-sweep-disabled-note"- style="width: 16px; height: 16px;">- <span><i aria-hidden="true" class="fas fa-clock-rotate-left"></i> {{ tooltip("Index documents in the background (scheduled)", "When enabled, a scheduled background job periodically scans your collections and indexes any documents that weren't indexed immediately (e.g. when the immediate auto-index queue was full). Requires the document scheduler to be enabled. Off by default.") }}</span>- <span id="background-sweep-disabled-note" class="ldr-text-muted" hidden>Enable the document scheduler first.</span>+ aria-describedby="background-sweep-disabled-note">+ <span><i aria-hidden="true" class="fas fa-clock-rotate-left"></i> {{ tooltip("Index documents in the background (scheduled)", "When enabled, a scheduled background job periodically scans your collections and indexes any documents that weren't indexed immediately (e.g. when the immediate auto-index queue was full). Requires the document scheduler to be enabled. Off by default.") }}+ <span id="background-sweep-disabled-note" class="ldr-text-muted" hidden>Enable the document scheduler first.</span>+ </span></label>- <a href="/library/collections/create" id="create-collection-btn" class="ldr-btn-collections ldr-btn-collections-primary">- <i aria-hidden="true" class="fas fa-plus"></i> Create Collection- </a></div></div>diff --git a/src/local_deep_research/web/templates/pages/context_overflow.html b/src/local_deep_research/web/templates/pages/context_overflow.htmlindex f86befc73c..b165280159 100644--- a/src/local_deep_research/web/templates/pages/context_overflow.html+++ b/src/local_deep_research/web/templates/pages/context_overflow.html@@ -14,7 +14,7 @@<div class="ldr-page-header" style="display: flex; align-items: center; justify-content: space-between;"><div style="display: flex; align-items: center; gap: 1rem;"><h1>Token Usage & Context Analytics</h1>- <a href="/metrics" style="background: var(--primary-color); color: white; padding: 8px 16px; border-radius: 6px; text-decoration: none; font-size: 0.875rem;">+ <a href="/metrics" style="background: var(--primary-color); color: var(--text-on-accent); padding: 8px 16px; border-radius: 6px; text-decoration: none; font-size: 0.875rem;">← Back to Metrics</a></div>diff --git a/src/local_deep_research/web/templates/pages/error.html b/src/local_deep_research/web/templates/pages/error.htmlindex 4ba577e1ed..f300116318 100644--- a/src/local_deep_research/web/templates/pages/error.html+++ b/src/local_deep_research/web/templates/pages/error.html@@ -80,7 +80,14 @@gap: 0.5rem;padding: 0.875rem 2rem;background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);+ /* Bootstrap's pressed rule (.btn:first-child:active, 0,3,0)+ outranks the ink above and draws these variables, which a+ plain .btn leaves undefined. */+ --bs-btn-hover-color: var(--text-on-accent);+ --bs-btn-hover-bg: var(--accent-secondary);+ --bs-btn-active-color: var(--text-on-accent);+ --bs-btn-active-bg: var(--accent-secondary);border: none;border-radius: 8px;font-size: 1rem;diff --git a/src/local_deep_research/web/templates/pages/journal_quality.html b/src/local_deep_research/web/templates/pages/journal_quality.htmlindex e731eb2061..9dbe6fbe7d 100644--- a/src/local_deep_research/web/templates/pages/journal_quality.html+++ b/src/local_deep_research/web/templates/pages/journal_quality.html@@ -23,18 +23,18 @@/* Quality badges */.ldr-quality-badge { display: inline-flex; align-items: center; justify-content: center; min-width: 2rem; padding: 0.2rem 0.5rem; border-radius: 0.375rem; font-size: 0.8125rem; font-weight: 600; color: white; }- .ldr-quality-dangerous { background: var(--error-color); }- .ldr-quality-low { background: var(--warning-color); color: #1a1a2e; }+ .ldr-quality-dangerous { background: var(--error-color); color: var(--text-on-error); }+ .ldr-quality-low { background: var(--warning-color); color: var(--text-on-warning); }.ldr-quality-moderate { background: var(--accent-tertiary, #40bfff); }- .ldr-quality-strong { background: var(--success-color); }- .ldr-quality-elite { background: var(--accent-primary); }+ .ldr-quality-strong { background: var(--success-color); color: var(--text-on-success); }+ .ldr-quality-elite { background: var(--accent-primary); color: var(--text-on-accent); }.ldr-quality-unknown { background: var(--text-muted, #8a8aa0); }/* Quartile chips (Q1=green, Q2=blue, Q3=yellow, Q4=orange) */.ldr-quartile-chip { display: inline-flex; align-items: center; justify-content: center; min-width: 2rem; padding: 0.15rem 0.45rem; border-radius: 0.375rem; font-size: 0.75rem; font-weight: 600; }- .ldr-quartile-q1 { background: var(--success-color); color: white; }- .ldr-quartile-q2 { background: var(--accent-primary); color: white; }- .ldr-quartile-q3 { background: var(--warning-color); color: #1a1a2e; }+ .ldr-quartile-q1 { background: var(--success-color); color: var(--text-on-success); }+ .ldr-quartile-q2 { background: var(--accent-primary); color: var(--text-on-accent); }+ .ldr-quartile-q3 { background: var(--warning-color); color: var(--text-on-warning); }.ldr-quartile-q4 { background: rgba(250,140,80,0.85); color: #1a1a2e; }.ldr-quartile-unknown { color: var(--text-muted, #8a8aa0); font-weight: 400; }@@ -72,8 +72,8 @@/* Pagination */.ldr-pagination { display: flex; justify-content: center; gap: 0.5rem; margin-top: 1rem; align-items: center; }.ldr-pagination-btn { padding: 0.4rem 0.75rem; border: 1px solid var(--border-color); border-radius: 0.375rem; background: var(--bg-tertiary); color: var(--text-primary); cursor: pointer; font-size: 0.8rem; }- .ldr-pagination-btn:hover { background: var(--accent-primary); color: white; }- .ldr-pagination-btn.ldr-active { background: var(--accent-primary); color: white; }+ .ldr-pagination-btn:hover { background: var(--accent-primary); color: var(--text-on-accent); }+ .ldr-pagination-btn.ldr-active { background: var(--accent-primary); color: var(--text-on-accent); }.ldr-pagination-btn:disabled { opacity: 0.4; cursor: default; }.ldr-table-info { text-align: center; font-size: 0.8rem; color: var(--text-secondary); margin-top: 0.5rem; }@@ -200,7 +200,7 @@<div id="ldr-data-banner" style="display: none; margin-bottom: 1rem; padding: 1rem 1.5rem; border-radius: 0.75rem; border: 1px solid var(--border-color); background: var(--bg-secondary);"><div style="display: flex; align-items: center; justify-content: space-between; gap: 1rem;"><div id="ldr-data-banner-text" style="color: var(--text-secondary); font-size: 0.9rem;"></div>- <button id="ldr-data-download-btn" onclick="downloadJournalData()" style="padding: 0.5rem 1rem; border-radius: 0.375rem; border: 1px solid var(--accent-primary); background: var(--accent-primary); color: white; cursor: pointer; font-size: 0.85rem; white-space: nowrap;"></button>+ <button id="ldr-data-download-btn" onclick="downloadJournalData()" style="padding: 0.5rem 1rem; border-radius: 0.375rem; border: 1px solid var(--accent-primary); background: var(--accent-primary); color: var(--text-on-accent); cursor: pointer; font-size: 0.85rem; white-space: nowrap;"></button></div><div id="ldr-data-progress" style="display: none; margin-top: 0.75rem;"><div id="ldr-data-progress-intro" style="font-size: 0.8rem; color: var(--text-secondary); margin-bottom: 0.5rem;">Downloading...</div>@@ -217,7 +217,7 @@Journal quality scores are automatically collected as you run research.Start a research session with academic sources (ArXiv, OpenAlex, Semantic Scholar, NASA ADS) enabled.</p>- <a href="/" style="display: inline-block; background: var(--accent-primary); color: white; padding: 0.75rem 1.5rem; border-radius: 0.375rem; text-decoration: none;">+ <a href="/" style="display: inline-block; background: var(--accent-primary); color: var(--text-on-accent); padding: 0.75rem 1.5rem; border-radius: 0.375rem; text-decoration: none;"><i class="fas fa-search"></i> Start Your First Research</a></div>@@ -377,7 +377,7 @@<p style="color:var(--text-secondary); max-width:450px; margin:0 auto 1.5rem;">Journal quality data appears here as you run research with academic search engines (ArXiv, OpenAlex, Semantic Scholar, NASA ADS).</p>- <a href="/" style="display:inline-block; background:var(--accent-primary); color:white; padding:0.6rem 1.25rem; border-radius:0.375rem; text-decoration:none; font-size:0.9rem;">Start a Research</a>+ <a href="/" style="display:inline-block; background:var(--accent-primary); color:var(--text-on-accent); padding:0.6rem 1.25rem; border-radius:0.375rem; text-decoration:none; font-size:0.9rem;">Start a Research</a></div><div id="ldr-yr-content" style="display:none;"><div class="ldr-your-research-stats">@@ -707,8 +707,10 @@ function renderSourcesBanner(sources) {if (!grid || !Array.isArray(sources)) return;grid.innerHTML = sources.map(s => {const ok = !!s.present;- const pillBg = ok ? 'rgba(52,199,89,0.15)' : 'rgba(255,99,71,0.15)';- const pillColor = ok ? '#34c759' : '#ff6347';+ // A filled pill with the ink chosen for its fill: the status colours+ // themselves are too faint as text on the card in many dark themes.+ const pillBg = ok ? 'var(--success-color)' : 'var(--error-color)';+ const pillColor = ok ? 'var(--text-on-success)' : 'var(--text-on-error)';const pillIcon = ok ? '✓' : '✗';const pillLabel = ok ? 'Downloaded' : 'Not downloaded';const datasetLink = s.dataset_urldiff --git a/src/local_deep_research/web/templates/pages/link_analytics.html b/src/local_deep_research/web/templates/pages/link_analytics.htmlindex a5a7979b65..6c462bdd87 100644--- a/src/local_deep_research/web/templates/pages/link_analytics.html+++ b/src/local_deep_research/web/templates/pages/link_analytics.html@@ -31,7 +31,7 @@</select></div><div>- <button id="classify-domains-btn" class="btn" style="background: var(--accent-primary); color: white; padding: 0.5rem 1rem; border-radius: 0.375rem; border: none; cursor: pointer; font-size: 0.875rem;">+ <button id="classify-domains-btn" class="btn" style="background: var(--accent-primary); color: var(--text-on-accent); padding: 0.5rem 1rem; border-radius: 0.375rem; border: none; cursor: pointer; font-size: 0.875rem;"><i aria-hidden="true" class="fas fa-brain"></i> Classify Domains with AI</button><span id="classification-status" style="margin-left: 1rem; font-size: 0.875rem; color: var(--text-secondary);"></span>@@ -155,7 +155,7 @@</label></div>- <button id="start-classification" class="btn" style="width: 100%; background: var(--accent-primary); color: white; padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem;">+ <button id="start-classification" class="btn" style="width: 100%; background: var(--accent-primary); color: var(--text-on-accent); padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem;"><i aria-hidden="true" class="fas fa-play"></i> Start Classification</button></div>@@ -173,7 +173,7 @@<!-- Log entries will be added here --></div>- <button id="stop-classification" class="btn" style="width: 100%; background: var(--error-color); color: white; padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem; margin-top: 1rem;">+ <button id="stop-classification" class="btn" style="width: 100%; background: var(--error-color); color: var(--text-on-error); padding: 0.75rem; border-radius: 0.5rem; border: none; cursor: pointer; font-size: 1rem; margin-top: 1rem;"><i aria-hidden="true" class="fas fa-stop"></i> Stop Classification</button></div>@@ -184,7 +184,7 @@<p style="color: var(--text-secondary); margin: 1rem 0;">Successfully classified <span id="final-classified">0</span> domains.</p>- <button id="close-complete" class="btn" style="background: var(--accent-primary); color: white; padding: 0.75rem 1.5rem; border-radius: 0.5rem; border: none; cursor: pointer;">+ <button id="close-complete" class="btn" style="background: var(--accent-primary); color: var(--text-on-accent); padding: 0.75rem 1.5rem; border-radius: 0.5rem; border: none; cursor: pointer;"><i aria-hidden="true" class="fas fa-check"></i> Done</button></div>diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.htmlindex 54455cc459..b6789f0a61 100644--- a/src/local_deep_research/web/templates/pages/metrics.html+++ b/src/local_deep_research/web/templates/pages/metrics.html@@ -157,7 +157,7 @@</div><div class="ldr-metric-card"><div class="ldr-metric-icon">- <i class="fas fa-ldr-star"></i>+ <i class="fas fa-star" aria-hidden="true"></i></div><div class="ldr-metric-label ldr-tooltip" data-tooltip="Average user satisfaction rating (1-5 stars) for research sessions. All rating data is stored locally on your device only and never shared.">User Satisfaction@@ -294,7 +294,7 @@<!-- User Satisfaction --><div><h4 class="ldr-tooltip" data-tooltip="Your personal research satisfaction ratings. All data stays private on your local device.">- <i class="fas fa-ldr-star"></i> User Satisfaction+ <i class="fas fa-star" aria-hidden="true"></i> User Satisfaction<i class="fas fa-info-circle ldr-info-icon"></i></h4><div id="rating-breakdown">@@ -1487,15 +1487,7 @@statusCard.innerHTML = `<div class="ldr-metric-header" style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 1rem;"><h4 style="margin: 0; color: var(--text-primary);">${window.escapeHtml(displayName)}</h4>- <span class="ldr-status-badge" style="- background: ${getStatusColor(stats.status)};- color: white;- padding: 2px 8px;- border-radius: 12px;- font-size: 0.75rem;- font-weight: 600;- text-transform: uppercase;- ">${window.escapeHtml(stats.status)}</span>+ <span class="ldr-engine-health-badge ldr-engine-health-badge--${getStatusModifier(stats.status)}">${window.escapeHtml(stats.status)}</span></div><div class="ldr-engine-stats-grid" style="display: grid; grid-template-columns: 1fr 1fr; gap: 0.5rem; font-size: 0.875rem;"><div>@@ -1533,6 +1525,16 @@default: return 'var(--text-muted)';}}+ // The badge's modifier class (metrics.css), which sets its fill+ // together with the ink chosen for that fill.+ function getStatusModifier(status) {+ switch (status) {+ case 'healthy': return 'healthy';+ case 'degraded': return 'degraded';+ case 'poor': return 'poor';+ default: return 'unknown';+ }+ }// Format time for displayfunction formatTime(timeString) {try {diff --git a/src/local_deep_research/web/templates/pages/note_detail.html b/src/local_deep_research/web/templates/pages/note_detail.htmlindex 765f1a1769..6a44d7b5fe 100644--- a/src/local_deep_research/web/templates/pages/note_detail.html+++ b/src/local_deep_research/web/templates/pages/note_detail.html@@ -359,7 +359,7 @@border-radius: 50%;background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);border: none;- color: white;+ color: var(--text-on-accent);font-size: 1.5rem;cursor: pointer;box-shadow: 0 4px 16px rgba(var(--accent-primary-rgb), 0.4);@@ -583,7 +583,7 @@.ldr-note-action-btn.ldr-primary {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);- color: white;+ color: var(--text-on-accent);border: none;box-shadow: 0 4px 12px rgba(var(--accent-primary-rgb), 0.3);}@@ -854,7 +854,7 @@.ldr-toolbar-btn:active {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);border-color: var(--accent-primary);}@@ -1449,7 +1449,7 @@.ldr-link-suggestion-add {background: linear-gradient(135deg, var(--accent-primary) 0%, var(--accent-secondary) 100%);- color: white;+ color: var(--text-on-accent);border: none;padding: 0.35rem 0.65rem;border-radius: 8px;@@ -1517,7 +1517,7 @@/* Badge for counts */.ldr-badge {background: var(--accent-primary);- color: white;+ color: var(--text-on-accent);font-size: 0.7rem;padding: 0.15rem 0.5rem;border-radius: 10px;diff --git a/src/local_deep_research/web/templates/pages/research.html b/src/local_deep_research/web/templates/pages/research.htmlindex 80f013f399..ba3bbe5e06 100644--- a/src/local_deep_research/web/templates/pages/research.html+++ b/src/local_deep_research/web/templates/pages/research.html@@ -115,7 +115,7 @@panel meant a user could launch with the wrong policy withoutrealizing it. Always visible by design.The data-scope attribute is updated by JS on dropdown change;- CSS below colors the frame / header / icon so the active scope+ CSS below colors the frame so the active scopeis instantly recognizable without reading the dropdown value. --><style>/* Default panel = neutral slate. BOTH no longer wears@@ -123,21 +123,17 @@"Public search egress enabled" banner does that jobin text, and reserving color for active-choice scopes(sky/teal/violet) makes the cue more legible.- Specific scope rules below override per state. */+ The heading uses theme text for contrast in every scope. */.ldr-privacy-panel { border:1px solid #475569; border-radius:6px; padding:0.5rem 1rem 0.85rem; background:rgba(71, 85, 105, 0.05); transition:border-color 0.15s ease, background-color 0.15s ease; }- .ldr-privacy-panel-header { font-size:0.95rem; font-weight:600; color:#cbd5e1; margin-bottom:0.5rem; transition:color 0.15s ease; }+ .ldr-privacy-panel-header { font-size:0.95rem; font-weight:600; color:var(--text-primary); margin-bottom:0.5rem; transition:color 0.15s ease; }.ldr-privacy-panel[data-scope="public_only"] { border-color:#3b82f6; background:rgba(59, 130, 246, 0.07); }- .ldr-privacy-panel[data-scope="public_only"] .ldr-privacy-panel-header { color:#60a5fa; }.ldr-privacy-panel[data-scope="private_only"] { border-color:#14a37f; background:rgba(20, 163, 127, 0.06); }- .ldr-privacy-panel[data-scope="private_only"] .ldr-privacy-panel-header { color:#0f7a5f; }.ldr-privacy-panel[data-scope="strict"] { border-color:#8b5cf6; background:rgba(139, 92, 246, 0.07); }- .ldr-privacy-panel[data-scope="strict"] .ldr-privacy-panel-header { color:#a78bfa; }/* Unprotected = escape hatch: light-red frame as a caution cue. */.ldr-privacy-panel[data-scope="unprotected"] { border-color:#e05252; background:rgba(224, 82, 82, 0.08); }- .ldr-privacy-panel[data-scope="unprotected"] .ldr-privacy-panel-header { color:#e05252; }/* Local-inference checkboxes adopt the "local = teal" cue when on. */.ldr-privacy-panel input[type="checkbox"] { accent-color:#14a37f; }- .ldr-experimental-badge { font-size:0.8rem; font-weight:600; color:#d9a441; border:1px solid rgba(217, 164, 65, 0.4); border-radius:4px; padding:0.05rem 0.35rem; margin-left:0.4rem; vertical-align:middle; text-transform:uppercase; letter-spacing:0.02em; cursor:help; }+ .ldr-experimental-badge { font-size:0.8rem; font-weight:600; color:var(--text-primary); border:1px solid rgba(var(--warning-color-rgb), 0.4); border-radius:4px; padding:0.05rem 0.35rem; margin-left:0.4rem; vertical-align:middle; text-transform:uppercase; letter-spacing:0.02em; cursor:help; }/* Whole-workspace scope cue (research card / query textarea /chat input) lives in styles.css now so chat.html and anyfuture page that loads the shared stylesheet inherit it. */diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.htmlindex f9f1d90633..a4b366ce7a 100644--- a/src/local_deep_research/web/templates/pages/zotero.html+++ b/src/local_deep_research/web/templates/pages/zotero.html@@ -21,7 +21,7 @@color: var(--text-primary);}.ldr-zotero-actions button.ldr-zotero-primary {- background: var(--primary-color, #6e4ff6); color: #fff; border-color: transparent;+ background: var(--primary-color, #6e4ff6); color: var(--text-on-accent); border-color: transparent;}.ldr-zotero-actions button:disabled { opacity: .5; cursor: not-allowed; }.ldr-zotero-msg { margin-top: 12px; font-size: .9rem; min-height: 1.2em; }diff --git a/src/local_deep_research/web/themes/core/hashed.css b/src/local_deep_research/web/themes/core/hashed.cssindex edf99df99a..0d20b9941d 100644--- a/src/local_deep_research/web/themes/core/hashed.css+++ b/src/local_deep_research/web/themes/core/hashed.css@@ -22,6 +22,7 @@ is_default = true--success-color: #0acf97;--warning-color: #f9bc0b;--error-color: #fa5c7c;+ --text-on-accent: #000000;/* RGB variants for rgba() usage */--bg-primary-rgb: 18, 18, 18;diff --git a/src/local_deep_research/web/themes/core/high-contrast.css b/src/local_deep_research/web/themes/core/high-contrast.cssindex b5a860c457..075438c630 100644--- a/src/local_deep_research/web/themes/core/high-contrast.css+++ b/src/local_deep_research/web/themes/core/high-contrast.css@@ -20,6 +20,7 @@ description = "Maximum accessibility with WCAG AAA compliance"--success-color: #00ff00;--warning-color: #ffff00;--error-color: #ff0000;+ --text-on-accent: #000000;/* RGB variants */--bg-primary-rgb: 0, 0, 0;@@ -60,6 +61,41 @@ description = "Maximum accessibility with WCAG AAA compliance"[data-theme="high-contrast"] a:hover {color: var(--accent-tertiary);}+/* Accent-filled controls that are links keep the accent ink: the two link+ rules above (0,1,1 and 0,2,1) outrank their class rules and would draw+ cyan or green on the yellow fill. */+[data-theme="high-contrast"] a.btn-primary,+[data-theme="high-contrast"] a.btn-primary:hover,+[data-theme="high-contrast"] a.ldr-skip-link,+[data-theme="high-contrast"] a.ldr-skip-link:hover,+[data-theme="high-contrast"] a.ldr-btn-collections-primary,+[data-theme="high-contrast"] a.ldr-btn-collections-primary:hover,+[data-theme="high-contrast"] a.ldr-action-btn-rag,+[data-theme="high-contrast"] a.ldr-action-btn-rag:hover,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-accent,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-accent:hover,+[data-theme="high-contrast"] a.ldr-page-link.active,+[data-theme="high-contrast"] a.ldr-page-link.active:hover,+[data-theme="high-contrast"] a.ldr-research-chip:hover {+ color: var(--text-on-accent);+}+/* Error-filled links keep the error ink, for the same reason. */+[data-theme="high-contrast"] a.ldr-btn-danger,+[data-theme="high-contrast"] a.ldr-btn-danger:hover,+[data-theme="high-contrast"] a.ldr-action-btn-pdf,+[data-theme="high-contrast"] a.ldr-action-btn-pdf:hover,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-warning,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-warning:hover,+[data-theme="high-contrast"] a.ldr-logout-btn:hover {+ color: var(--text-on-error);+}+/* Success-filled links keep the success ink, for the same reason. */+[data-theme="high-contrast"] a.ldr-btn-success,+[data-theme="high-contrast"] a.ldr-btn-success:hover,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-success,+[data-theme="high-contrast"] a.ldr-nav-link-btn.ldr-nav-success:hover {+ color: var(--text-on-success);+}[data-theme="high-contrast"] *:focus {outline: 3px solid var(--accent-primary) !important;outline-offset: 2px;diff --git a/src/local_deep_research/web/themes/core/light.css b/src/local_deep_research/web/themes/core/light.cssindex f2b94bb6e1..c73c4e0fc6 100644--- a/src/local_deep_research/web/themes/core/light.css+++ b/src/local_deep_research/web/themes/core/light.css@@ -7,34 +7,36 @@ type = "light"description = "Clean and bright for well-lit environments"---*/[data-theme="light"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #f8f9fa;--bg-secondary: #ffffff;--bg-tertiary: #e9ecef;--accent-primary: #5c3dcc;- --accent-secondary: #7c5ce7;- --accent-tertiary: #0984e3;+ --accent-secondary: #613ae2;+ --accent-tertiary: #065897;--text-primary: #212529;--text-secondary: #495057;- --text-muted: #6c757d;+ --text-muted: #5b6269;--border-color: #dee2e6;- --success-color: #28a745;- --warning-color: #ffc107;- --error-color: #dc3545;+ --control-border: #748495;+ --success-color: #186329;+ --warning-color: #6d5300;+ --error-color: #a31d29;/* RGB variants */--bg-primary-rgb: 248, 249, 250;--bg-secondary-rgb: 255, 255, 255;--bg-tertiary-rgb: 233, 236, 239;--accent-primary-rgb: 92, 61, 204;- --accent-secondary-rgb: 124, 92, 231;- --accent-tertiary-rgb: 9, 132, 227;+ --accent-secondary-rgb: 97, 58, 226;+ --accent-tertiary-rgb: 6, 88, 151;--text-primary-rgb: 33, 37, 41;--text-secondary-rgb: 73, 80, 87;- --text-muted-rgb: 108, 117, 125;+ --text-muted-rgb: 91, 98, 105;--border-color-rgb: 222, 226, 230;- --success-color-rgb: 40, 167, 69;- --warning-color-rgb: 255, 193, 7;- --error-color-rgb: 220, 53, 69;+ --success-color-rgb: 24, 99, 41;+ --warning-color-rgb: 109, 83, 0;+ --error-color-rgb: 163, 29, 41;/* Shadows and effects */--card-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);@@ -48,6 +50,10 @@ description = "Clean and bright for well-lit environments"--highlight-color-rgb: 0, 0, 0;/* Aliases */+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/core/midnight.css b/src/local_deep_research/web/themes/core/midnight.cssindex 42ef620ce6..3bf958d97d 100644--- a/src/local_deep_research/web/themes/core/midnight.css+++ b/src/local_deep_research/web/themes/core/midnight.css@@ -20,6 +20,7 @@ description = "Deep blue aesthetic for night coding"--success-color: #57cc99;--warning-color: #fca311;--error-color: #e71d36;+ --text-on-accent: #000000;/* RGB variants */--bg-primary-rgb: 13, 27, 42;diff --git a/src/local_deep_research/web/themes/core/sepia.css b/src/local_deep_research/web/themes/core/sepia.cssindex 69ae61e1c7..7780783d86 100644--- a/src/local_deep_research/web/themes/core/sepia.css+++ b/src/local_deep_research/web/themes/core/sepia.css@@ -7,35 +7,37 @@ type = "light"description = "Eye-friendly reading inspired by Solarized"---*/[data-theme="sepia"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #f4ecd8;--bg-secondary: #fdf6e3;--bg-tertiary: #eee8d5;- --accent-primary: #b58900;- --accent-secondary: #cb4b16;- --accent-tertiary: #268bd2;- --text-primary: #5c5144;- --text-secondary: #657b83;- --text-muted: #93a1a1;+ --accent-primary: #735700;+ --accent-secondary: #9f3b11;+ --accent-tertiary: #185886;+ --text-primary: #50463b;+ --text-secondary: #445359;+ --text-muted: #556161;--border-color: #d3c6a6;- --success-color: #859900;- --warning-color: #b58900;- --error-color: #dc322f;+ --control-border: #947e49;+ --success-color: #4f5a00;+ --warning-color: #6b5100;+ --error-color: #9f1e1b;--error-text-color: #ae322b;/* RGB variants */--bg-primary-rgb: 244, 236, 216;--bg-secondary-rgb: 253, 246, 227;--bg-tertiary-rgb: 238, 232, 213;- --accent-primary-rgb: 181, 137, 0;- --accent-secondary-rgb: 203, 75, 22;- --accent-tertiary-rgb: 38, 139, 210;- --text-primary-rgb: 92, 81, 68;- --text-secondary-rgb: 101, 123, 131;- --text-muted-rgb: 147, 161, 161;+ --accent-primary-rgb: 115, 87, 0;+ --accent-secondary-rgb: 159, 59, 17;+ --accent-tertiary-rgb: 24, 88, 134;+ --text-primary-rgb: 80, 70, 59;+ --text-secondary-rgb: 68, 83, 89;+ --text-muted-rgb: 85, 97, 97;--border-color-rgb: 211, 198, 166;- --success-color-rgb: 133, 153, 0;- --warning-color-rgb: 181, 137, 0;- --error-color-rgb: 220, 50, 47;+ --success-color-rgb: 79, 90, 0;+ --warning-color-rgb: 107, 81, 0;+ --error-color-rgb: 159, 30, 27;/* Shadows and effects */--card-shadow: 0 2px 10px rgba(101, 82, 51, 0.1);@@ -49,14 +51,10 @@ description = "Eye-friendly reading inspired by Solarized"--highlight-color-rgb: 0, 0, 0;/* Aliases */+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}--/* Theme-specific adjustments */-[data-theme="sepia"] a {- color: var(--accent-tertiary);-}-[data-theme="sepia"] a:hover {- color: var(--accent-secondary);-}diff --git a/src/local_deep_research/web/themes/dev/catppuccin.css b/src/local_deep_research/web/themes/dev/catppuccin.cssindex f19d5064b1..c8feb36dbc 100644--- a/src/local_deep_research/web/themes/dev/catppuccin.css+++ b/src/local_deep_research/web/themes/dev/catppuccin.css@@ -20,6 +20,7 @@ description = "Soothing pastel theme (Mocha variant)"--success-color: #a6e3a1;--warning-color: #f9e2af;--error-color: #f38ba8;+ --text-on-accent: #000000;--bg-primary-rgb: 30, 30, 46;--bg-secondary-rgb: 49, 50, 68;diff --git a/src/local_deep_research/web/themes/dev/dracula.css b/src/local_deep_research/web/themes/dev/dracula.cssindex b6306b33bf..b165be129a 100644--- a/src/local_deep_research/web/themes/dev/dracula.css+++ b/src/local_deep_research/web/themes/dev/dracula.css@@ -20,6 +20,7 @@ description = "Purple and pink dark theme"--success-color: #50fa7b;--warning-color: #f1fa8c;--error-color: #ff5555;+ --text-on-accent: #000000;--bg-primary-rgb: 40, 42, 54;--bg-secondary-rgb: 52, 55, 70;diff --git a/src/local_deep_research/web/themes/dev/gruvbox-dark.css b/src/local_deep_research/web/themes/dev/gruvbox-dark.cssindex 0e92fa3460..c876a2bfae 100644--- a/src/local_deep_research/web/themes/dev/gruvbox-dark.css+++ b/src/local_deep_research/web/themes/dev/gruvbox-dark.css@@ -20,6 +20,7 @@ description = "Retro groove colors with warm tones (dark)"--success-color: #b8bb26;--warning-color: #fabd2f;--error-color: #fb4934;+ --text-on-accent: #000000;--bg-primary-rgb: 40, 40, 40;--bg-secondary-rgb: 60, 56, 54;diff --git a/src/local_deep_research/web/themes/dev/gruvbox-light.css b/src/local_deep_research/web/themes/dev/gruvbox-light.cssindex 6b2d1e41bf..3e40f46ac2 100644--- a/src/local_deep_research/web/themes/dev/gruvbox-light.css+++ b/src/local_deep_research/web/themes/dev/gruvbox-light.css@@ -7,33 +7,35 @@ type = "light"description = "Retro groove colors with warm tones (light)"---*/[data-theme="gruvbox-light"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #fbf1c7;--bg-secondary: #ebdbb2;--bg-tertiary: #d5c4a1;- --accent-primary: #d65d0e;- --accent-secondary: #af3a03;- --accent-tertiary: #427b58;- --text-primary: #3c3836;- --text-secondary: #504945;- --text-muted: #7c6f64;+ --accent-primary: #743308;+ --accent-secondary: #7e2a02;+ --accent-tertiary: #264531;+ --text-primary: #35312f;+ --text-secondary: #403a37;+ --text-muted: #514841;--border-color: #bdae93;- --success-color: #79740e;- --warning-color: #b57614;- --error-color: #9d0006;+ --control-border: #776749;+ --success-color: #434008;+ --warning-color: #56380a;+ --error-color: #7b0005;--bg-primary-rgb: 251, 241, 199;--bg-secondary-rgb: 235, 219, 178;--bg-tertiary-rgb: 213, 196, 161;- --accent-primary-rgb: 214, 93, 14;- --accent-secondary-rgb: 175, 58, 3;- --accent-tertiary-rgb: 66, 123, 88;- --text-primary-rgb: 60, 56, 54;- --text-secondary-rgb: 80, 73, 69;- --text-muted-rgb: 124, 111, 100;+ --accent-primary-rgb: 116, 51, 8;+ --accent-secondary-rgb: 126, 42, 2;+ --accent-tertiary-rgb: 38, 69, 49;+ --text-primary-rgb: 53, 49, 47;+ --text-secondary-rgb: 64, 58, 55;+ --text-muted-rgb: 81, 72, 65;--border-color-rgb: 189, 174, 147;- --success-color-rgb: 121, 116, 14;- --warning-color-rgb: 181, 118, 20;- --error-color-rgb: 157, 0, 6;+ --success-color-rgb: 67, 64, 8;+ --warning-color-rgb: 86, 56, 10;+ --error-color-rgb: 123, 0, 5;--card-shadow: 0 2px 12px rgba(60, 56, 54, 0.1);--glow-effect: 0 0 10px rgba(214, 93, 14, 0.15);@@ -44,6 +46,10 @@ description = "Retro groove colors with warm tones (light)"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/dev/monokai.css b/src/local_deep_research/web/themes/dev/monokai.cssindex 5975b87b6e..01baa8ac01 100644--- a/src/local_deep_research/web/themes/dev/monokai.css+++ b/src/local_deep_research/web/themes/dev/monokai.css@@ -20,6 +20,7 @@ description = "Vibrant colors on dark background"--success-color: #a6e22e;--warning-color: #e6db74;--error-color: #f92672;+ --text-on-accent: #000000;--bg-primary-rgb: 39, 40, 34;--bg-secondary-rgb: 62, 61, 50;diff --git a/src/local_deep_research/web/themes/dev/nord.css b/src/local_deep_research/web/themes/dev/nord.cssindex c7ba2555c9..3dfb428e31 100644--- a/src/local_deep_research/web/themes/dev/nord.css+++ b/src/local_deep_research/web/themes/dev/nord.css@@ -20,6 +20,7 @@ description = "Arctic, north-bluish color palette"--success-color: #a3be8c;--warning-color: #ebcb8b;--error-color: #bf616a;+ --text-on-accent: #000000;--bg-primary-rgb: 46, 52, 64;--bg-secondary-rgb: 59, 66, 82;diff --git a/src/local_deep_research/web/themes/dev/one-dark.css b/src/local_deep_research/web/themes/dev/one-dark.cssindex a05ecefdb2..92a32306fb 100644--- a/src/local_deep_research/web/themes/dev/one-dark.css+++ b/src/local_deep_research/web/themes/dev/one-dark.css@@ -20,6 +20,7 @@ description = "Atom editor inspired dark theme"--success-color: #98c379;--warning-color: #e5c07b;--error-color: #e06c75;+ --text-on-accent: #000000;--bg-primary-rgb: 33, 37, 43;--bg-secondary-rgb: 40, 44, 52;diff --git a/src/local_deep_research/web/themes/dev/solarized-dark.css b/src/local_deep_research/web/themes/dev/solarized-dark.cssindex b1f3c9b889..3d3a235ff5 100644--- a/src/local_deep_research/web/themes/dev/solarized-dark.css+++ b/src/local_deep_research/web/themes/dev/solarized-dark.css@@ -20,6 +20,7 @@ description = "Ethan Schoonover's precision color scheme (dark)"--success-color: #859900;--warning-color: #b58900;--error-color: #dc322f;+ --text-on-accent: #000000;--bg-primary-rgb: 0, 43, 54;--bg-secondary-rgb: 7, 54, 66;diff --git a/src/local_deep_research/web/themes/dev/solarized-light.css b/src/local_deep_research/web/themes/dev/solarized-light.cssindex 35d4c8e144..1cf846ff82 100644--- a/src/local_deep_research/web/themes/dev/solarized-light.css+++ b/src/local_deep_research/web/themes/dev/solarized-light.css@@ -7,33 +7,35 @@ type = "light"description = "Ethan Schoonover's precision color scheme (light)"---*/[data-theme="solarized-light"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #fdf6e3;--bg-secondary: #eee8d5;--bg-tertiary: #ddd6c3;- --accent-primary: #268bd2;- --accent-secondary: #2aa198;- --accent-tertiary: #859900;+ --accent-primary: #17547f;+ --accent-secondary: #185a55;+ --accent-tertiary: #454f00;--text-primary: #073642;- --text-secondary: #586e75;- --text-muted: #93a1a1;+ --text-secondary: #3a484d;+ --text-muted: #4b5656;--border-color: #93a1a1;- --success-color: #859900;- --warning-color: #b58900;- --error-color: #dc322f;+ --control-border: #687777;+ --success-color: #454f00;+ --warning-color: #5c4700;+ --error-color: #8b1a18;--bg-primary-rgb: 253, 246, 227;--bg-secondary-rgb: 238, 232, 213;--bg-tertiary-rgb: 221, 214, 195;- --accent-primary-rgb: 38, 139, 210;- --accent-secondary-rgb: 42, 161, 152;- --accent-tertiary-rgb: 133, 153, 0;+ --accent-primary-rgb: 23, 84, 127;+ --accent-secondary-rgb: 24, 90, 85;+ --accent-tertiary-rgb: 69, 79, 0;--text-primary-rgb: 7, 54, 66;- --text-secondary-rgb: 88, 110, 117;- --text-muted-rgb: 147, 161, 161;+ --text-secondary-rgb: 58, 72, 77;+ --text-muted-rgb: 75, 86, 86;--border-color-rgb: 147, 161, 161;- --success-color-rgb: 133, 153, 0;- --warning-color-rgb: 181, 137, 0;- --error-color-rgb: 220, 50, 47;+ --success-color-rgb: 69, 79, 0;+ --warning-color-rgb: 92, 71, 0;+ --error-color-rgb: 139, 26, 24;--card-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);--glow-effect: 0 0 10px rgba(38, 139, 210, 0.15);@@ -44,6 +46,10 @@ description = "Ethan Schoonover's precision color scheme (light)"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/dev/tokyo-night.css b/src/local_deep_research/web/themes/dev/tokyo-night.cssindex 102ad4cf75..718441378a 100644--- a/src/local_deep_research/web/themes/dev/tokyo-night.css+++ b/src/local_deep_research/web/themes/dev/tokyo-night.css@@ -20,6 +20,7 @@ description = "Neon colors inspired by Tokyo lights"--success-color: #9ece6a;--warning-color: #e0af68;--error-color: #f7768e;+ --text-on-accent: #000000;--bg-primary-rgb: 26, 27, 38;--bg-secondary-rgb: 36, 40, 59;diff --git a/src/local_deep_research/web/themes/loader.py b/src/local_deep_research/web/themes/loader.pyindex daed2747a2..f702116978 100644--- a/src/local_deep_research/web/themes/loader.py+++ b/src/local_deep_research/web/themes/loader.py@@ -10,6 +10,7 @@ from pathlib import Pathfrom loguru import loggerfrom .schema import (+ LIGHT_THEME_REQUIRED_VARIABLES,REQUIRED_RGB_VARIANTS,REQUIRED_VARIABLES,ThemeMetadata,@@ -22,6 +23,19 @@ FRONTMATTER_PATTERN = re.compile(r"/\*---\s*(.*?)\s*---\*/", re.DOTALL)# Pattern to extract theme ID from CSS selectorTHEME_ID_PATTERN = re.compile(r'\[data-theme="([^"]+)"\]')+# Matches CSS comments, including the TOML frontmatter block, so declaration+# scanning can ignore anything that is only mentioned in a comment.+CSS_COMMENT_PATTERN = re.compile(r"/\*.*?\*/", re.DOTALL)++# Matches an actual custom-property *declaration* (`--name: value;`) at the+# start of a line or right after a `{` / `;` (so single-line and minified+# rules count too), as opposed to a `var(--name)` usage elsewhere in the+# value, or a longer name that merely starts with the same characters+# (e.g. `--control-border-hover` must not satisfy `--control-border`).+CUSTOM_PROPERTY_DECLARATION_PATTERN = re.compile(+ r"(?:^|[{;])\s*(--[\w-]+)\s*:", re.MULTILINE+)+class ThemeLoader:"""Loads and parses theme files from a directory."""@@ -61,6 +75,28 @@ class ThemeLoader:match = THEME_ID_PATTERN.search(css_content)return match.group(1) if match else None+ def declared_custom_properties(self, css_content: str) -> set[str]:+ """Custom property names actually *declared* in the CSS.++ Comments are stripped first so a variable only mentioned in a+ comment (or referenced via `var(--name)`) isn't mistaken for a+ declaration, and matching is on the exact property name so+ `--control-border` doesn't match `--control-border-hover`.++ Args:+ css_content: The CSS file content++ Returns:+ Set of declared custom property names, e.g. {"--text-primary"}+ """+ without_comments = CSS_COMMENT_PATTERN.sub("", css_content)+ return {+ match.group(1)+ for match in CUSTOM_PROPERTY_DECLARATION_PATTERN.finditer(+ without_comments+ )+ }+def validate_css_variables(self, css_content: str, theme_id: str) -> tuple[list[str], list[str]]:@@ -136,6 +172,18 @@ class ThemeLoader:theme_type = meta.get("type", "dark")if theme_type not in ("dark", "light"):theme_type = "dark"+ if theme_type == "light":+ declared_vars = self.declared_custom_properties(content)+ missing_light = [+ var+ for var in LIGHT_THEME_REQUIRED_VARIABLES+ if var not in declared_vars+ ]+ if missing_light:+ logger.warning(+ f"Light theme {theme_id} missing variables: "+ f"{missing_light}"+ )return ThemeMetadata(id=theme_id,diff --git a/src/local_deep_research/web/themes/nature/forest.css b/src/local_deep_research/web/themes/nature/forest.cssindex f77a58a273..610771ace5 100644--- a/src/local_deep_research/web/themes/nature/forest.css+++ b/src/local_deep_research/web/themes/nature/forest.css@@ -20,6 +20,7 @@ description = "Natural greens inspired by woodland"--success-color: #69f0ae;--warning-color: #ffca28;--error-color: #ef5350;+ --text-on-accent: #000000;--bg-primary-rgb: 26, 47, 26;--bg-secondary-rgb: 36, 53, 36;diff --git a/src/local_deep_research/web/themes/nature/lavender.css b/src/local_deep_research/web/themes/nature/lavender.cssindex 270fee9d27..0f4511e617 100644--- a/src/local_deep_research/web/themes/nature/lavender.css+++ b/src/local_deep_research/web/themes/nature/lavender.css@@ -20,6 +20,7 @@ description = "Soft purple hues for a calm feel"--success-color: #69f0ae;--warning-color: #ffe082;--error-color: #ff5252;+ --text-on-accent: #000000;--bg-primary-rgb: 30, 30, 63;--bg-secondary-rgb: 42, 42, 84;diff --git a/src/local_deep_research/web/themes/nature/ocean.css b/src/local_deep_research/web/themes/nature/ocean.cssindex 0bd857339c..d57d9f90a2 100644--- a/src/local_deep_research/web/themes/nature/ocean.css+++ b/src/local_deep_research/web/themes/nature/ocean.css@@ -20,6 +20,7 @@ description = "Deep sea blues and teals"--success-color: #00e676;--warning-color: #ffd54f;--error-color: #ff5252;+ --text-on-accent: #000000;--bg-primary-rgb: 12, 24, 33;--bg-secondary-rgb: 27, 40, 56;diff --git a/src/local_deep_research/web/themes/nature/rose.css b/src/local_deep_research/web/themes/nature/rose.cssindex d53b5b3f79..ee93ac4b0c 100644--- a/src/local_deep_research/web/themes/nature/rose.css+++ b/src/local_deep_research/web/themes/nature/rose.css@@ -20,6 +20,7 @@ description = "Soft pink and magenta hues"--success-color: #69f0ae;--warning-color: #ffe082;--error-color: #ff5252;+ --text-on-accent: #000000;--bg-primary-rgb: 45, 27, 45;--bg-secondary-rgb: 61, 38, 64;diff --git a/src/local_deep_research/web/themes/nature/sunset.css b/src/local_deep_research/web/themes/nature/sunset.cssindex 9e3d61f822..ebebfc3fa3 100644--- a/src/local_deep_research/web/themes/nature/sunset.css+++ b/src/local_deep_research/web/themes/nature/sunset.css@@ -20,6 +20,7 @@ description = "Warm orange and pink tones"--success-color: #00d2d3;--warning-color: #feca57;--error-color: #ff6b6b;+ --text-on-accent: #000000;--bg-primary-rgb: 26, 26, 46;--bg-secondary-rgb: 45, 45, 68;diff --git a/src/local_deep_research/web/themes/research/ayu-mirage.css b/src/local_deep_research/web/themes/research/ayu-mirage.cssindex 1a1c2bf039..5109b27dfe 100644--- a/src/local_deep_research/web/themes/research/ayu-mirage.css+++ b/src/local_deep_research/web/themes/research/ayu-mirage.css@@ -20,6 +20,7 @@ description = "Modern minimalist twilight aesthetic"--success-color: #87D96C;--warning-color: #FFD173;--error-color: #FF6666;+ --text-on-accent: #000000;--bg-primary-rgb: 31, 36, 48;--bg-secondary-rgb: 36, 41, 54;diff --git a/src/local_deep_research/web/themes/research/everforest-dark.css b/src/local_deep_research/web/themes/research/everforest-dark.cssindex 341e925de4..f5b629dcd9 100644--- a/src/local_deep_research/web/themes/research/everforest-dark.css+++ b/src/local_deep_research/web/themes/research/everforest-dark.css@@ -20,6 +20,7 @@ description = "Green-based theme for eye protection"--success-color: #A7C080;--warning-color: #DBBC7F;--error-color: #E67E80;+ --text-on-accent: #000000;--bg-primary-rgb: 45, 53, 59;--bg-secondary-rgb: 52, 63, 68;diff --git a/src/local_deep_research/web/themes/research/everforest-light.css b/src/local_deep_research/web/themes/research/everforest-light.cssindex 5e00c2dd3b..e8e5d0da5a 100644--- a/src/local_deep_research/web/themes/research/everforest-light.css+++ b/src/local_deep_research/web/themes/research/everforest-light.css@@ -7,33 +7,35 @@ type = "light"description = "Soft green warmth for daytime"---*/[data-theme="everforest-light"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #FDF6E3;--bg-secondary: #F4F0D9;--bg-tertiary: #E6E2CC;- --accent-primary: #8DA101;- --accent-secondary: #35A77C;- --accent-tertiary: #3A94C5;- --text-primary: #5C6A72;- --text-secondary: #829181;- --text-muted: #A6B0A0;+ --accent-primary: #525d01;+ --accent-secondary: #1f6249;+ --accent-tertiary: #215671;+ --text-primary: #3c454b;+ --text-secondary: #464f45;+ --text-muted: #545e4e;--border-color: #E0DCC7;- --success-color: #8DA101;- --warning-color: #DFA000;- --error-color: #F85552;+ --control-border: #867c4a;+ --success-color: #4c5601;+ --warning-color: #6a4b00;+ --error-color: #9c0907;--bg-primary-rgb: 253, 246, 227;--bg-secondary-rgb: 244, 240, 217;--bg-tertiary-rgb: 230, 226, 204;- --accent-primary-rgb: 141, 161, 1;- --accent-secondary-rgb: 53, 167, 124;- --accent-tertiary-rgb: 58, 148, 197;- --text-primary-rgb: 92, 106, 114;- --text-secondary-rgb: 130, 145, 129;- --text-muted-rgb: 166, 176, 160;+ --accent-primary-rgb: 82, 93, 1;+ --accent-secondary-rgb: 31, 98, 73;+ --accent-tertiary-rgb: 33, 86, 113;+ --text-primary-rgb: 60, 69, 75;+ --text-secondary-rgb: 70, 79, 69;+ --text-muted-rgb: 84, 94, 78;--border-color-rgb: 224, 220, 199;- --success-color-rgb: 141, 161, 1;- --warning-color-rgb: 223, 160, 0;- --error-color-rgb: 248, 85, 82;+ --success-color-rgb: 76, 86, 1;+ --warning-color-rgb: 106, 75, 0;+ --error-color-rgb: 156, 9, 7;--card-shadow: 0 2px 12px rgba(92, 106, 114, 0.08);--glow-effect: 0 0 10px rgba(141, 161, 1, 0.15);@@ -44,6 +46,10 @@ description = "Soft green warmth for daytime"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/research/flexoki-dark.css b/src/local_deep_research/web/themes/research/flexoki-dark.cssindex 1452320cf2..52ca44b91d 100644--- a/src/local_deep_research/web/themes/research/flexoki-dark.css+++ b/src/local_deep_research/web/themes/research/flexoki-dark.css@@ -20,6 +20,7 @@ description = "Ink-inspired theme for prose and code"--success-color: #879A39;--warning-color: #D0A215;--error-color: #D14D41;+ --text-on-accent: #000000;--bg-primary-rgb: 16, 15, 15;--bg-secondary-rgb: 28, 27, 26;diff --git a/src/local_deep_research/web/themes/research/flexoki-light.css b/src/local_deep_research/web/themes/research/flexoki-light.cssindex 598cc74c01..27040e2719 100644--- a/src/local_deep_research/web/themes/research/flexoki-light.css+++ b/src/local_deep_research/web/themes/research/flexoki-light.css@@ -7,33 +7,35 @@ type = "light"description = "Paper-inspired warm reading tones"---*/[data-theme="flexoki-light"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #FFFCF0;--bg-secondary: #F2F0E5;--bg-tertiary: #E6E4D9;- --accent-primary: #BC5215;- --accent-secondary: #66800B;- --accent-tertiary: #205EA6;- --text-primary: #100F0F;+ --accent-primary: #934010;+ --accent-secondary: #4d6008;+ --accent-tertiary: #1c5292;+ --text-primary: #100f0f;--text-secondary: #343331;- --text-muted: #6F6E69;+ --text-muted: #5d5c58;--border-color: #CECDC3;- --success-color: #66800B;- --warning-color: #AD8301;- --error-color: #AF3029;+ --control-border: #807e69;+ --success-color: #475808;+ --warning-color: #684e01;+ --error-color: #952923;--bg-primary-rgb: 255, 252, 240;--bg-secondary-rgb: 242, 240, 229;--bg-tertiary-rgb: 230, 228, 217;- --accent-primary-rgb: 188, 82, 21;- --accent-secondary-rgb: 102, 128, 11;- --accent-tertiary-rgb: 32, 94, 166;+ --accent-primary-rgb: 147, 64, 16;+ --accent-secondary-rgb: 77, 96, 8;+ --accent-tertiary-rgb: 28, 82, 146;--text-primary-rgb: 16, 15, 15;--text-secondary-rgb: 52, 51, 49;- --text-muted-rgb: 111, 110, 105;+ --text-muted-rgb: 93, 92, 88;--border-color-rgb: 206, 205, 195;- --success-color-rgb: 102, 128, 11;- --warning-color-rgb: 173, 131, 1;- --error-color-rgb: 175, 48, 41;+ --success-color-rgb: 71, 88, 8;+ --warning-color-rgb: 104, 78, 1;+ --error-color-rgb: 149, 41, 35;--card-shadow: 0 2px 12px rgba(16, 15, 15, 0.08);--glow-effect: 0 0 10px rgba(188, 82, 21, 0.15);@@ -44,6 +46,10 @@ description = "Paper-inspired warm reading tones"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/research/kanagawa.css b/src/local_deep_research/web/themes/research/kanagawa.cssindex aa55c82297..df62a96e1b 100644--- a/src/local_deep_research/web/themes/research/kanagawa.css+++ b/src/local_deep_research/web/themes/research/kanagawa.css@@ -20,6 +20,9 @@ description = "Japanese-inspired, The Great Wave palette"--success-color: #98BB6C;--warning-color: #E6C384;--error-color: #C34043;+ --text-on-accent: #000000;+ /* Black reaches only 4.13:1 on this --error-color; white 5.08:1. */+ --text-on-error: #ffffff;--bg-primary-rgb: 31, 31, 40;--bg-secondary-rgb: 42, 42, 55;diff --git a/src/local_deep_research/web/themes/research/light-owl.css b/src/local_deep_research/web/themes/research/light-owl.cssindex f533f3a378..4adb6a64c4 100644--- a/src/local_deep_research/web/themes/research/light-owl.css+++ b/src/local_deep_research/web/themes/research/light-owl.css@@ -7,33 +7,35 @@ type = "light"description = "Accessibility-focused for daylight"---*/[data-theme="light-owl"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #F0F0F0;--bg-secondary: #FAFAFA;--bg-tertiary: #E0E0E0;- --accent-primary: #4876D6;- --accent-secondary: #994CC3;- --accent-tertiary: #0C969B;- --text-primary: #403F53;- --text-secondary: #5C5C72;- --text-muted: #90A7B2;+ --accent-primary: #2752ac;+ --accent-secondary: #7b36a1;+ --accent-tertiary: #07585c;+ --text-primary: #403f53;+ --text-secondary: #4a4a5c;+ --text-muted: #485d68;--border-color: #D6D6D6;- --success-color: #4CA64C;- --warning-color: #DAAA01;- --error-color: #DE3D3B;+ --control-border: #7b7b7b;+ --success-color: #2a5a2a;+ --warning-color: #634d00;+ --error-color: #971b1a;--bg-primary-rgb: 240, 240, 240;--bg-secondary-rgb: 250, 250, 250;--bg-tertiary-rgb: 224, 224, 224;- --accent-primary-rgb: 72, 118, 214;- --accent-secondary-rgb: 153, 76, 195;- --accent-tertiary-rgb: 12, 150, 155;+ --accent-primary-rgb: 39, 82, 172;+ --accent-secondary-rgb: 123, 54, 161;+ --accent-tertiary-rgb: 7, 88, 92;--text-primary-rgb: 64, 63, 83;- --text-secondary-rgb: 92, 92, 114;- --text-muted-rgb: 144, 167, 178;+ --text-secondary-rgb: 74, 74, 92;+ --text-muted-rgb: 72, 93, 104;--border-color-rgb: 214, 214, 214;- --success-color-rgb: 76, 166, 76;- --warning-color-rgb: 218, 170, 1;- --error-color-rgb: 222, 61, 59;+ --success-color-rgb: 42, 90, 42;+ --warning-color-rgb: 99, 77, 0;+ --error-color-rgb: 151, 27, 26;--card-shadow: 0 2px 12px rgba(64, 63, 83, 0.08);--glow-effect: 0 0 10px rgba(72, 118, 214, 0.15);@@ -44,6 +46,10 @@ description = "Accessibility-focused for daylight"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/research/night-owl.css b/src/local_deep_research/web/themes/research/night-owl.cssindex d33c54c580..5d92833cea 100644--- a/src/local_deep_research/web/themes/research/night-owl.css+++ b/src/local_deep_research/web/themes/research/night-owl.css@@ -20,6 +20,7 @@ description = "Accessibility-focused for low light"--success-color: #9CCC65;--warning-color: #FFCA28;--error-color: #EF5350;+ --text-on-accent: #000000;--bg-primary-rgb: 1, 22, 39;--bg-secondary-rgb: 11, 41, 66;diff --git a/src/local_deep_research/web/themes/research/palenight.css b/src/local_deep_research/web/themes/research/palenight.cssindex 119d125244..045ebdab79 100644--- a/src/local_deep_research/web/themes/research/palenight.css+++ b/src/local_deep_research/web/themes/research/palenight.css@@ -20,6 +20,7 @@ description = "Material Design inspired purple tones"--success-color: #c3e88d;--warning-color: #ffcb6b;--error-color: #ff5370;+ --text-on-accent: #000000;--bg-primary-rgb: 41, 45, 62;--bg-secondary-rgb: 48, 51, 72;diff --git a/src/local_deep_research/web/themes/research/rose-pine-dawn.css b/src/local_deep_research/web/themes/research/rose-pine-dawn.cssindex af2056be9b..a880ac439a 100644--- a/src/local_deep_research/web/themes/research/rose-pine-dawn.css+++ b/src/local_deep_research/web/themes/research/rose-pine-dawn.css@@ -7,33 +7,35 @@ type = "light"description = "Rosé Pine for daylight"---*/[data-theme="rose-pine-dawn"] {+ /* Keep text readable on every surface, including tinted controls. */--bg-primary: #faf4ed;--bg-secondary: #fffaf3;--bg-tertiary: #f2e9e1;- --accent-primary: #d7827e;- --accent-secondary: #907aa9;- --accent-tertiary: #56949f;- --text-primary: #575279;- --text-secondary: #797593;- --text-muted: #9893a5;+ --accent-primary: #a33833;+ --accent-secondary: #695381;+ --accent-tertiary: #365c64;+ --text-primary: #4a4566;+ --text-secondary: #524f65;+ --text-muted: #635e70;--border-color: #dfdad9;- --success-color: #56949f;- --warning-color: #ea9d34;- --error-color: #b4637a;+ --control-border: #907e7b;+ --success-color: #355c63;+ --warning-color: #7a4c0d;+ --error-color: #854054;--bg-primary-rgb: 250, 244, 237;--bg-secondary-rgb: 255, 250, 243;--bg-tertiary-rgb: 242, 233, 225;- --accent-primary-rgb: 215, 130, 126;- --accent-secondary-rgb: 144, 122, 169;- --accent-tertiary-rgb: 86, 148, 159;- --text-primary-rgb: 87, 82, 121;- --text-secondary-rgb: 121, 117, 147;- --text-muted-rgb: 152, 147, 165;+ --accent-primary-rgb: 163, 56, 51;+ --accent-secondary-rgb: 105, 83, 129;+ --accent-tertiary-rgb: 54, 92, 100;+ --text-primary-rgb: 74, 69, 102;+ --text-secondary-rgb: 82, 79, 101;+ --text-muted-rgb: 99, 94, 112;--border-color-rgb: 223, 218, 217;- --success-color-rgb: 86, 148, 159;- --warning-color-rgb: 234, 157, 52;- --error-color-rgb: 180, 99, 122;+ --success-color-rgb: 53, 92, 99;+ --warning-color-rgb: 122, 76, 13;+ --error-color-rgb: 133, 64, 84;--card-shadow: 0 2px 12px rgba(87, 82, 121, 0.08);--glow-effect: 0 0 10px rgba(215, 130, 126, 0.15);@@ -44,6 +46,10 @@ description = "Rosé Pine for daylight"/* Theme-aware colors for shadows and highlights */--shadow-color-rgb: 0, 0, 0;--highlight-color-rgb: 0, 0, 0;+ --text-on-accent: #ffffff;+ --text-on-warning: #ffffff;+ --text-on-success: #ffffff;+ --text-on-error: #ffffff;--primary-color: var(--accent-primary);--card-bg: var(--bg-secondary);}diff --git a/src/local_deep_research/web/themes/research/rose-pine.css b/src/local_deep_research/web/themes/research/rose-pine.cssindex 2d60fe4008..e31fa575e5 100644--- a/src/local_deep_research/web/themes/research/rose-pine.css+++ b/src/local_deep_research/web/themes/research/rose-pine.css@@ -20,6 +20,7 @@ description = "Warm and soft soho vibes"--success-color: #9ccfd8;--warning-color: #f6c177;--error-color: #eb6f92;+ --text-on-accent: #000000;--bg-primary-rgb: 25, 23, 36;--bg-secondary-rgb: 31, 29, 46;diff --git a/src/local_deep_research/web/themes/research/vesper.css b/src/local_deep_research/web/themes/research/vesper.cssindex 8443dd6958..b26eb25fa1 100644--- a/src/local_deep_research/web/themes/research/vesper.css+++ b/src/local_deep_research/web/themes/research/vesper.css@@ -20,6 +20,7 @@ description = "Warm peppermint and orange accents"--success-color: #60CDAB;--warning-color: #FFC799;--error-color: #F07171;+ --text-on-accent: #000000;--bg-primary-rgb: 16, 16, 16;--bg-secondary-rgb: 28, 28, 28;diff --git a/src/local_deep_research/web/themes/schema.py b/src/local_deep_research/web/themes/schema.pyindex ae1bc8e371..36b33a32ae 100644--- a/src/local_deep_research/web/themes/schema.py+++ b/src/local_deep_research/web/themes/schema.py@@ -24,6 +24,20 @@ REQUIRED_VARIABLES: list[str] = ["--error-color",]+# Light palettes darken the status colors so they read as text on pale+# surfaces, so each must also say which ink sits on a filled accent, a filled+# warning, a filled error and a filled success, and how strong an input edge+# is. Dark+# palettes inherit the styles.css defaults (the shipped ones also set+# --text-on-accent, since white is too faint on their light accents).+LIGHT_THEME_REQUIRED_VARIABLES: list[str] = [+ "--control-border",+ "--text-on-accent",+ "--text-on-warning",+ "--text-on-error",+ "--text-on-success",+]+# RGB variants for rgba() usageREQUIRED_RGB_VARIANTS: list[str] = ["--bg-primary-rgb",diff --git a/tests/accessibility_tests/theme-contrast.spec.js b/tests/accessibility_tests/theme-contrast.spec.jsnew file mode 100644index 0000000000..69b1ca2ae5--- /dev/null+++ b/tests/accessibility_tests/theme-contrast.spec.js@@ -0,0 +1,281 @@+/** Actual rendered contrast, including shared controls that bypass theme tokens. */+import { test, expect, devices } from '@playwright/test';+import AxeBuilder from '@axe-core/playwright';++const pages = [+ '/', '/settings/', '/history/', '/library/', '/news/', '/chat/',+ '/notes/', '/library/collections', '/library/collections/create',+ '/library/download-manager', '/library/search/', '/library/zotero',+ '/news/subscriptions', '/metrics/', '/metrics/journals', '/benchmark/',+ '/benchmark/results', '/library/embedding-settings',+];++async function assertContrast(page, include, { requireResolved = false } = {}) {+ let builder = new AxeBuilder({ page }).withRules(['color-contrast']);+ if (include) builder = builder.include(include);+ const { violations, incomplete } = await builder.analyze();+ const failures = violations.flatMap(violation => violation.nodes.map(node => ({+ target: node.target,+ reason: node.failureSummary,+ })));+ expect(failures).toEqual([]);+ if (requireResolved) {+ expect(incomplete.flatMap(rule => rule.nodes.map(node => ({+ target: node.target,+ reason: node.any.map(check => check.message),+ }))), 'unresolved contrast is not a passing contrast check').toEqual([]);+ }+}++// Axe checks text contrast but does not detect a disappearing close icon or+// an input outline blending into its surface. Check their rendered colors too.+async function assertControlContrast(locator, pseudo = null) {+ const result = await locator.evaluate((element, pseudoElement) => {+ const foregroundStyle = getComputedStyle(element, pseudoElement);+ const foreground = pseudoElement+ ? foregroundStyle.backgroundColor : foregroundStyle.borderTopColor;+ let surface = element;+ let background = getComputedStyle(surface).backgroundColor;+ while (background === 'rgba(0, 0, 0, 0)' && surface.parentElement) {+ surface = surface.parentElement;+ background = getComputedStyle(surface).backgroundColor;+ }+ // rgb(r, g, b) is opaque; rgba(r, g, b, a) carries its alpha. Dropping+ // the alpha would turn a missing pseudo-element into opaque black.+ const channels = color => color.match(/[\d.]+/g).map(Number);+ const [fr, fg, fb, alpha = 1] = channels(foreground);+ const [br, bg, bb] = channels(background);+ // A translucent stroke is seen blended over the surface behind it.+ const blended = [[fr, br], [fg, bg], [fb, bb]]+ .map(([front, back]) => alpha * front + (1 - alpha) * back);+ const luminance = rgb => rgb+ .map(value => value / 255)+ .map(value => (value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4))+ .reduce((sum, value, index) => sum + value * [0.2126, 0.7152, 0.0722][index], 0);+ const [dark, light] = [luminance(blended), luminance([br, bg, bb])].sort((a, b) => a - b);+ return {+ ratio: (light + 0.05) / (dark + 0.05),+ alpha,+ content: pseudoElement ? foregroundStyle.content : null,+ color: foreground,+ };+ }, pseudo);+ if (pseudo) {+ expect(result.content, `${pseudo} must be rendered`).not.toBe('none');+ expect(result.content, `${pseudo} must be rendered`).not.toBe('normal');+ }+ expect(result.alpha, `icon or control boundary must not be transparent (${result.color})`).toBeGreaterThan(0);+ expect(result.ratio, 'visible icon or control boundary needs at least 3:1 contrast').toBeGreaterThanOrEqual(3);+ return result;+}++async function applyTheme(page, theme) {+ // Avoid persisting test preferences or hitting the settings write rate limit.+ await page.evaluate(id => window.themeService.setTheme(id, false), theme);+ await expect(page.locator('html')).toHaveAttribute('data-theme', theme);+ // Allow the actual color/background transitions to finish before axe reads them.+ await page.waitForTimeout(400);+}++// Exercise empty, partly indexed and fully indexed cards without creating+// collections or starting embedding work on the test server.+async function loadCollectionFixtures(page) {+ await page.route('**/library/api/collections', route => route.fulfill({ json: {+ success: true,+ collections: [+ { id: 'empty', name: 'Empty collection', description: 'Ready for your first documents.', document_count: 0 },+ { id: 'pending', name: 'Literature review — renewable energy for homes',+ description: 'Working papers and source material for the research project.',+ document_count: 5, indexed_document_count: 3, created_at: '2026-01-15T12:00:00Z',+ embedding: { provider: 'sentence_transformers', model: 'sentence-transformers/all-MiniLM-L6-v2' } },+ { id: 'indexed', name: 'Indexed collection', document_count: 3, indexed_document_count: 3 },+ ],+ } }));+ // The scheduled-indexing row appears asynchronously. It must be present to+ // reproduce the toolbar overflow; the initial hidden row can mask the bug.+ await page.route(/\/settings\/api\/document_scheduler\.(enabled|sweep_library_collections|generate_rag)$/, route =>+ route.fulfill({ json: { value: route.request().url().endsWith('.enabled') } }));+ await page.goto('/library/collections');+ await page.waitForFunction(() => window.themeService);+ await expect(page.locator('#background-sweep-toggle-row')).toBeVisible();+ await expect(page.locator('.ldr-collection-card-wrapper')).toHaveCount(3);+ await expect(page.locator('.ldr-pending-index-badge')).toHaveText('2 pending indexing');+}++async function assertHorizontallyVisible(locator) {+ const bounds = await locator.evaluate(element => {+ const rect = element.getBoundingClientRect();+ return { left: rect.left, right: rect.right, viewport: window.innerWidth };+ });+ // overflow-x:hidden can keep document.scrollWidth equal to the viewport+ // even when a button is completely clipped. Check the element itself.+ expect(bounds.left).toBeGreaterThanOrEqual(0);+ expect(bounds.right).toBeLessThanOrEqual(bounds.viewport);+}++test('collection controls remain reachable from narrow phones to desktop', async ({ page }) => {+ await loadCollectionFixtures(page);+ await applyTheme(page, 'sepia');+ for (const width of [320, 393, 768, 1024, 1440]) {+ await test.step(`${width}px`, async () => {+ await page.setViewportSize({ width, height: 900 });+ for (const selector of ['#create-collection-btn', '#auto-index-toggle', '#background-sweep-toggle']) {+ const control = page.locator(selector);+ await assertHorizontallyVisible(control);+ await control.scrollIntoViewIfNeeded();+ await control.click({ trial: true });+ }+ for (const card of await page.locator('.ldr-collection-card-wrapper').all()) {+ await assertHorizontallyVisible(card);+ for (const label of await card.locator('h3, .ldr-stat-item span').all()) {+ await assertHorizontallyVisible(label);+ }+ }+ });+ }+ await page.setViewportSize({ width: 393, height: 851 });+ await page.getByRole('link', { name: 'Create Collection', exact: true }).click();+ await expect(page).toHaveURL(/\/library\/collections\/create$/);+ await expect(page.getByRole('heading', { name: 'Create New Collection' })).toBeVisible();+});++// Both profiles run under the standard chromium project, including CI.+for (const [profile, device] of [+ ['desktop', devices['Desktop Chrome']],+ ['mobile', devices['Pixel 5']],+]) {+ test.describe(profile, () => {+ const { defaultBrowserType: _defaultBrowserType, ...contextOptions } = device;+ test.use({ ...contextOptions, colorScheme: 'light' });++ for (const route of pages) {+ test(`all light themes have readable text on ${route}`, async ({ page }) => {+ test.setTimeout(120_000);+ await page.goto(route);+ await page.waitForFunction(() => window.themeService && window.LDR_THEME_METADATA);+ if (route === '/') {+ // A cold provider discovery can otherwise hide half the advanced form.+ await expect(page.locator('#model_provider')).not.toContainText('Loading providers', { timeout: 30_000 });+ }+ if (route === '/settings/') {+ // Settings sections start collapsed on every viewport (#5425).+ // Open the first three (database, backups, LLM) just as a+ // reader would, so axe samples real rendered settings text.+ for (let index = 0; index < 3; index++) {+ await page.locator('.ldr-settings-section-header.collapsed').first().click();+ }+ await expect(page.locator('.ldr-settings-item:visible').first()).toBeVisible({ timeout: 30_000 });+ }+ if (route === '/metrics/journals') {+ await expect(page.locator('#ldr-sources-grid > div').first()).toBeVisible({ timeout: 30_000 });+ }+ const themes = await page.evaluate(() => Object.entries(window.LDR_THEME_METADATA)+ .filter(([, metadata]) => metadata.type === 'light')+ .map(([id]) => id));+ expect(themes).toContain('sepia');+ expect(themes.length).toBeGreaterThan(1);+ for (const theme of themes) {+ await test.step(theme, async () => {+ await applyTheme(page, theme);+ await assertContrast(page);+ });+ }+ });+ }++ test('collection cards have resolved text contrast in every light theme', async ({ page, isMobile }) => {+ test.setTimeout(120_000);+ await loadCollectionFixtures(page);+ const themes = await page.evaluate(() => Object.entries(window.LDR_THEME_METADATA)+ .filter(([, metadata]) => metadata.type === 'light').map(([id]) => id));+ for (const theme of themes) {+ await test.step(theme, async () => {+ await applyTheme(page, theme);+ // Gradients and overlays previously caused axe to mark every+ // card as incomplete, silently passing the violations-only scan.+ await assertContrast(page, '.ldr-collection-card-wrapper', { requireResolved: true });+ if (!isMobile) {+ await page.locator('.ldr-collection-view-link').first().hover();+ await page.waitForTimeout(400);+ await assertContrast(page, '.ldr-collection-card-wrapper', { requireResolved: true });+ await page.mouse.move(0, 0);+ }+ });+ }+ });++ test('light themes keep the note editor controls visible and usable', async ({ page, isMobile }) => {+ test.setTimeout(120_000);+ await page.goto('/notes/');+ await page.waitForFunction(() => window.themeService);+ await page.locator('[data-action="create-new-note"]').first().click();+ const modal = page.locator('#noteModal');+ const close = modal.getByRole('button', { name: 'Close', exact: true });+ await expect(modal).toBeVisible();+ const themes = await page.evaluate(() => Object.entries(window.LDR_THEME_METADATA)+ .filter(([, metadata]) => metadata.type === 'light').map(([id]) => id));+ for (const theme of themes) {+ await test.step(theme, async () => {+ await applyTheme(page, theme);+ await assertContrast(page, '#noteModal');+ await assertControlContrast(modal.locator('#note-title'));+ await assertControlContrast(modal.locator('.ldr-markdown-editor-container'));+ const resting = await assertControlContrast(close, '::before');+ // Computed colors ignore CSS filters, so the contrast+ // check cannot see an invert() turning the X white (the+ // original bug). Require that nothing filters it.+ await expect(close).toHaveCSS('filter', 'none');+ if (!isMobile) {+ // Bootstrap's .btn-close:hover re-applies its own icon+ // color and a lower opacity; the icon must keep its ink.+ await close.hover();+ await page.waitForTimeout(400);+ const hovered = await assertControlContrast(close, '::before');+ expect(hovered.color, 'close icon keeps its color on hover').toBe(resting.color);+ await expect(close).toHaveCSS('opacity', '1');+ await expect(close).toHaveCSS('filter', 'none');+ await page.mouse.move(0, 0);+ }+ });+ }+ // Confirm the visible close control remains keyboard operable.+ await close.focus();+ await close.press('Enter');+ await expect(modal).toBeHidden();+ });++ test('sepia keeps focused links, hovered buttons and privacy scopes readable', async ({ page }) => {+ // Exercise the real UI cues without changing a shared test account's policy.+ // Persistence is outside this visual contrast test.+ await page.route('**/settings/api/policy.egress_scope', async route => {+ if (route.request().method() === 'PUT') {+ await route.fulfill({ json: { status: 'success' } });+ } else {+ await route.continue();+ }+ });+ await page.goto('/');+ await page.waitForFunction(() => window.themeService);+ await applyTheme(page, 'sepia');+ const skipLink = page.locator('.ldr-skip-link');+ await skipLink.focus();+ await expect(skipLink).toBeInViewport();+ await assertContrast(page, '.ldr-skip-link');++ await page.locator('#query').fill('Theme readability check');+ await page.locator('#start-research-btn').hover();+ await page.waitForTimeout(400);+ await assertContrast(page, '#start-research-btn');+ await page.mouse.move(0, 0);++ const scopes = await page.locator('#policy_egress_scope option').evaluateAll(options => options.map(option => option.value));+ expect(scopes).toEqual(expect.arrayContaining(['adaptive', 'public_only', 'private_only', 'strict']));+ for (const scope of scopes) {+ await page.locator('#policy_egress_scope').selectOption(scope);+ await expect(page.locator('.ldr-privacy-panel')).toHaveAttribute('data-scope', scope);+ await page.waitForTimeout(400);+ await assertContrast(page, '.ldr-privacy-panel');+ }+ });+ });+}diff --git a/tests/accessibility_tests/wcag-compliance.spec.js b/tests/accessibility_tests/wcag-compliance.spec.jsindex ca0ec166c9..82c8eacb58 100644--- a/tests/accessibility_tests/wcag-compliance.spec.js+++ b/tests/accessibility_tests/wcag-compliance.spec.js@@ -10,11 +10,6 @@ import { createAxeBuilder, getCriticalViolations, formatViolations } from './axeconst BASE_URL = process.env.BASE_URL || 'http://localhost:5000';const TEST_TIMEOUT = 30000;-// Color-contrast is excluded because several selectable themes (e.g. sepia)-// have text colors that don't meet WCAG AA 4.5:1 contrast ratios.-// This is a systemic theme design issue tracked separately.-const AXE_DISABLE_RULES = ['color-contrast'];-test.use({baseURL: BASE_URL,trace: 'on-first-retry',@@ -33,7 +28,7 @@ test.describe('WCAG Compliance Tests', () => {});test('should have no critical WCAG violations on research page', async ({ page }) => {- const results = await createAxeBuilder(page, { disableRules: AXE_DISABLE_RULES }).analyze();+ const results = await createAxeBuilder(page).analyze();const criticalViolations = getCriticalViolations(results.violations);@@ -144,7 +139,7 @@ test.describe('WCAG Compliance Tests', () => {});test('should have no critical WCAG violations on settings page', async ({ page }) => {- const results = await createAxeBuilder(page, { disableRules: AXE_DISABLE_RULES }).analyze();+ const results = await createAxeBuilder(page).analyze();const criticalViolations = getCriticalViolations(results.violations);if (criticalViolations.length > 0) {@@ -177,7 +172,7 @@ test.describe('WCAG Compliance Tests', () => {});test('should have no critical WCAG violations on history page', async ({ page }) => {- const results = await createAxeBuilder(page, { disableRules: AXE_DISABLE_RULES }).analyze();+ const results = await createAxeBuilder(page).analyze();const criticalViolations = getCriticalViolations(results.violations);if (criticalViolations.length > 0) {@@ -371,7 +366,7 @@ test.describe('Full Page Accessibility Scan', () => {test(`${pageInfo.name} page should pass WCAG 2.1 AA`, async ({ page }) => {await page.goto(pageInfo.path, { waitUntil: 'domcontentloaded' });- const results = await createAxeBuilder(page, { disableRules: AXE_DISABLE_RULES }).analyze();+ const results = await createAxeBuilder(page).analyze();const criticalViolations = getCriticalViolations(results.violations);diff --git a/tests/theme_tests/test_accent_ink_contrast.py b/tests/theme_tests/test_accent_ink_contrast.pynew file mode 100644index 0000000000..a833af333e--- /dev/null+++ b/tests/theme_tests/test_accent_ink_contrast.py@@ -0,0 +1,3357 @@+# allow: no-sut-import — guardian; statically parses the shipped theme and+# component CSS rather than exercising Python production code+"""Labels on filled accent controls must be readable in every theme.++Outline buttons (hover, keyboard focus and active, since Bootstrap's+``.btn:focus-visible`` reuses the hover colors), the skip link, primary+buttons, the selected settings tab, active filters and accent badges draw+``var(--text-on-accent)`` on ``var(--accent-primary)`` and/or+``var(--accent-secondary)`` (``test_accent_fills_use_accent_ink`` sweeps+every stylesheet, template ``<style>`` block and inline ``style``+attribute in templates and scripts; ``test_filled_anchors_keep_readable_ink``+replays the cascade for every filled control class on a link -- accent,+status and other colour fills). White is too faint on every+shipped dark accent, so each theme sets the token next to its accent; the+styles.css ``:root`` palette (used alone by the login pages) keeps white on+its own accent.+"""++import functools+import hashlib+import re+from pathlib import Path++import pytest++WEB_ROOT = (+ Path(__file__).resolve().parents[2] / "src" / "local_deep_research" / "web"+)+CSS_ROOT = WEB_ROOT / "static" / "css"+THEME_FILES = sorted((WEB_ROOT / "themes").rglob("*.css"))++# Generated (git-ignored) sheets under ``static/css`` that the page-sheet+# scan must skip. ``themes.css`` is the concatenation of ``themes/*/*.css``+# that the FastAPI lifespan (``web/fastapi_app.py``, via+# ``theme_registry.get_combined_css()``) writes on every boot, so it exists+# only after the app (or a test that boots it) has started -- e.g. in the+# CI pytest run, never in a clean checkout. Read as a plain page sheet, its+# ``[data-theme="x"]`` rules lose their scope and get judged against every+# other palette. The theme sources themselves are checked via THEME_FILES.+# test_generated_sheet_exclusions_are_generated keeps this list honest.+GENERATED_SHEETS = {"themes.css"}++ACCENT_INK = "var(--text-on-accent)"+++def _strip_comments(css):+ return re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)+++def _custom_properties(css):+ """``{token: value}`` for every ``--token: value`` declaration, the value+ kept as written. Nothing is dropped here: ``_resolve`` reads the value+ when a check needs the token as a colour, and fails on one it cannot+ read, so an unreadable theme value never falls back to the ``:root``+ default."""+ return {+ name: " ".join(value.split())+ for name, value in re.findall(+ r"(?:^|[{;])\s*--([\w-]+)\s*:\s*([^;{}]*?)\s*(?=[;}])",+ _strip_comments(css),+ flags=re.MULTILINE,+ )+ }+++_HEX = re.compile(r"#([\da-fA-F]{3,4}|[\da-fA-F]{6}|[\da-fA-F]{8})")+_NUMBER = r"\s*([\d.]+)(%?)\s*"+_RGB_LITERAL = re.compile(+ rf"rgba?\({_NUMBER},{_NUMBER},{_NUMBER}(?:,{_NUMBER})?\)"+ r"|rgba?\(\s*([\d.]+)(%?)\s+([\d.]+)(%?)\s+([\d.]+)(%?)\s*"+ r"(?:/\s*([\d.]+)(%?)\s*)?\)",+ re.IGNORECASE,+)+_KEYWORDS = {+ "white": ((255, 255, 255), 1.0),+ "black": ((0, 0, 0), 1.0),+ "transparent": ((0, 0, 0), 0.0),+}+++def _parse_color(value):+ """``(rgb, alpha)`` for a literal colour the checks read: 3/4/6/8-digit+ hex, ``rgb()``/``rgba()`` with literal numbers (comma or space+ syntax), ``white``, ``black`` and ``transparent``; None for anything+ else (``hsl()``, a named colour, ``var()``, ``color-mix()``...)."""+ value = value.strip()+ hex_match = _HEX.fullmatch(value)+ if hex_match:+ digits = hex_match.group(1)+ if len(digits) <= 4:+ digits = "".join(c * 2 for c in digits)+ channels = [+ int(digits[i : i + 2], 16) for i in range(0, len(digits), 2)+ ]+ alpha = channels[3] / 255 if len(channels) == 4 else 1.0+ return tuple(channels[:3]), alpha+ if value.lower() in _KEYWORDS:+ return _KEYWORDS[value.lower()]+ rgb_match = _RGB_LITERAL.fullmatch(value)+ if rgb_match:+ groups = [g for g in rgb_match.groups()]+ groups = groups[:8] if groups[0] is not None else groups[8:]+ channels = []+ for number, percent in zip(groups[0:6:2], groups[1:6:2]):+ channel = float(number) * 2.55 if percent else float(number)+ if channel > 255:+ return None+ channels.append(channel)+ alpha = 1.0+ if groups[6] is not None:+ alpha = float(groups[6]) / (100 if groups[7] else 1)+ if alpha > 1:+ return None+ return tuple(channels), alpha+ return None+++def _root_defaults():+ css = _strip_comments((CSS_ROOT / "styles.css").read_text(encoding="utf-8"))+ match = re.search(r"(?:^|\})\s*:root\s*\{([^{}]*)\}", css)+ assert match, "styles.css has no :root block"+ return _custom_properties(match.group(1))+++def _resolve(token, props, seen=()):+ """The opaque colour ``--token`` draws under ``props``, following+ ``var()`` references. Fails (AssertionError) when the token is+ undefined, a ``var()`` cycle, translucent, or a value ``_parse_color``+ does not read."""+ value = props.get(token)+ assert value is not None, f"--{token} is not defined"+ ref = re.fullmatch(r"var\(\s*--([\w-]+)\s*(?:,.*)?\)", value)+ if ref:+ assert ref.group(1) not in seen, f"--{token} is a var() cycle"+ return _resolve(ref.group(1), props, (*seen, token))+ parsed = _parse_color(value)+ assert parsed is not None, f"--{token}: {value!r} is not a colour read here"+ rgb, alpha = parsed+ assert alpha == 1, f"--{token}: {value!r} is translucent"+ return rgb+++def _luminance(rgb):+ linear = [+ c / 12.92 if c <= 0.04045 else ((c + 0.055) / 1.055) ** 2.4+ for c in (channel / 255 for channel in rgb)+ ]+ return 0.2126 * linear[0] + 0.7152 * linear[1] + 0.0722 * linear[2]+++def _contrast(a, b):+ dark, light = sorted((_luminance(a), _luminance(b)))+ return (light + 0.05) / (dark + 0.05)+++def test_all_themes_are_discovered():+ """An empty glob would make the parametrized check skip, not fail."""+ stems = {path.stem for path in THEME_FILES}+ assert {"hashed", "high-contrast", "sepia", "vesper"} <= stems+ assert len(THEME_FILES) >= 30+++def test_generated_sheet_exclusions_are_generated():+ """Every sheet the scan skips must be a git-ignored build output with a+ named generator, so the exclusion can't silently hide a hand-written+ sheet."""+ ignored = {+ line.strip()+ for line in (REPO_ROOT / ".gitignore")+ .read_text(encoding="utf-8")+ .splitlines()+ }+ generator = (WEB_ROOT / "fastapi_app.py").read_text(encoding="utf-8")+ for rel in GENERATED_SHEETS:+ assert f"src/local_deep_research/web/static/css/{rel}" in ignored, (+ f"{rel} is excluded from the scan but not git-ignored"+ )+ assert f'"css" / "{rel}"' in generator, (+ f"{rel} is excluded from the scan but fastapi_app.py no "+ "longer writes it"+ )+ assert "theme_registry.get_combined_css()" in generator++[email protected]("path", THEME_FILES, ids=lambda path: path.stem)[email protected]("fill", ["accent-primary", "accent-secondary"])+def test_accent_ink_contrast(path, fill):+ props = _root_defaults()+ props.update(_custom_properties(path.read_text(encoding="utf-8")))+ ink = _resolve("text-on-accent", props)+ background = _resolve(fill, props)+ ratio = _contrast(ink, background)+ assert ratio >= 4.5, (+ f"{path.stem}: --text-on-accent on --{fill} is {ratio:.2f}:1"+ )+++def test_root_palette_accent_ink_contrast():+ """Pages that load styles.css without themes.css (login, register), or+ after it (change password), draw the :root pair together.++ Known gap, not asserted (pre-existing): white on the :root+ --accent-secondary (#9179f0, the .btn-primary:hover fill) is 3.39:1.+ """+ props = _root_defaults()+ ink = _resolve("text-on-accent", props)+ ratio = _contrast(ink, _resolve("accent-primary", props))+ assert ratio >= 4.5, (+ f":root --text-on-accent on --accent-primary {ratio:.2f}:1"+ )++[email protected]("path", THEME_FILES, ids=lambda path: path.stem)+def test_theme_sets_accent_ink_beside_its_accent(path):+ """Inheriting the :root ink would pair it with this theme's accent, which+ the :root value was never chosen for."""+ props = _custom_properties(path.read_text(encoding="utf-8"))+ assert "text-on-accent" in props, f"{path.stem} must set --text-on-accent"+++def _rules(filename):+ return _parse_rules((CSS_ROOT / filename).read_text(encoding="utf-8"))+++def _parse_rules(css):+ css = _strip_comments(css)+ for match in re.finditer(r"([^{}]*)\{([^{}]*)\}", css):+ decls = {}+ for decl in match.group(2).split(";"):+ name, sep, value = decl.partition(":")+ if sep:+ decls[name.strip().lower()] = " ".join(value.split())+ yield " ".join(match.group(1).split()), decls+++def test_outline_primary_hover_focus_active_use_accent_ink():+ """Bootstrap's .btn:focus-visible reuses the hover pair, so this covers+ keyboard focus as well as hover and active."""+ rules = [d for s, d in _rules("styles.css") if s == ".btn-outline-primary"]+ assert rules, "styles.css no longer styles .btn-outline-primary"+ decls = rules[-1]+ for state in ("hover", "active"):+ assert decls.get(f"--bs-btn-{state}-bg") == "var(--accent-primary)"+ assert decls.get(f"--bs-btn-{state}-color") == ACCENT_INK+++def test_accent_ink_only_sits_on_accent_fills():+ """The palette check above only holds where the ink is drawn on an accent+ fill; a rule pairing it with another background needs its own token."""+ offenders = []+ for name, rules in _sheets():+ for selector, decls in rules:+ if decls.get("color") != ACCENT_INK:+ continue+ background = decls.get("background-color", decls.get("background"))+ if background is not None and not _is_accent_fill(background):+ offenders.append(f"{name} {selector}: {background}")+ assert not offenders, offenders+++# A fill counts as an accent fill when every colour stop in it is the+# primary or secondary accent: the two fills the contrast check above+# covers. Gradients mixing in --accent-tertiary or a literal colour are not+# covered by that check, so they are out of scope here.+_COLOR_STOP = re.compile(+ r"var\(--[\w-]+\)|rgba?\([^()]*(?:\([^()]*\)[^()]*)*\)"+ r"|#[\da-fA-F]{3,8}\b|\b(?:white|black|transparent)\b"+)+# ``var(--accent-primary, #6e4ff6)`` draws the token whenever it is defined,+# so a fallback is dropped before the stops and the ink are compared.+_VAR_FALLBACK = re.compile(+ r"var\(\s*(--[\w-]+)\s*,[^()]*(?:\([^()]*\)[^()]*)*\)"+)+++def _drop_fallbacks(value):+ return _VAR_FALLBACK.sub(r"var(\1)", value)+++_RGB_STOP = re.compile(r"rgba?\(\s*var\(--([\w-]+)\)\s*(?:,\s*([\d.]+)\s*)?\)")+_VAR_STOP = re.compile(r"var\(--([\w-]+)\)")+_ACCENT_TOKENS = frozenset({"accent-primary", "accent-secondary"})+_ACCENT_RGB_TOKENS = frozenset({"accent-primary-rgb", "accent-secondary-rgb"})+# The last class or pseudo-class of a compound selector: ``.a.b:hover``+# inherits its fill or ink from ``.a.b`` and then ``.a``.+_LAST_SIMPLE = re.compile(r"(\.[\w-]+|:[\w-]+(\([^()]*\))?)$")+_PSEUDO_ELEMENT = re.compile(r"::?(?:before|after)$")++# Rules on an accent fill that keep another ink because no template, script+# or Python module emits their class or id (checked with git grep, including+# template-literal class names); fix them if they are ever used again.+DEAD_ACCENT_RULES = {+ # document_text.html's .ldr-text-actions only holds .ldr-btn-secondary.+ ("document_details.css", ".ldr-text-actions .ldr-btn-primary"),+ ("document_details.css", ".ldr-text-actions .ldr-btn-primary:hover"),+ # Only link_analytics.html has a modal header, and it does not load+ # collections.css.+ ("collections.css", ".ldr-modal-header"),+ ("link_analytics.css", ".ldr-domain-count"),+ # No template or script renders the mobile sheet's badge.+ ("mobile-navigation.css", ".ldr-mobile-sheet-badge"),+ ("news.css", ".ldr-filter-chip.active"),+ ("styles.css", ".ldr-notification-group .btn-sm:hover"),+ ("styles.css", ".ldr-settings-card .btn:hover"),+ ("styles.css", ".ldr-sidebar-nav li.active .ldr-nav-shortcut"),+ ("styles.css", ".ldr-sidebar-nav li a:focus .ldr-nav-shortcut"),+ ("styles.css", ".ldr-sidebar-nav li:hover .ldr-nav-shortcut"),+ ("styles.css", "#try-again-btn"),+ ("styles.css", "#try-again-btn:hover"),+ ("settings.css", ".ldr-editor-lang"),+}+++def _custom_property_definitions():+ """Every custom-property definition in shipped CSS (stylesheets, theme+ files and template ``<style>`` blocks), whatever its selector:+ ``{token: [(file, selector, value), ...]}``."""+ definitions = {}+ for name, css in _css_sources():+ for selector, decls in _parse_rules(css):+ for prop, value in decls.items():+ if prop.startswith("--"):+ definitions.setdefault(prop[2:], []).append(+ (name, selector, value)+ )+ return definitions+++def _css_sources():+ yield from _stylesheets()+ for path in THEME_FILES:+ yield path.name, path.read_text(encoding="utf-8")+++def _stops_are_accent(value, accent, accent_rgb):+ stops = _COLOR_STOP.findall(+ _drop_fallbacks(value.replace("!important", ""))+ )+ if not stops:+ return False+ for stop in stops:+ rgb = _RGB_STOP.fullmatch(stop)+ if rgb:+ if rgb.group(1) not in accent_rgb:+ return False+ if rgb.group(2) is not None and float(rgb.group(2)) != 1:+ return False+ continue+ token = _VAR_STOP.fullmatch(stop)+ if not token or token.group(1) not in accent:+ return False+ return True+++def _accent_aliases():+ """Tokens that draw the primary or secondary accent, followed through+ ``--x: var(--accent-primary)`` aliases (``--primary-color``,+ ``--news-gradient-1``) and their ``-rgb`` twins, transitively.++ A token counts when any of its definitions resolves to the accent, so a+ per-theme override with a literal colour (``--mobile-nav-active``) still+ makes its fills accent fills: conservative, since the theme where it+ resolves to the accent needs the accent ink. Returns+ ``(accent, accent_rgb, mixed)``; ``mixed`` maps the tokens whose other+ definitions do not resolve to the accent to those definitions."""+ definitions = _custom_property_definitions()+ accent, accent_rgb = set(_ACCENT_TOKENS), set(_ACCENT_RGB_TOKENS)+ changed = True+ while changed:+ changed = False+ for token, values in definitions.items():+ if token in accent or token in accent_rgb:+ continue+ for _, _, value in values:+ plain = _drop_fallbacks(value.replace("!important", "")).strip()+ ref = _VAR_STOP.fullmatch(plain)+ if ref and ref.group(1) in accent_rgb:+ accent_rgb.add(token)+ elif _stops_are_accent(value, accent, accent_rgb):+ accent.add(token)+ else:+ continue+ changed = True+ break+ mixed = {}+ for token in (accent | accent_rgb) - _ACCENT_TOKENS - _ACCENT_RGB_TOKENS:+ for name, selector, value in definitions[token]:+ plain = _drop_fallbacks(value.replace("!important", "")).strip()+ ref = _VAR_STOP.fullmatch(plain)+ if not (+ _stops_are_accent(value, accent, accent_rgb)+ or (ref and ref.group(1) in accent_rgb)+ ):+ mixed.setdefault(token, []).append((name, selector, value))+ return accent, accent_rgb, mixed+++def _aliases():+ return _accent_aliases()+++def _is_accent_fill(background):+ accent, accent_rgb, _ = _aliases()+ return _stops_are_accent(background, accent, accent_rgb)+++# Raw-text scan, independent of the rule parser the sweep uses.+_ALIAS_DEFINITION = re.compile(+ r"--([\w-]+)\s*:\s*var\(\s*--accent-(?:primary|secondary)(-rgb)?\s*[,)]"+)+++def test_accent_aliases_are_recognised():+ """Every ``--x: var(--accent-primary|secondary...)`` definition in+ shipped CSS, under any selector, names a token the fill sweep treats+ as the accent, so a rule filled with ``var(--primary-color)`` or+ ``var(--news-gradient-1)`` is held to the accent ink like one filled+ with ``var(--accent-primary)``."""+ accent, accent_rgb, _ = _aliases()+ assert {"primary-color", "news-gradient-1", "mobile-nav-active"} <= accent+ assert "primary-color-rgb" in accent_rgb+ missed, found = [], 0+ for name, css in _css_sources():+ for match in _ALIAS_DEFINITION.finditer(_strip_comments(css)):+ found += 1+ pool = accent_rgb if match.group(2) else accent+ if match.group(1) not in pool:+ missed.append(f"{name}: {match.group(0)}")+ assert found >= 33, "alias scan found too few definitions"+ assert not missed, missed+++# Aliases that resolve to the accent in one scope and to another colour in+# another. Their fills are still held to the accent ink (conservative); a+# new entry needs a check that the ink also reads on the other colour.+MIXED_ACCENT_ALIASES = {+ # Literal per-theme colours in mobile-navigation.css; its only text fill+ # (.ldr-mobile-sheet-badge) is dead, the others are stripes and ripples.+ "mobile-nav-active": "per-theme literal in mobile-navigation.css",+ "mobile-nav-text-active": "per-theme literal; used as a text colour",+ # Bootstrap button variables, set per button variant; no shipped rule+ # fills with them directly.+ "bs-btn-active-bg": "Bootstrap variant variable",+ "bs-btn-active-border-color": "Bootstrap variant variable",+ "bs-btn-border-color": "Bootstrap variant variable",+ "bs-btn-color": "Bootstrap variant variable",+ "bs-btn-hover-bg": "Bootstrap variant variable",+ "bs-btn-hover-border-color": "Bootstrap variant variable",+}+++def test_mixed_accent_aliases_are_reviewed():+ """A token defined as the accent in one place and as something else+ elsewhere is treated as an accent fill everywhere; listing it makes a+ new one visible for review."""+ _, _, mixed = _aliases()+ assert set(mixed) == set(MIXED_ACCENT_ALIASES), {+ token: mixed.get(token)+ for token in set(mixed) ^ set(MIXED_ACCENT_ALIASES)+ }+++def _compound_chain(selector):+ chain = [selector]+ while True:+ match = _LAST_SIMPLE.search(selector)+ if not match or match.start() == 0:+ return chain+ if selector[match.start() - 1] in " >+~":+ return chain+ selector = selector[: match.start()]+ chain.append(selector)+++def _selector_chain(selector):+ """``.a .b.c:hover`` -> itself, ``.a .b.c``, ``.a .b``, then the subject+ compound alone (``.b.c:hover``, ``.b.c``, ``.b``): a rule on the subject+ alone matches the same element."""+ chain = _compound_chain(selector)+ subject = re.split(r"\s*[ >+~]\s*", selector)[-1]+ if subject != selector:+ chain += [s for s in _compound_chain(subject) if s not in chain]+ return chain+++def _stylesheets():+ for path in sorted(CSS_ROOT.rglob("*.css")):+ if path.relative_to(CSS_ROOT).as_posix() in GENERATED_SHEETS:+ continue+ yield path.name, path.read_text(encoding="utf-8")+ for name, path in _markup_files():+ if path.suffix != ".html":+ continue+ html = path.read_text(encoding="utf-8")+ for css in re.findall(r"<style[^>]*>(.*?)</style>", html, flags=re.S):+ yield name, css+++# --- Inline styles ---------------------------------------------------------+#+# Inline styles are read from the templates (``templates/`` and the HTML+# fragments script fetches from ``static/templates/``) and the scripts+# (``static/js/``):+# - ``style=`` attributes in any case (``STYLE=``), quoted with ``"``,+# ``'``, a backtick or, inside a script string, an escaped ``\"`` or+# ``\'``, or unquoted, and ``el.style = ...`` assignments;+# - ``el.style.cssText = ...`` (and ``+=``) and+# ``el.setAttribute('style', ...)`` writes.+# A ``style =`` right after a standalone ``const``, ``let`` or ``var``+# whose right-hand side is a call declares a script variable and is+# skipped. A style whose value is all literal text becomes+# a pseudo-rule ``style@L<line>`` of its file. The scanner does not+# interpret script: every ``${...}`` expression and server-side template+# tag in a style's value -- in any property, since an expression can also+# add declarations (``width: ${w}`` with ``w = '1px; background: red'``)+# -- fails ``test_dynamic_inline_styles_are_allowlisted`` unless its exact+# (file, line, property) is listed in DYNAMIC_INLINE_STYLES with the same+# expression text. The values listed there, read off the source by a+# reviewer, replace the expression: one pseudo-rule ``style@L<line>#<n>``+# per combination, checked like any other rule. A style the scanner+# cannot read as ``property: value`` declarations fails with no+# allowlist: an attribute that is itself an expression (``style=${st}``,+# ``style="${st}"``); an expression or tag in a property name or in a part+# with no ``:``; a quote, backtick, backslash or brace left in a value+# once its expressions, a ``font-family`` list of plain quoted names+# (``'Courier New'``) and plain ``url()``s are set aside, so a string+# concatenation such as ``'style="color: ' + c + '"'`` fails; a write whose right-hand side is+# not a single string literal; and a quote, expression or tag that does+# not close. At a site it finds, the scanner fails rather than skipping+# what it cannot read. Sites spelled other ways are not found: styles set+# one property at a time (``el.style.color = ...``,+# ``style.setProperty(...)``, ``Object.assign(el.style, ...)``),+# ``el['style']``, an attribute name built by script, and ``<style>`` text+# built in script.+_MAX_VARIANTS = 64+# A server-side template tag, which renders before the browser parses the+# attribute.+_JINJA = re.compile(r"\{\{.*?\}\}|\{%.*?%\}|\{#.*?#\}", re.S)+# An attribute named ``style`` (not ``data-style``, not ``el.style``).+_STYLE_ATTR = re.compile(r"(?<![\w$.-])style\s*=(?![=>])\s*", re.I)+# A write to an element's whole inline style.+_STYLE_WRITE = re.compile(+ r"\.style\s*=(?![=>])\s*"+ r"|\.style\.cssText\s*\+?=\s*"+ r"|\.setAttribute\(\s*(['\"`])style\1\s*,\s*",+ re.I,+)+# ``const style = getComputedStyle(...)``: a script variable set from a+# call. The keyword must stand alone (not ``data-var``), and a string+# right-hand side is read like any other style.+_VARIABLE_DECLARATION = re.compile(r"(?<![\w$.-])(?:const|let|var)\s+$")+_CALL = re.compile(r"[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)*\s*\(")+_UNQUOTED = re.compile(r"[^\s>]+")+_PROPERTY_NAME = re.compile(r"\s*-*[A-Za-z][\w-]*\s*")+_STRAY = re.compile(r"['\"`\\{}]|\$\{")+# Quotes in a value are read in two shapes only, so script glue between+# string pieces (``', c, '`` in ``['<i style="background:', c,+# '">'].join('')``) is never taken for CSS: a ``url()`` whose quoted+# argument holds no quote, comma, space, ``$``, ``+``, brace, backslash or+# backtick, and a ``font-family`` list of quoted plain names+# (``'Courier New'``) followed by bare names (``monospace``). Any other+# quote leaves the style unread.+_CSS_URL = re.compile(+ r"url\(\s*(?:'[^'\"`\\$+{}, ]*'|\"[^'\"`\\$+{}, ]*\"|[^'\"`\\$+{}()\s]*)\s*\)"+)+_FONT_NAME = r"(?:'[\w-]+(?: [\w-]+)*'|\"[\w-]+(?: [\w-]+)*\")"+_BARE_NAME = r"-?[A-Za-z_][\w-]*"+_FONT_FAMILY = re.compile(+ rf"\s*(?:{_FONT_NAME}(?:\s*,\s*{_FONT_NAME})*(?:\s*,\s*{_BARE_NAME})*"+ rf"|{_BARE_NAME}(?:\s*,\s*{_BARE_NAME})*)\s*"+)+# A value DYNAMIC_INLINE_STYLES may give for an expression that always+# yields a number (``width: ${pct}%``); read as ``0``, and never allowed in+# a property that takes a colour.+NUMBER = "<number>"+_COLOUR_PROPERTY = re.compile(+ r"color|background|border|outline|shadow|fill|stroke"+)+++def _skip_string(text, start):+ """The index after the JavaScript string literal opening at+ ``text[start]`` (``'``, ``"`` or a template literal, whose ``${...}``+ are skipped), or None when it does not close."""+ quote, index = text[start], start + 1+ while index < len(text):+ char = text[index]+ if char == "\\":+ index += 2+ continue+ if char == quote:+ return index + 1+ if quote == "`" and text.startswith("${", index):+ index = _skip_expression(text, index)+ if index is None:+ return None+ continue+ if char == "\n" and quote != "`":+ return None+ index += 1+ return None+++def _skip_expression(text, start):+ """The index after the ``${...}`` opening at ``text[start]``, counting+ nested braces and skipping string and template literals, or None when+ it does not close. Only used to find where an expression ends; what+ the expression evaluates to is never read."""+ depth, index = 1, start + 2+ while index < len(text):+ char = text[index]+ if char in "'\"`":+ index = _skip_string(text, index)+ if index is None:+ return None+ continue+ if char == "{":+ depth += 1+ elif char == "}":+ depth -= 1+ if depth == 0:+ return index + 1+ index += 1+ return None+++def _read_attribute(text, start):+ """``(offset, value)`` of the quoted attribute value opening at+ ``text[start]`` (``${...}`` expressions and template tags inside it+ skipped whole, whatever quotes they hold), or None when it does not+ close."""+ close = text[start : start + 2] if text[start] == "\\" else text[start]+ index = begin = start + len(close)+ while index < len(text):+ if text.startswith("${", index):+ index = _skip_expression(text, index)+ if index is None:+ return None+ continue+ tag = _JINJA.match(text, index)+ if tag:+ index = tag.end()+ continue+ if text.startswith(close, index):+ return begin, text[begin:index]+ index += 1+ return None+++def _read_write(text, start):+ """``(offset, value)`` of a style write's right-hand side when it is a+ single string literal (a template literal's ``${...}`` kept in the+ value), followed by ``;``, ``,``, ``)``, ``}`` or the end of the file;+ None for anything else (a variable, a call, a concatenation)."""+ if start >= len(text) or text[start] not in "'\"`":+ return None+ end = _skip_string(text, start)+ if end is None or not re.match(r"\s*(?:[;,)}]|$)", text[end:]):+ return None+ return start + 1, text[start + 1 : end - 1]+++def _style_sites(text):+ """``(offset, read)`` for each inline style in ``text`` (see the comment+ above): ``read`` is ``(value offset, raw value)``, or None when the+ style cannot be read."""+ for match in _STYLE_ATTR.finditer(text):+ if _VARIABLE_DECLARATION.search(+ text[max(0, match.start() - 12) : match.start()]+ ) and _CALL.match(text, match.end()):+ continue+ start = match.end()+ if text.startswith(("${", "{{", "{%"), start):+ yield match.start(), None+ elif text.startswith(('"', "'", "`", '\\"', "\\'"), start):+ yield match.start(), _read_attribute(text, start)+ else:+ bare = _UNQUOTED.match(text, start)+ yield match.start(), bare and (start, bare.group())+ for match in _STYLE_WRITE.finditer(text):+ yield match.start(), _read_write(text, match.end())+++def _expression_spans(value):+ """``[(start, end, source)]`` for each ``${...}`` and template tag in+ ``value`` (``source`` with its whitespace collapsed), or None when an+ expression does not close."""+ found, index = [], 0+ while index < len(value):+ if value.startswith("${", index):+ end = _skip_expression(value, index)+ if end is None:+ return None+ found.append(+ (index, end, " ".join(value[index + 2 : end - 1].split()))+ )+ index = end+ continue+ tag = _JINJA.match(value, index)+ if tag:+ found.append((index, tag.end(), " ".join(tag.group().split())))+ index = tag.end()+ continue+ index += 1+ return found+++def _split_style(value):+ """``[(offset, part)]``: ``value`` split on the ``;`` outside+ expressions, template tags and parentheses, or None when an expression+ does not close."""+ parts, depth, index, begin = [], 0, 0, 0+ while index < len(value):+ if value.startswith("${", index):+ index = _skip_expression(value, index)+ if index is None:+ return None+ continue+ tag = _JINJA.match(value, index)+ if tag:+ index = tag.end()+ continue+ char = value[index]+ depth += char == "("+ depth -= char == ")"+ if char == ";" and depth == 0:+ parts.append((begin, value[begin:index]))+ begin = index + 1+ index += 1+ parts.append((begin, value[begin:]))+ return parts+++def _style_declarations(text, offset, value):+ """``[(property, value, spans)]`` for an inline style's raw ``value``+ starting at ``text[offset]``, or None when it cannot be read (see the+ comment above). ``spans`` holds ``(start, end, source, line)`` for each+ expression or template tag in the declaration's value."""+ parts = _split_style(value)+ if parts is None:+ return None+ decls = []+ for begin, part in parts:+ if not part.strip():+ continue+ name, sep, rest = part.partition(":")+ if not sep or not _PROPERTY_NAME.fullmatch(name):+ return None+ spans = _expression_spans(rest)+ if spans is None:+ return None+ literal = rest+ for start, end, _ in reversed(spans):+ literal = literal[:start] + " " + literal[end:]+ plain = _CSS_URL.sub(" ", literal)+ if name.strip().lower() == "font-family" and _FONT_FAMILY.fullmatch(+ plain+ ):+ plain = ""+ if _STRAY.search(plain):+ return None+ base = offset + begin + len(name) + 1+ decls.append(+ (+ name.strip().lower(),+ rest,+ [+ (start, end, source, text.count("\n", 0, base + start) + 1)+ for start, end, source in spans+ ],+ )+ )+ return decls+++def _merge_gradient(decls):+ """A gradient ``background-image`` paints over the background colour:+ both are the fill, read as ``background-color``."""+ image = decls.get("background-image")+ if image and _COLOR_STOP.search(re.sub(r"url\([^()]*\)", " ", image)):+ under = decls.get("background-color", decls.get("background"))+ decls["background-color"] = f"{image} {under or ''}".strip()+ return decls+++def _style_variants(name, decls, allowlist):+ """The declaration sets an inline style's listed expressions can+ produce, or None when one of its expressions is not listed with that+ exact text (``test_dynamic_inline_styles_are_allowlisted`` reports it)+ or the combinations exceed _MAX_VARIANTS (reported as unread). Each+ listed (file, line, property) is one axis; listed entries sharing a+ pair label are taken value by value."""+ axes, seen = {}, set()+ for prop, _, spans in decls:+ for _, _, source, line in spans:+ key = (name, line, prop)+ entry = allowlist.get(key)+ if entry is None or entry[0] != source:+ return None+ if key not in seen:+ seen.add(key)+ axes.setdefault(entry[2] or key, []).append(key)+ combos = [{}]+ for keys in axes.values():+ widths = {len(allowlist[key][1]) for key in keys}+ if len(widths) != 1:+ return None+ width = widths.pop()+ combos = [+ {**combo, **{key: allowlist[key][1][i] for key in keys}}+ for combo in combos+ for i in range(width)+ ]+ if len(combos) > _MAX_VARIANTS:+ return []+ variants = []+ for combo in combos:+ variant = {}+ for prop, rest, spans in decls:+ value = rest+ for start, end, _, line in reversed(spans):+ chosen = combo[(name, line, prop)]+ value = (+ value[:start]+ + ("0" if chosen == NUMBER else chosen)+ + value[end:]+ )+ variant[prop] = " ".join(value.split())+ variants.append(_merge_gradient(variant))+ return variants+++def _scan_styles(text, name, allowlist=None):+ """``(rules, unread, found)`` for the inline styles in one file's+ ``text``: the pseudo-rules (``style@L<line>``, or ``style@L<line>#<n>``+ per combination of listed expression values), ``{"style@L<line>":+ reason}`` for each style that cannot be read, and ``{(name, line,+ property): {expression, ...}}`` for every expression found."""+ allowlist = DYNAMIC_INLINE_STYLES if allowlist is None else allowlist+ rules, unread, found = [], {}, {}+ for offset, read in _style_sites(text):+ label = f"style@L{text.count(chr(10), 0, offset) + 1}"+ decls = read and _style_declarations(text, *read)+ if decls is None:+ unread[label] = "cannot be read as literal declarations"+ continue+ for prop, _, spans in decls:+ for _, _, source, line in spans:+ found.setdefault((name, line, prop), set()).add(source)+ if not any(spans for _, _, spans in decls):+ static = {prop: " ".join(rest.split()) for prop, rest, _ in decls}+ rules.append((label, _merge_gradient(static)))+ continue+ variants = _style_variants(name, decls, allowlist)+ if variants == []:+ unread[label] = f"more than {_MAX_VARIANTS} combinations"+ elif variants:+ rules += [(f"{label}#{n}", v) for n, v in enumerate(variants)]+ return rules, unread, found+++def _markup_files():+ """``[(key, path)]`` for the templates and scripts the inline-style and+ anchor sweeps read, each keyed by its path under the web root+ (``templates/pages/metrics.html``,+ ``static/templates/followup_modal.html``, ``static/js/pages/news.js``):+ file names repeat across directories (``components/news.js`` and+ ``pages/news.js``, a fragment and a Jinja template both named+ ``followup_modal.html``), and a key shared by two files would let one+ file's styles, expressions or anchors overwrite the other's."""+ return [+ (path.relative_to(WEB_ROOT).as_posix(), path)+ for root, pattern in (+ (WEB_ROOT / "templates", "*.html"),+ (WEB_ROOT / "static" / "templates", "*.html"),+ (WEB_ROOT / "static" / "js", "*.js"),+ )+ for path in sorted(root.rglob(pattern))+ ]++[email protected]_cache(maxsize=None)+def _inline_scan():+ """``(sheets, unread, found)``: the inline-style pseudo-rules of each+ template and script, ``{(file, "style@L<line>"): reason}`` for each+ style that cannot be read, and ``{(file, line, property):+ {expression, ...}}`` for every expression in an inline style."""+ sheets, unread, found = [], {}, {}+ for name, path in _markup_files():+ rules, missing, expressions = _scan_styles(+ path.read_text(encoding="utf-8"), name+ )+ unread.update(((name, label), why) for label, why in missing.items())+ found.update(expressions)+ if rules:+ sheets.append((name, rules))+ return sheets, unread, found+++def _inline_styles():+ """``style`` attributes and whole-style writes in templates and scripts,+ one pseudo-rule per style named after its line (one per combination of+ listed expression values, ``style@L<line>#<n>``)."""+ yield from _inline_scan()[0]+++def _allow_key(name, selector):+ """The allowlist key of a rule: an expanded inline style+ (``style@L12#1``) is listed by its attribute (``style@L12``)."""+ return name, re.sub(r"^(style@L\d+)#\d+$", r"\1", selector)+++# Every expression in an inline style: (file, line of the ``${``,+# property) -> (expression text, whitespace collapsed; every value it can+# take; pair label or None). Entries on one style sharing a pair label are+# taken value by value (the fill and ink of one ternary); all others are+# combined. NUMBER marks an expression that always yields a number. Each+# entry names the source its values were read from; a reviewer re-reads+# it whenever the line or the expression changes (the entry then fails as+# unlisted or stale). An entry pins the use site only: a change to what the+# expression evaluates to, made elsewhere (a new branch in the helper or+# ternary it names), fails only when a listed value disappears from the+# file (``test_dynamic_inline_style_values_are_literals``).+_STATE_COLORS = (+ "var(--success-color, #2ecc71)",+ "var(--error-color, #fa5c7c)",+ "var(--accent-primary, #0b84ff)",+ "var(--bg-tertiary, #444)",+)+DYNAMIC_INLINE_STYLES = {+ # benchmark.html L1428 (createExpandableText): the two halves of an+ # expandable answer, one shown and one hidden.+ ("templates/pages/benchmark.html", 1430, "display"): (+ "isExpanded ? 'none' : 'inline'",+ ("none", "inline"),+ None,+ ),+ ("templates/pages/benchmark.html", 1431, "display"): (+ "isExpanded ? 'inline' : 'none'",+ ("inline", "none"),+ None,+ ),+ # context-overflow.js L517: ``const utilColor = utilPct > 80 ?+ # 'var(--error-color)' : utilPct > 50 ? 'var(--warning-color)' :+ # 'var(--success-color)'``, assigned once. L516 makes utilPct a number+ # (``Math.round(...)`` or 0); L579's truncationPercent is a number too.+ ("static/js/components/context-overflow.js", 571, "color"): (+ "utilColor",+ ("var(--error-color)", "var(--warning-color)", "var(--success-color)"),+ None,+ ),+ ("static/js/components/context-overflow.js", 574, "background"): (+ "utilColor",+ ("var(--error-color)", "var(--warning-color)", "var(--success-color)"),+ None,+ ),+ ("static/js/components/context-overflow.js", 574, "width"): (+ "Math.min(utilPct, 100)",+ (NUMBER,),+ None,+ ),+ ("static/js/components/context-overflow.js", 579, "width"): (+ "Math.min(truncationPercent, 100)",+ (NUMBER,),+ None,+ ),+ # details.js L716: an inline ternary of two literals.+ ("static/js/components/details.js", 716, "color"): (+ "item.success_status === 'success' ? 'var(--success-color)' "+ ": 'var(--error-color)'",+ ("var(--success-color)", "var(--error-color)"),+ None,+ ),+ # journal_quality.html L712-713: ``const pillBg = ok ?+ # 'var(--success-color)' : 'var(--error-color)'`` and ``const pillColor+ # = ok ? 'var(--text-on-success)' : 'var(--text-on-error)'`` in the same+ # arrow function, on the same ``ok``: paired.+ ("templates/pages/journal_quality.html", 723, "background"): (+ "pillBg",+ ("var(--success-color)", "var(--error-color)"),+ "pill",+ ),+ ("templates/pages/journal_quality.html", 723, "color"): (+ "pillColor",+ ("var(--text-on-success)", "var(--text-on-error)"),+ "pill",+ ),+ # journal_quality.html L772 ``function _stateColor(state)``: four+ # ``return`` literals (success, error, running, pending). L821-825+ # sets ``width`` to 0, 100, a number ``row.percent`` or 5.+ ("templates/pages/journal_quality.html", 828, "color"): (+ "_stateColor(row.state)",+ _STATE_COLORS,+ None,+ ),+ ("templates/pages/journal_quality.html", 831, "background"): (+ "_stateColor(row.state)",+ _STATE_COLORS,+ None,+ ),+ ("templates/pages/journal_quality.html", 831, "width"): (+ "width",+ (NUMBER,),+ None,+ ),+ # link_analytics.html L281: ``colors.background[index]`` from+ # generateChartColors (L453), which only copies its ten baseColors.+ ("templates/pages/link_analytics.html", 284, "border-left"): (+ "cardColor",+ tuple(+ f"rgba({rgb}, 0.8)"+ for rgb in (+ "107, 70, 193",+ "245, 158, 11",+ "59, 130, 246",+ "16, 185, 129",+ "239, 68, 68",+ "139, 69, 19",+ "255, 192, 203",+ "128, 128, 128",+ "255, 165, 0",+ "75, 0, 130",+ )+ ),+ None,+ ),+ # metrics.html L974: an inline ternary of two literals.+ ("templates/pages/metrics.html", 974, "color"): (+ "item.success_status === 'success' ? 'green' : 'red'",+ ("green", "red"),+ None,+ ),+ # news.js: ``Math.max(0, Math.min(100, ...))`` and ``Number(...) ||+ # 10`` are numbers.+ ("static/js/pages/news.js", 1207, "width"): (+ "Math.max(0, Math.min(100, (Number(item.impact_score) || 0) * 10))",+ (NUMBER,),+ None,+ ),+ ("static/js/pages/news.js", 2868, "width"): (+ "Number(statusData.progress) || 10",+ (NUMBER,),+ None,+ ),+}+++def test_markup_files_have_distinct_keys():+ """Each scanned template and script has its own key, so no file's+ inline styles, expressions (``_inline_scan``), text (``_markup_text``)+ or anchors (``_anchor_class_sets``) are overwritten by another file's:+ the scripts include file names that repeat across directories+ (``components/news.js`` and ``pages/news.js``)."""+ files = _markup_files()+ keys = [key for key, _ in files]+ assert len(keys) == len(set(keys)), sorted(+ key for key in set(keys) if keys.count(key) > 1+ )+ names = [path.name for _, path in files]+ assert len(set(names)) < len(names), "no repeated file name is scanned"+ assert {+ "static/js/components/news.js",+ "static/js/pages/news.js",+ } <= set(keys)+ assert _markup_text("static/js/pages/news.js") != _markup_text(+ "static/js/components/news.js"+ )+++def _markup_text(name):+ return dict(_markup_files())[name].read_text(encoding="utf-8")+++def test_dynamic_inline_styles_are_allowlisted():+ """Every inline style is read as literal declarations or fails, and+ every expression or template tag in one is listed in+ DYNAMIC_INLINE_STYLES at its exact (file, line, property) with the same+ expression text; a listed entry no longer found fails as stale."""+ _, unread, found = _inline_scan()+ assert not unread, unread+ unlisted = {+ key: sorted(sources)+ for key, sources in found.items()+ if len(sources) != 1+ or DYNAMIC_INLINE_STYLES.get(key, (None,))[0] not in sources+ }+ assert not unlisted, f"list these with their values: {unlisted}"+ stale = {+ key: entry[0]+ for key, entry in DYNAMIC_INLINE_STYLES.items()+ if found.get(key) != {entry[0]}+ }+ assert not stale, f"entries no longer found: {stale}"+++def test_dynamic_inline_style_values_are_literals():+ """Each DYNAMIC_INLINE_STYLES entry: its source line still holds the+ expression; each value is plain CSS text that cannot add a+ declaration (no ``;``, brace, quote, backslash or expression) and,+ unless it is NUMBER, still appears as a string literal in that file;+ NUMBER never stands for a colour; and entries sharing a pair label+ have the same number of values. The values' completeness is the+ reviewer's reading of the named source, not something this checks."""+ problems = []+ pairs = {}+ for (name, line, prop), (+ expression,+ values,+ pair,+ ) in DYNAMIC_INLINE_STYLES.items():+ text = _markup_text(name)+ source_line = " ".join(text.splitlines()[line - 1].split())+ if f"${{{expression}}}" not in source_line:+ problems.append(f"{name}:{line} no longer holds ${{{expression}}}")+ if not values:+ problems.append(f"{name}:{line} {prop}: no values")+ for value in values:+ if value == NUMBER:+ if _COLOUR_PROPERTY.search(prop):+ problems.append(f"{name}:{line} {prop}: NUMBER colour")+ continue+ if re.search(r"[;{}'\"`\\$<>]", value) or not value.strip():+ problems.append(f"{name}:{line} {prop}: {value!r} not plain")+ if f"'{value}'" not in text and f'"{value}"' not in text:+ problems.append(f"{name}:{line} {prop}: {value!r} not in file")+ if pair:+ pairs.setdefault((name, pair), set()).add(len(values))+ problems += [+ f"{key}: pair widths {w}" for key, w in pairs.items() if len(w) != 1+ ]+ assert not problems, problems+++def test_inline_style_scanner_over_reports():+ """Every shape the scanner does not model fails rather than being read+ as a style without a fill, and every expression is reported for the+ allowlist whatever property it sits in; literal styles and listed+ expressions still become rules."""+ unread_cases = {+ "whole attribute": '<i style="${st}">',+ "bare expression": "<i style=${st}>",+ "jinja attribute": "<i style={{ st }}>",+ "declaration from expression": '<i style="color: red; ${st}">',+ "expression in name": "<i style=\"${'back' + 'ground'}: red\">",+ "concatenation": "'<i style=\"background: ' + c + '; color: #fff\">'",+ "escaped concatenation": '"<i style=\\"background: " + c + "\\">"',+ "unquoted concatenation": "'<i style=background:' + c + '>'",+ "unclosed expression": '<i style="background: ${c; color: white">',+ "unclosed attribute": '<i style="background: red',+ "cssText variable": "el.style.cssText = css;",+ "cssText concatenation": "el.style.cssText = 'background: ' + c;",+ "cssText template concatenation": "el.style.cssText = `a: b` + c;",+ "style property assigned": "el.style = make();",+ "setAttribute variable": "el.setAttribute('style', css);",+ "setAttribute uppercase": 'el.setAttribute("STYLE", css);',+ # Script glue between string pieces is not a CSS string.+ "array join": "['<i style=\"background:', c, '\">'].join('')",+ "array join, spaced": "['<i style=\"background: ' , c , '\">']",+ "array join, member": "['<i style=\"background:', s.c, '\">']",+ "multi-argument call": (+ "fmt('<i style=\"background: ', c, '; color: white\">')"+ ),+ "multi-argument escaped quote": (+ 'fmt("<i style=\\"background: ", c, "; color: white\\">")'+ ),+ "multi-argument escaped single quote": (+ "fmt('<i style=\\'background: ', c, '\\'>')"+ ),+ "name between strings": "<i style=\"font-family: 'a', c, 'b'\">",+ "font-family glue": "['<i style=\"font-family: ', c, '\">']",+ "glue inside url()": "['<i style=\"background: url(', c, ')\">']",+ "glue inside url(), double quotes": (+ 'fmt("<i style=\'background: url(", c, ")\'>")'+ ),+ "glue after url()": (+ "['<i style=\"background: url(a.png) ', c, '\">']"+ ),+ "quote outside font-family": "<i style=\"content: 'a'\">",+ # An attribute ending in "var" is not a variable declaration.+ "attribute named data-var": '<i data-var style="${st}">',+ "data-var, call-shaped value": "<i data-var style=f(x)>",+ }+ for case, markup in unread_cases.items():+ rules, unread, _ = _scan_styles(markup, "case.js", {})+ assert unread and not rules, (case, rules)+ dynamic_cases = {+ "fill": ('<i style="background: ${pick({ ok })}">', 1, "background"),+ "non-fill property": (+ '<i style="width: ${w}; color: red">',+ 1,+ "width",+ ),+ "uppercase": ('<i STYLE="color: ${c}">', 1, "color"),+ "escaped quote": ('"<i style=\\"color: ${c}\\">"', 1, "color"),+ "single quote": ("`<i style='color: ${c}'>`", 1, "color"),+ "element style": ("el.style = `color: ${c}`;", 1, "color"),+ "cssText": ("el.style.cssText = `\n color: ${c};`;", 2, "color"),+ "cssText append": ("el.style.cssText += `color: ${c}`;", 1, "color"),+ "setAttribute": (+ "el.setAttribute('style', `color: ${c}`);",+ 1,+ "color",+ ),+ "jinja value": ('<i style="color: {{ c }}">', 1, "color"),+ "nested quote": (+ '<i style="background: ${ok ? "var(--a)" : "var(--b)"}">',+ 1,+ "background",+ ),+ "after data-var": ('<i data-var style="color: ${c}">', 1, "color"),+ "after an attribute named var": (+ '<i var style="color: ${c}">',+ 1,+ "color",+ ),+ }+ for case, (markup, line, prop) in dynamic_cases.items():+ rules, unread, found = _scan_styles(markup, "case.js", {})+ assert not rules and not unread, (case, rules, unread)+ assert set(found) == {("case.js", line, prop)}, (case, found)+ # A variable named style set from a call is a script variable, not a+ # style.+ for markup in (+ "const style = getComputedStyle(el);",+ "\tlet style = document.createElement('style');",+ ):+ assert _scan_styles(markup, "x.js", {}) == ([], {}, {}), markup+ # Literal styles are read, writes included.+ rules, unread, _ = _scan_styles(+ '<b style="background-image: linear-gradient(#000, #111); '+ "color: white; background-image: url('a.png') \">\n"+ "el.style.cssText = 'background: #000; color: #fff';",+ "x.js",+ {},+ )+ assert not unread, unread+ assert [label for label, _ in rules] == ["style@L1", "style@L2"]+ assert rules[1][1] == {"background": "#000", "color": "#fff"}+ # Quoted font names stay literal CSS strings.+ rules, unread, _ = _scan_styles(+ "<pre style=\"font-family: 'Courier New', monospace\">\n"+ "<pre style=\"font-family: 'Monaco', 'Menlo', 'Ubuntu Mono'\">",+ "x.js",+ {},+ )+ assert not unread, unread+ assert [d["font-family"] for _, d in rules] == [+ "'Courier New', monospace",+ "'Monaco', 'Menlo', 'Ubuntu Mono'",+ ]+ # Listed expressions expand: paired entries value by value, the rest+ # combined, and an entry with other expression text does not match.+ markup = '<i style="background: ${bg}; color: ${ink}; width: ${w}%">'+ listed = {+ ("x.js", 1, "background"): ("bg", ("var(--a)", "var(--b)"), "p"),+ ("x.js", 1, "color"): ("ink", ("var(--on-a)", "var(--on-b)"), "p"),+ ("x.js", 1, "width"): ("w", (NUMBER,), None),+ }+ rules, unread, _ = _scan_styles(markup, "x.js", listed)+ assert not unread+ assert [+ (label, d["background"], d["color"], d["width"]) for label, d in rules+ ] == [+ ("style@L1#0", "var(--a)", "var(--on-a)", "0%"),+ ("style@L1#1", "var(--b)", "var(--on-b)", "0%"),+ ]+ listed[("x.js", 1, "color")] = ("ink2", ("var(--on-a)", "var(--on-b)"), "p")+ assert _scan_styles(markup, "x.js", listed)[0] == []+ listed[("x.js", 1, "color")] = ("ink", ("var(--on-a)", "var(--on-b)"), None)+ assert len(_scan_styles(markup, "x.js", listed)[0]) == 4+++def test_inline_style_scan_finds_the_known_expressions():+ """The scan reaches the expression styles reviewers found (an empty or+ narrowed scan would make the allowlist test pass vacuously), and+ expands the listed fills into rules the sweeps check."""+ sheets, _, found = _inline_scan()+ assert {+ ("templates/pages/journal_quality.html", 723, "background"),+ ("templates/pages/journal_quality.html", 831, "background"),+ ("static/js/components/context-overflow.js", 574, "background"),+ ("static/js/components/details.js", 716, "color"),+ ("templates/pages/metrics.html", 974, "color"),+ } <= set(found), sorted(found)+ expanded = {+ _allow_key(name, selector)+ for name, rules in sheets+ for selector, _ in rules+ if "#" in selector+ }+ assert {+ ("templates/pages/journal_quality.html", "style@L723"),+ ("templates/pages/journal_quality.html", "style@L831"),+ ("static/js/components/context-overflow.js", "style@L574"),+ } <= expanded, sorted(expanded)+++def _sheets():+ for name, css in _stylesheets():+ yield name, list(_parse_rules(css))+ yield from _inline_styles()+++def test_accent_fill_sweep_reads_css_and_templates():+ """An empty glob would make the sweep below pass vacuously."""+ names = {name for name, _ in _stylesheets()}+ assert {+ "news-enhanced.css",+ "templates/auth/login.html",+ "templates/pages/note_detail.html",+ } <= names+ inline = {name for name, _ in _inline_styles()}+ assert {+ "templates/pages/link_analytics.html",+ "static/js/collection_upload.js",+ "static/templates/followup_modal.html",+ } <= inline+++# Accent fills that draw no text, so they need no ink.+_BAR = "progress or score bar; its label sits outside the fill"+_STRIPE = "decorative accent stripe; content: '' draws no text"+NON_TEXT_ACCENT_FILLS = {+ ("benchmark.css", ".ldr-progress-fill"): _BAR,+ ("templates/pages/benchmark_simple.html", ".ldr-progress-fill"): _BAR,+ ("library.css", ".ldr-progress-fill"): _BAR,+ ("semantic-search.css", ".ldr-progress-track .ldr-progress-bar"): _BAR,+ ("templates/pages/zotero.html", ".ldr-zotero-progress-fill"): _BAR,+ ("collection_details.css", ".ldr-progress-fill"): _BAR,+ ("link_analytics.css", ".ldr-source-type-fill.ldr-academic"): _BAR,+ ("news.css", ".ldr-active-research-card .ldr-progress-bar"): _BAR,+ ("star_reviews.css", ".ldr-rating-fill"): _BAR,+ ("styles.css", ".ldr-progress-fill"): _BAR,+ ("styles.css", ".ldr-detail-progress-fill"): _BAR,+ ("static/js/collection_upload.js", "style@L576"): _BAR,+ ("static/js/collection_upload.js", "style@L646"): _BAR,+ # _stateColor(): success, error, accent or the track colour.+ ("templates/pages/journal_quality.html", "style@L831"): _BAR,+ ("collection_details.css", ".ldr-stat-card::before"): _STRIPE,+ ("collection_details.css", ".ldr-document-item::before"): _STRIPE,+ ("news-enhanced.css", ".ldr-news-item::before"): _STRIPE,+ ("news.css", ".ldr-active-research-card::before"): _STRIPE,+ ("notes.css", ".ldr-note-card::before"): _STRIPE,+ ("mobile-navigation.css", ".ldr-mobile-nav-tab.active::before"): _STRIPE,+ (+ "mobile-navigation.css",+ ".ldr-mobile-nav-tab::after",+ ): "tap ripple; content: '' draws no text",+ (+ "mobile-navigation.css",+ ".ldr-mobile-sheet-item::after",+ ): "tap ripple; content: '' draws no text",+ (+ "collection_details.css",+ ".ldr-documents-list::-webkit-scrollbar-thumb",+ ): "scrollbar thumb",+ (+ "collections.css",+ ".ldr-collections-grid::-webkit-scrollbar-thumb",+ ): "scrollbar thumb",+ (+ "collections.css",+ ".ldr-collections-grid::-webkit-scrollbar-thumb:hover",+ ): "scrollbar thumb",+ (+ "document_details.css",+ ".ldr-content-preview::-webkit-scrollbar-thumb",+ ): "scrollbar thumb",+ (+ "news.css",+ ".ldr-subscriptions-horizontal::-webkit-scrollbar-thumb",+ ): "scrollbar thumb",+ (+ "settings.css",+ ".ldr-settings-tabs::-webkit-scrollbar-thumb",+ ): "scrollbar thumb",+ (+ "mobile-responsive.css",+ 'input[type="range"]::-webkit-slider-thumb',+ ): "range slider thumb",+ (+ "mobile-responsive.css",+ 'input[type="range"]::-moz-range-thumb',+ ): "range slider thumb",+ (+ "news.css",+ ".ldr-toggle-switch input:checked + .ldr-toggle-slider",+ ): "toggle track; its knob is the ::after with its own fill",+ (+ "benchmark.css",+ ".ldr-toggle-switch.ldr-active",+ ): "toggle track; its knob is the ::after with its own fill",+ # The checkmark is the ::after, checked above as ink on this fill.+ (+ "settings.css",+ '.ldr-checkbox-label input[type="checkbox"]:checked',+ ): "checked checkbox box",+ (+ "templates/auth/login.html",+ '.ldr-checkbox-label input[type="checkbox"]:checked',+ ): "checked native checkbox box (no glyph rule)",+ (+ "templates/auth/register.html",+ '.ldr-checkbox-label input[type="checkbox"]:checked',+ ): "checked native checkbox box (no glyph rule)",+}+++def _ink(value):+ return _drop_fallbacks(value.replace("!important", "")).strip()+++def test_accent_fills_use_accent_ink():+ """The converse of the check above: text drawn on an accent fill uses+ the accent ink. A state or modifier rule inherits the fill or the ink+ from its base selector in the same sheet (``.btn-primary:hover`` keeps+ the ``.btn-primary`` fill; ``.ldr-nav-link-btn.ldr-nav-accent`` keeps+ the ``.ldr-nav-link-btn`` ink), so the pair is resolved through that+ chain. An accent fill whose chain sets no ink fails too (its text would+ take an ink from a co-class or parent the sweep cannot see) unless it+ is listed in NON_TEXT_ACCENT_FILLS. Inline ``style`` attributes in+ templates and scripts count as rules of their own. A fill through an+ alias of the accent (``var(--primary-color)``, see ``_accent_aliases``)+ is an accent fill. Gradient text (background-clip: text) draws no+ fill.++ Limits: the chain only climbs from a selector to its own base, so a+ base-state rule that also matches a modifier (``.x:hover`` restyling a+ hovered ``.x.active``) is not applied to it, and rules from other sheets+ and type selectors (``a:hover``, a theme's ``[data-theme] a``) are not+ seen; ``test_filled_anchors_keep_readable_ink`` covers those for+ filled controls on links."""+ offenders = []+ allowed_seen = set()+ for name, rules in _sheets():+ fills, inks, selectors = {}, {}, []+ for selector_list, decls in rules:+ if selector_list.startswith("@"):+ continue+ clipped = {"background-clip", "-webkit-background-clip"} & set(+ decls+ )+ background = decls.get("background-color", decls.get("background"))+ for selector in (s.strip() for s in selector_list.split(",")):+ if background:+ fills[selector] = None if clipped else background+ if "color" in decls:+ inks[selector] = decls["color"]+ if background or "color" in decls:+ selectors.append(selector)+ for selector in dict.fromkeys(selectors):+ chain = _selector_chain(selector)+ fill = next((fills[s] for s in chain if s in fills), None)+ ink = next((inks[s] for s in chain if s in inks), None)+ pseudo = _PSEUDO_ELEMENT.search(selector)+ if pseudo and fill is None and selector in inks:+ # An unfilled ::before/::after with its own ink draws on the+ # originating element's fill (the settings checkmark).+ origin = _selector_chain(selector[: pseudo.start()])+ fill = next((fills[s] for s in origin if s in fills), None)+ ancestor = re.match(r"(.*\S)\s*[ >]\s*[^ >+~]+$", selector)+ if ancestor and fill is None and selector in inks:+ # Unfilled text inside an accent-filled ancestor+ # (``.dropdown-item.active small``).+ origin = _selector_chain(ancestor.group(1))+ fill = next((fills[s] for s in origin if s in fills), None)+ if not fill or not _is_accent_fill(fill):+ continue+ if ink is not None and _ink(ink) == ACCENT_INK:+ continue+ for allowlist in (DEAD_ACCENT_RULES, NON_TEXT_ACCENT_FILLS):+ if _allow_key(name, selector) in allowlist:+ allowed_seen.add(_allow_key(name, selector))+ break+ else:+ offenders.append(f"{name} {selector}: {ink} on {fill}")+ assert not offenders, offenders+ stale = (DEAD_ACCENT_RULES | set(NON_TEXT_ACCENT_FILLS)) - allowed_seen+ assert not stale, f"allowlist entries no longer needed: {sorted(stale)}"+++# Inks chosen for one filled token. A rule that pairs one of them with a+# fill, or a modifier or state rule that swaps the fill while keeping the+# ink of its base (``.ldr-log-indicator--has-error`` keeps+# ``.ldr-log-indicator``'s accent ink), must still read there.+FILL_INKS = frozenset(+ {+ ACCENT_INK,+ "var(--text-on-error)",+ "var(--text-on-warning)",+ "var(--text-on-success)",+ }+)+# ``.block--modifier`` is a modifier of ``.block``: script adds it beside+# the block's class, so it takes the block's ink.+_BEM_MODIFIER = re.compile(r"\.([\w-]+?)--[\w-]+")+++def _palettes():+ """``[(name, props)]`` for the bare ``:root`` palette and every theme."""+ root = _root_defaults()+ palettes = [(":root", root)]+ for path in THEME_FILES:+ props = dict(root)+ props.update(_custom_properties(path.read_text(encoding="utf-8")))+ palettes.append((path.stem, props))+ return palettes++[email protected]("kind", ["error", "warning", "success"])+def test_status_ink_contrast(kind):+ """``--text-on-<kind>`` reads on ``--<kind>-color`` in every palette+ (the :root error ink, black, is 4.13:1 on kanagawa's red, which sets+ white; light palettes set white on their darkened status colours)."""+ failures = []+ for name, props in _palettes():+ ratio = _contrast(+ _resolve(f"text-on-{kind}", props), _resolve(f"{kind}-color", props)+ )+ if ratio < 4.5:+ failures.append(f"{name}: {ratio:.2f}:1")+ assert not failures, failures+++# A stop of a status colour: ``var(--error-color)`` or its ``-rgb`` twin.+_STATUS_STOP = re.compile(+ r"var\(--(error|warning|success)-color\)"+ r"|rgba?\(\s*var\(--(error|warning|success)-color-rgb\)"+ r"\s*(?:,\s*([\d.]+)\s*)?\)"+)+++def _direct_status_kinds(value, aliases):+ kinds = set()+ for match in _STATUS_STOP.finditer(value):+ alpha = float(match.group(3)) if match.group(3) else 1.0+ if alpha >= 0.5:+ kinds.add(match.group(1) or match.group(2))+ for token in _VAR_STOP.findall(value):+ kinds |= aliases.get(token, set())+ return kinds+++def _status_aliases():+ """``{token: kinds}`` for the custom properties that draw a status+ colour solidly (as ``_status_fill_kinds`` reads it) under any of their+ definitions in shipped CSS, followed transitively: a plain alias or a+ gradient (``--news-gradient-2``, accent secondary to error red)."""+ definitions = _custom_property_definitions()+ aliases = {}+ changed = True+ while changed:+ changed = False+ for token, values in definitions.items():+ if token in ("error-color", "warning-color", "success-color"):+ continue+ kinds = set()+ for _, _, value in values:+ kinds |= _direct_status_kinds(_ink(value), aliases)+ if kinds - aliases.get(token, set()):+ aliases[token] = aliases.get(token, set()) | kinds+ changed = True+ return aliases+++def _status_fill_kinds(fill):+ """The status colours (``error``, ``warning``, ``success``) a fill draws+ solidly: as a plain stop, through a ``var()`` fallback, as a gradient+ stop, as an ``-rgb`` twin at alpha 0.5 or more, or through a custom+ property that draws one (``_status_aliases``). Fainter tints are left+ to the rule's own ink and the page behind them."""+ return _direct_status_kinds(_ink(fill), _status_aliases())+++# Status fills that draw no text, so they need no ink.+_DOT = "status dot; draws no text"+_STRENGTH = "password strength bar; draws no text"+NON_TEXT_STATUS_FILLS = {+ ("context_overflow.css", ".ldr-progress-fill"): _BAR,+ ("link_analytics.css", ".ldr-source-type-fill.ldr-news"): _BAR,+ ("link_analytics.css", ".ldr-source-type-fill.ldr-general"): _BAR,+ ("news.css", ".ldr-impact-fill"): _BAR,+ # The same bar restyled with --news-gradient-2 (accent to error red).+ ("news-enhanced.css", ".ldr-impact-fill"): _BAR,+ ("subscriptions.css", ".ldr-status-indicator.active"): _DOT,+ ("subscriptions.css", ".ldr-status-indicator.ldr-inactive"): _DOT,+ ("subscriptions.css", ".ldr-status-indicator.ldr-checking"): _DOT,+ ("templates/auth/change_password.html", ".ldr-strength-weak"): _STRENGTH,+ ("templates/auth/change_password.html", ".ldr-strength-medium"): _STRENGTH,+ ("templates/auth/change_password.html", ".ldr-strength-strong"): _STRENGTH,+ ("templates/auth/register.html", ".ldr-strength-weak"): _STRENGTH,+ ("templates/auth/register.html", ".ldr-strength-medium"): _STRENGTH,+ ("templates/auth/register.html", ".ldr-strength-strong"): _STRENGTH,+ # The utilColor and _stateColor() bars; their figures sit beside them.+ ("static/js/components/context-overflow.js", "style@L574"): _BAR,+ ("templates/pages/journal_quality.html", "style@L831"): _BAR,+}++# Pre-existing gaps on status fills: (sheet, selector) -> (worst palette,+# worst ratio, number of palettes under 4.5:1), as measured by+# test_fill_inks_read_on_swapped_fills. Only that exact measurement is+# exempt; any change to it (better or worse) fails as stale so the list+# stays exact. A fill whose only status colour is the error red is never+# exempt: --text-on-error reads on it in every palette.+KNOWN_STATUS_FILL_GAPS = {+ # The warning-to-error gradient: --text-on-error reads on its red end+ # everywhere, but kanagawa's error ink (white) is 1.68:1 on its yellow+ # start. No single ink token reads on both ends in every palette.+ ("metrics.css", ".ldr-nav-link-btn.ldr-nav-warning"): ("kanagawa", 1.68, 1),+ ("styles.css", ".ldr-nav-link-btn.ldr-nav-warning"): ("kanagawa", 1.68, 1),+}+++def _fill_ink_pairs():+ """``(sheet, selector, ink, fill)`` for each rule with a non-accent fill+ whose ink, set by the rule or inherited along its selector chain (and+ from a BEM block to its ``--modifier``), is one of FILL_INKS, and for+ each rule with a status fill (``_status_fill_kinds``) whatever its ink;+ ``ink`` is None there when the chain sets none."""+ pairs = []+ for name, rules in _sheets():+ fills, inks, filled = {}, {}, []+ for selector_list, decls in rules:+ if selector_list.startswith("@"):+ continue+ clipped = {"background-clip", "-webkit-background-clip"} & set(+ decls+ )+ background = decls.get("background-color", decls.get("background"))+ for selector in (s.strip() for s in selector_list.split(",")):+ if background:+ fills[selector] = None if clipped else background+ filled.append(selector)+ if "color" in decls:+ inks[selector] = decls["color"]+ for selector in dict.fromkeys(filled):+ fill = fills[selector]+ if not fill or _PSEUDO_ELEMENT.search(selector):+ continue+ if _is_accent_fill(_ink(fill)):+ continue+ chain = _selector_chain(selector)+ for link in list(chain):+ block = _BEM_MODIFIER.sub(lambda m: "." + m.group(1), link)+ if block != link:+ chain += [+ s for s in _selector_chain(block) if s not in chain+ ]+ ink = next((inks[s] for s in chain if s in inks), None)+ if _status_fill_kinds(fill):+ pairs.append((name, selector, ink and _ink(ink), fill))+ elif ink is not None and _ink(ink) in FILL_INKS:+ pairs.append((name, selector, _ink(ink), fill))+ return pairs+++def test_fill_inks_read_on_swapped_fills():+ """A rule pairing a fill ink (FILL_INKS) with a fill other than the+ accent, directly or by inheriting the ink of its base selector, keeps+ 4.5:1 on every stop of that fill, composited over the page and card+ backgrounds (a transparent fill leaves the ink on those), in every+ palette. So does any ink, literal colours included, on a status fill+ (``--error-color``, ``--warning-color`` or ``--success-color``, see+ ``_status_fill_kinds``); a status fill whose chain sets no ink fails+ (its text would take an ink from a co-class or parent the sweep cannot+ see) unless it is listed in NON_TEXT_STATUS_FILLS. A fill or ink that+ does not resolve fails rather than being skipped, including a fill in+ a colour syntax the parser does not read (``_fill_stops``). The only+ exemptions are the exact pre-existing gaps in KNOWN_STATUS_FILL_GAPS.++ Limits: the ink is inherited within one sheet only (along the selector+ chain and from a ``.block`` to its ``.block--modifier``); an inline+ style built from a template expression is checked as each value+ DYNAMIC_INLINE_STYLES lists for it (an unlisted expression fails in+ ``test_dynamic_inline_styles_are_allowlisted``); pseudo-element rules,+ fills and inks set one property at a time (``element.style.color``),+ ``filter`` on hover and+ cross-sheet type selectors (``a:hover``, see+ ``test_filled_anchors_keep_readable_ink``) are not checked."""+ pairs = _fill_ink_pairs()+ found = {(name, selector) for name, selector, _, _ in pairs}+ assert {+ ("styles.css", ".ldr-log-indicator--has-error"),+ ("styles.css", ".ldr-console-log-entry.ldr-log-error .ldr-log-badge"),+ ("styles.css", ".ldr-badge-danger"),+ ("templates/pages/journal_quality.html", ".ldr-quality-dangerous"),+ ("static/js/components/context-overflow.js", "style@L250"),+ } <= found+ assert len(pairs) >= 80, "too few fill/ink pairs were found"+ palettes = _palettes()+ offenders, gaps, allowed_seen = [], {}, set()+ for name, selector, ink, fill in pairs:+ key = _allow_key(name, selector)+ if ink is None:+ if key in NON_TEXT_STATUS_FILLS:+ allowed_seen.add(key)+ else:+ offenders.append(f"{name} {selector}: no ink on {fill}")+ continue+ failing = []+ for palette, props in palettes:+ ink_rgb = _resolve_color(ink, props)+ stops = _fill_stops(fill, props)+ if ink_rgb is None or stops is None:+ offenders.append(f"{name} {selector} [{palette}]: unresolved")+ continue+ # A transparent fill leaves the ink on the page or card.+ backdrops = [_resolve(token, props) for token in _BACKDROPS]+ worst = min(+ _contrast(ink_rgb, surface)+ for surface in _over(backdrops, stops)+ )+ if worst < 4.5:+ failing.append((worst, palette))+ if not failing:+ continue+ if key in KNOWN_STATUS_FILL_GAPS and _status_fill_kinds(fill) - {+ "error"+ }:+ worst, palette = min(failing, key=lambda item: item[0])+ gaps[key] = (palette, round(worst, 2), len(failing))+ continue+ offenders += [+ f"{name} {selector} [{palette}]: {ink} on {fill} {worst:.2f}:1"+ for worst, palette in failing+ ]+ assert not offenders, offenders+ stale = {+ key: (reason, None)+ for key, reason in NON_TEXT_STATUS_FILLS.items()+ if key not in allowed_seen+ }+ stale.update(+ (key, (recorded, gaps.get(key)))+ for key, recorded in KNOWN_STATUS_FILL_GAPS.items()+ if gaps.get(key) != recorded+ )+ assert not stale, f"entries to update (recorded, now): {stale}"+++# A custom property whose value names a status colour, read from the raw+# text independently of the rule parser.+_STATUS_DEFINITION = re.compile(+ r"--([\w-]+)\s*:\s*([^;{}]*(?:error|warning|success)-color[^;{}]*)"+)+++def test_status_colour_aliases_are_recognised():+ """The status-fill sweeps recognise the status tokens by name, so every+ custom property that names one must be followed: a ``--x:+ var(--error-color)`` alias or a gradient of status stops+ (``--news-gradient-2``) is a status fill through ``_status_aliases``.+ The only other definitions allowed are faint tints and shadows (every+ status stop an ``-rgb`` twin under alpha 0.5), which no sweep treats as+ a status fill; anything else, such as a bare ``-rgb`` twin alias+ (``--x-rgb: var(--error-color-rgb)``), fails."""+ aliases = _status_aliases()+ assert {"news-gradient-2", "news-gradient-3", "news-gradient-4"} <= set(+ aliases+ ), aliases+ assert _status_fill_kinds("var(--news-gradient-4)") == {"error", "warning"}+ missed, found = [], 0+ for name, css in _css_sources():+ for match in _STATUS_DEFINITION.finditer(_strip_comments(css)):+ token, value = match.group(1), _ink(match.group(2))+ if token in ("error-color", "warning-color", "success-color"):+ continue+ found += 1+ if token in aliases:+ continue+ faint = [+ float(alpha)+ for alpha in re.findall(+ r"rgba?\(\s*var\(--(?:error|warning|success)-color-rgb\)"+ r"\s*,\s*([\d.]+)\s*\)",+ value,+ )+ ]+ mentions = len(+ re.findall(r"(?:error|warning|success)-color", value)+ )+ if faint and len(faint) == mentions and max(faint) < 0.5:+ continue+ missed.append(f"{name}: --{token}: {value}")+ assert found >= 3, "status alias scan found too few definitions"+ assert not missed, missed+++# --- Accent-filled anchors against the cascade ----------------------------+#+# The sweep above resolves fill and ink within one sheet and through class+# chains only. An accent-filled class on an ``<a>`` also meets type+# selectors from other sheets: styles.css ``a`` and ``a:hover`` (0,1,1) and+# a theme's ``[data-theme="..."] a`` (0,1,1) and ``a:hover`` (0,2,1) outrank+# a single-class ink rule (0,1,0), so the label would take the link colour.+# The check below rebuilds that cascade statically.++# Classes JavaScript toggles at run time, so an anchor need not carry them+# in its markup to take a fill rule that requires them.+_STATE_CLASSES = frozenset(+ {"active", "selected", "show", "open", "disabled", "current"}+)+# The interaction states checked, as the pseudo-classes each one matches.+_STATES = {+ "rest": frozenset(),+ "hover": frozenset({"hover"}),+ "focus": frozenset({"focus", "focus-visible", "focus-within"}),+ "visited": frozenset({"visited"}),+ "pressed": frozenset(+ {"active", "hover", "focus", "focus-visible", "focus-within"}+ ),+}+_INTERACTIVE = frozenset(+ {"hover", "focus", "focus-visible", "focus-within", "active", "visited"}+)+# Pseudo-classes an anchor never matches.+_NEVER = frozenset(+ {"disabled", "checked", "indeterminate", "placeholder-shown"}+)+_SIMPLE = re.compile(+ r"\*|[a-zA-Z][\w-]*|\.[\w-]+|#[\w-]+|\[[^\]]*\]"+ r"|::?[\w-]+(?:\((?:[^()]|\([^()]*\))*\))?"+)+_SCOPE = re.compile(+ r"(?:html|:root|body)?(?:\[data-theme(?:=[\"']?[\w-]+[\"']?)?\])?"+ r"(?:\s+(?:html|body))?"+)+++def _split_top(text, sep):+ parts, depth, start = [], 0, 0+ for i, char in enumerate(text):+ depth += char == "("+ depth -= char == ")"+ if char == sep and depth == 0:+ parts.append(text[start:i].strip())+ start = i + 1+ parts.append(text[start:].strip())+ return parts+++def _subject_split(selector):+ """``.a > .b:hover`` -> (``.a``, ``.b:hover``), ignoring combinators+ inside ``:not(...)``."""+ depth, cut = 0, -1+ for i, char in enumerate(selector):+ depth += char == "("+ depth -= char == ")"+ if depth == 0 and char in " >+~":+ cut = i+ if cut < 0:+ return "", selector+ return selector[:cut].strip(" >+~"), selector[cut + 1 :].strip()+++def _simples(compound):+ tokens, pos = [], 0+ while pos < len(compound):+ match = _SIMPLE.match(compound, pos)+ if not match:+ return None+ tokens.append(match.group(0))+ pos = match.end()+ return tokens+++def _specificity(selector):+ ids = classes = types = 0+ for compound in re.split(r"\s*[ >+~]\s*", selector.strip()):+ for token in _simples(compound) or []:+ if token.startswith("#"):+ ids += 1+ elif token.startswith(("[", ".")):+ classes += 1+ elif token.startswith("::"):+ types += 1+ elif token.startswith(":"):+ name, _, args = token[1:].partition("(")+ if name == "where":+ continue+ if name in ("not", "is", "has"):+ inner = [+ _specificity(s) for s in _split_top(args[:-1], ",")+ ]+ best = max(inner, default=(0, 0, 0))+ ids, classes, types = (+ ids + best[0],+ classes + best[1],+ types + best[2],+ )+ else:+ classes += 1+ elif token != "*":+ types += 1+ return ids, classes, types+++def _compound_matches(compound, classes, state, tag="a"):+ """Whether a ``tag`` element (an ``<a>`` unless stated) with ``classes``+ in ``state`` matches one compound selector. Ids are never matched+ (elements are tracked by class), other attributes and structural+ pseudo-classes are assumed to match."""+ tokens = _simples(compound)+ if not tokens:+ return False+ for token in tokens:+ if token.startswith("::"):+ return False+ if token.startswith("#"):+ return False+ if token.startswith("."):+ if token[1:] not in classes:+ return False+ elif token.startswith(":"):+ name, _, args = token[1:].partition("(")+ if name in ("before", "after"):+ return False+ if name == "not":+ if any(+ _compound_matches(arg, classes, state, tag)+ for arg in _split_top(args[:-1], ",")+ ):+ return False+ elif name in ("is", "where"):+ if not any(+ _compound_matches(arg, classes, state, tag)+ for arg in _split_top(args[:-1], ",")+ ):+ return False+ elif name in ("link", "any-link"):+ if name == "link" and "visited" in state:+ return False+ elif name in _INTERACTIVE:+ if name not in state:+ return False+ elif name in _NEVER:+ return False+ elif token.startswith("["):+ continue+ elif token not in ("*", tag):+ return False+ return True+++def _anchor_class_sets():+ """The static classes of every ``<a>`` in templates and scripts (markup+ in HTML and template literals, and ``createElement('a')`` elements given+ a ``className`` or ``classList.add``), with template expressions+ dropped: ``{location: classes}``."""+ found = {}+ expression = re.compile(r"\$\{[^}]*\}|\{\{.*?\}\}|\{%.*?%\}", re.S)+ for name, path in _markup_files():+ text = path.read_text(encoding="utf-8")+ for match in re.finditer(+ r"<a\b[^>]*?\bclass\s*=\s*([\"'])(.*?)\1", text, flags=re.S+ ):+ line = text.count("\n", 0, match.start()) + 1+ classes = frozenset(expression.sub(" ", match.group(2)).split())+ if classes:+ found[f"{name}:{line}"] = classes+ for match in re.finditer(+ r"(?:const|let|var)\s+(\w+)\s*=\s*document\.createElement\("+ r"\s*['\"]a['\"]\s*\)",+ text,+ ):+ var = re.escape(match.group(1))+ names = set()+ for cls in re.finditer(+ rf"\b{var}\.className\s*=\s*(['\"`])(.*?)\1"+ rf"|\b{var}\.classList\.add\(([^)]*)\)",+ text,+ ):+ value = (+ cls.group(2) if cls.group(2) is not None else cls.group(3)+ )+ names |= set(re.findall(r"[\w-]+", expression.sub(" ", value)))+ if names:+ line = text.count("\n", 0, match.start()) + 1+ found[f"{name}:{line}"] = frozenset(names)+ return found+++def _decl(decls, prop):+ value = decls.get(prop)+ if value is None:+ return None+ important = value.endswith("!important")+ return important, value.replace("!important", "").strip()+++# The properties the cascade below tracks: the ink, the fill, the focus+# outline, and Bootstrap's button variables, which its .btn state rules+# draw as the ink and the fill.+_TRACKED = frozenset(+ {"color", "background", "background-color", "outline", "outline-color"}+)+_BS_BTN_VAR = re.compile(r"var\(\s*--(bs-btn-[\w-]+)\s*\)")+++def _prepare(rank, css):+ """``(rank, [(ancestors, subject, specificity)], decls)`` for each rule+ of ``css`` that sets a colour, a background, an outline,+ ``pointer-events`` or a ``--bs-btn-*`` variable."""+ prepared = []+ for selector_list, decls in _parse_rules(css):+ if selector_list.startswith("@") or not (+ _TRACKED & set(decls)+ or "pointer-events" in decls+ or any(prop.startswith("--bs-btn-") for prop in decls)+ ):+ continue+ selectors = [+ (*_subject_split(selector), _specificity(selector))+ for selector in _split_top(selector_list, ",")+ ]+ prepared.append((rank, selectors, decls))+ return prepared+++def _cascade_winners(rules, classes, state, context, theme, tag="a"):+ """Winning values of the tracked properties for one element:+ ``{"color"|"background"|"outline"|"pointer-events"|"--bs-btn-*":+ value}``. ``rules`` come+ from ``_prepare`` in load order; a selector counts when its subject+ compound matches and its ancestors are empty, a theme scope, or the+ given ancestors (``context``)."""+ winners = {}+ for rank, selectors, decls in rules:+ best = None+ for ancestors, subject, spec in selectors:+ if ancestors and ancestors != context:+ scope = _SCOPE.fullmatch(ancestors)+ if not scope or not scope.group(0):+ continue+ named = re.search(r"data-theme=[\"']?([\w-]+)", ancestors)+ if named and named.group(1) != theme:+ continue+ if not _compound_matches(subject, classes, state, tag):+ continue+ best = spec if best is None or spec > best else best+ if best is None:+ continue+ clipped = {"background-clip", "-webkit-background-clip"} & set(decls)+ pairs = [+ ("color", "color"),+ ("background", "background"),+ ("background-color", "background"),+ ("outline", "outline"),+ ("outline-color", "outline"),+ ("pointer-events", "pointer-events"),+ ]+ pairs += [+ (prop, prop) for prop in decls if prop.startswith("--bs-btn-")+ ]+ for prop, key in pairs:+ found = _decl(decls, prop)+ if found is None:+ continue+ important, value = found+ if key == "background" and clipped:+ value = "transparent"+ order = (important, best, rank)+ if key not in winners or order >= winners[key][0]:+ winners[key] = (order, value)+ values = {key: value for key, (_, value) in winners.items()}+ for key in ("color", "background", "outline"):+ value = values.get(key)+ for _ in range(5):+ if value is None or not _BS_BTN_VAR.search(value):+ break+ missing = [+ ref+ for ref in _BS_BTN_VAR.findall(value)+ if f"--{ref}" not in values+ ]+ if missing:+ # An undefined variable makes the declaration invalid at+ # computed-value time: the ink is inherited (unknown here)+ # and the fill is transparent.+ value = "transparent" if key == "background" else None+ break+ value = _BS_BTN_VAR.sub(+ lambda match: values[f"--{match.group(1)}"], value+ )+ values[key] = value+ return values+++def _cascade(rules, classes, state, context, theme, tag="a"):+ """Winning ``(color, background)`` values for one element, with+ ``var(--bs-btn-*)`` resolved against the variables the same cascade+ gives it."""+ values = _cascade_winners(rules, classes, state, context, theme, tag)+ return values.get("color"), values.get("background")+++def _resolve_color(value, props):+ """The opaque colour an ink or a stop draws, or None when it does not+ resolve (an unread syntax, a translucent literal, or a token+ ``_resolve`` rejects)."""+ value = _drop_fallbacks(value).strip()+ token = _VAR_STOP.fullmatch(value)+ if token:+ try:+ return _resolve(token.group(1), props)+ except AssertionError:+ return None+ parsed = _parse_color(value)+ if parsed is None or parsed[1] != 1:+ return None+ return parsed[0]+++def _readable(ink, fill, props):+ """Accent ink always reads on an accent fill (``test_accent_ink_contrast``+ checks the pair); any other ink must resolve to at least 4.5:1 on every+ colour stop of the fill under this theme's palette."""+ if _ink(ink) == ACCENT_INK:+ return True+ ink_rgb = _resolve_color(ink, props)+ stops = _COLOR_STOP.findall(_drop_fallbacks(fill))+ if ink_rgb is None or not stops:+ return False+ for stop in stops:+ stop_rgb = _resolve_color(stop, props)+ if stop_rgb is None or _contrast(ink_rgb, stop_rgb) < 4.5:+ return False+ return True+++# Bootstrap's button rules that set a button's ink or fill, and the+# .btn-primary variables they read, transcribed from bootstrap.css 5.3.8+# (app.js imports bootstrap.min.css before styles.css, so they load first).+# ``test_bootstrap_transcription_matches_the_locked_release`` ties this to+# the locked version.+BOOTSTRAP_VERSION = "5.3.8"+BOOTSTRAP_BTN_CSS = """+.btn {+ --bs-btn-color: var(--bs-body-color);+ --bs-btn-bg: transparent;+ color: var(--bs-btn-color);+ background-color: var(--bs-btn-bg);+}+.btn:hover {+ color: var(--bs-btn-hover-color);+ background-color: var(--bs-btn-hover-bg);+}+.btn-check + .btn:hover {+ color: var(--bs-btn-color);+ background-color: var(--bs-btn-bg);+}+.btn:focus-visible {+ color: var(--bs-btn-hover-color);+ background-color: var(--bs-btn-hover-bg);+}+.btn-check:checked + .btn, :not(.btn-check) + .btn:active, .btn:first-child:active, .btn.active, .btn.show {+ color: var(--bs-btn-active-color);+ background-color: var(--bs-btn-active-bg);+}+.btn:disabled, .btn.disabled, fieldset:disabled .btn {+ color: var(--bs-btn-disabled-color);+ background-color: var(--bs-btn-disabled-bg);+}+.btn-primary {+ --bs-btn-color: #fff;+ --bs-btn-bg: #0d6efd;+ --bs-btn-hover-color: #fff;+ --bs-btn-hover-bg: #0b5ed7;+ --bs-btn-active-color: #fff;+ --bs-btn-active-bg: #0a58ca;+ --bs-btn-disabled-color: #fff;+ --bs-btn-disabled-bg: #0d6efd;+}+"""+REPO_ROOT = WEB_ROOT.parents[2]+++def test_bootstrap_transcription_matches_the_locked_release():+ """The cascade check models Bootstrap from BOOTSTRAP_BTN_CSS, so a+ Bootstrap upgrade must revisit it; where the package is installed,+ every transcribed declaration is in the shipped stylesheet."""+ lock = (REPO_ROOT / "package-lock.json").read_text(encoding="utf-8")+ locked = re.search(+ r'"node_modules/bootstrap":\s*\{\s*"version":\s*"([^"]+)"', lock+ )+ assert locked, "package-lock.json no longer locks bootstrap"+ assert locked.group(1) == BOOTSTRAP_VERSION, (+ f"bootstrap {locked.group(1)} is locked; re-transcribe "+ "BOOTSTRAP_BTN_CSS from its dist/css/bootstrap.css"+ )+ shipped = REPO_ROOT / "node_modules/bootstrap/dist/css/bootstrap.css"+ if not shipped.exists():+ pytest.skip("bootstrap is not installed (npm ci)")+ rules = {}+ for selector, decls in _parse_rules(shipped.read_text(encoding="utf-8")):+ rules.setdefault(selector, {}).update(decls)+ for selector, decls in _parse_rules(BOOTSTRAP_BTN_CSS):+ assert selector in rules, f"bootstrap.css has no {selector!r} rule"+ for prop, value in decls.items():+ assert rules[selector].get(prop) == value, (selector, prop)+++def _theme_name(path):+ match = re.search(+ r"\[data-theme=[\"']?([\w-]+)", path.read_text(encoding="utf-8")+ )+ return match.group(1) if match else path.stem+++def _anchor_fill_trigger(background, ink):+ """Whether a fill rule is one the anchor replay checks: every filled+ control class. That is a fill with a colour stop (an accent or status+ token or an alias of one, its ``-rgb`` twin at alpha 0.5 or more, or a+ literal colour), a fill in a syntax the stop pattern does not read+ (replayed, so it fails as unresolved), or any fill whose ink -- set by+ the rule or inherited along its selector chain in the sheet -- is an+ on-fill ink (FILL_INKS) or a literal colour. A neutral surface+ (``--bg-tertiary``) under a theme text ink is not a filled control."""+ value = _ink(background)+ bare = re.sub(r"url\([^()]*\)|var\(--[\w-]+", " ", value)+ if _UNREAD_COLOR.search(bare):+ return True+ if _is_accent_fill(value) or _status_fill_kinds(value):+ return True+ accent, _, _ = _aliases()+ for stop in _COLOR_STOP.findall(value):+ token = _VAR_STOP.fullmatch(stop)+ rgba = _RGBA_TOKEN.fullmatch(stop)+ literal = _parse_color(stop)+ if token and (token.group(1) in _STATUS_TOKENS | accent):+ return True+ if rgba and rgba.group(1) in _STATUS_TOKENS | accent:+ if rgba.group(2) is None or float(rgba.group(2)) >= 0.5:+ return True+ if literal and literal[1] >= 0.5:+ return True+ if ink is None:+ return False+ ink = _ink(ink)+ return (+ ink in FILL_INKS+ or _parse_color(ink) is not None+ or bool(_UNREAD_COLOR.search(ink))+ )+++_TEMPLATES = WEB_ROOT / "templates"+++def _template_key(path):+ return path.relative_to(WEB_ROOT).as_posix()+++def _page_closure():+ """``{page key: (stylesheet names, template keys, script references)}``+ for each full page (a template that ``{% extends %}`` another), keyed+ like ``_markup_files``: every ``*.css`` and ``*.js`` named in its+ markup, the templates it extends and the ones they ``{% include %}`` or+ import from, transitively, and those templates themselves (whose+ ``<style>`` blocks and markup the page renders). Templates that extend+ nothing (fragments, components, standalone pages) are left out, and so+ is a page with a reference it cannot read: their sheets are+ unknown."""+ reference = re.compile(+ r"\{%-?\s*(extends|include|import|from)\s+([\"'])(.+?)\2"+ )+ pages = {}+ for path in sorted(_TEMPLATES.rglob("*.html")):+ if not re.search(+ r"\{%-?\s*extends\b", path.read_text(encoding="utf-8")+ ):+ continue+ sheets, scripts, todo, seen = set(), set(), [path], set()+ while todo:+ current = todo.pop()+ if current in seen:+ continue+ seen.add(current)+ if not current.is_file():+ # A template it cannot read: the page's sheets are unknown.+ sheets = None+ break+ body = current.read_text(encoding="utf-8")+ sheets |= set(re.findall(r"([\w.-]+\.css)\b", body))+ scripts |= set(re.findall(r"([\w./-]+\.js)\b", body))+ # A commented-out {# {% include %} #} loads nothing.+ live = re.sub(r"\{#.*?#\}", " ", body, flags=re.S)+ todo += [+ _TEMPLATES / target for _, _, target in reference.findall(live)+ ]+ if sheets is not None:+ templates = frozenset(_template_key(p) for p in seen)+ pages[_template_key(path)] = (sheets, templates, scripts)+ return pages+++def _page_sheets():+ """``{page key: stylesheet names}`` (``_page_closure``)."""+ return {page: sheets for page, (sheets, _, _) in _page_closure().items()}+++def _sheets_named_in_code():+ """Stylesheet names that script or Python code mentions (a sheet it may+ load into any page): never treated as absent from a page."""+ named = set()+ for path in [+ *(WEB_ROOT / "static" / "js").rglob("*.js"),+ *(REPO_ROOT / "src").rglob("*.py"),+ ]:+ named |= set(+ re.findall(r"([\w.-]+\.css)\b", path.read_text(encoding="utf-8"))+ )+ return named+++def _sheet_off_page(sheet, where):+ """Whether the fill sheet ``sheet`` is known not to reach the anchor at+ ``where``: the anchor is in a full page (``_page_sheets``) that names+ neither the sheet nor anything that loads it. styles.css and sheets+ named in code reach every page, a template's own ``<style>`` block+ (named after the template) reaches that template's anchors, and+ anchors built in script, and in templates whose page is unknown, are+ reached by every sheet."""+ page = where.rpartition(":")[0]+ if sheet in ("styles.css", page) or sheet in _sheets_named_in_code():+ return False+ loaded = _page_sheets().get(page)+ return loaded is not None and sheet not in loaded+++def _gap_exemptable(background):+ """A KNOWN_ANCHOR_FILL_GAPS entry only covers a fill with a stop outside+ the primary/secondary accent (and its aliases) and the status tokens:+ ``--accent-tertiary``, a neutral token or a literal colour."""+ accent, accent_rgb, _ = _aliases()+ status = {"error-color", "warning-color", "success-color"}+ for stop in _COLOR_STOP.findall(_ink(background)):+ token = _VAR_STOP.fullmatch(stop) or _RGB_STOP.fullmatch(stop)+ name = token and token.group(1)+ if not name or name not in accent | accent_rgb | status | {+ f"{s}-rgb" for s in status+ }:+ return True+ return False+++# Pre-existing gaps on filled anchors outside the accent and status fills+# (sheet, selector) -> (worst palette, worst ratio, number of failing+# scenarios, digest of every failing scenario and its ratio), as measured+# by test_filled_anchors_keep_readable_ink (``_gap_measurement``). A+# scenario is one (classes, context, state, palette) replay. Only a fill+# with a stop outside the primary/secondary accent and the status colours+# can be listed (``_gap_exemptable``); an unresolved ink or fill is never+# exempt, and any change to any failing scenario -- one more or one fewer,+# or a ratio that moves either way, even when the worst case and the count+# stay the same -- fails as stale, printing every failing scenario, so the+# list stays exact.+KNOWN_ANCHOR_FILL_GAPS = {+ # White on the --accent-tertiary to --accent-primary gradient: the+ # Metrics "Link Analytics" nav link and the document page's "View+ # Chunks" link. Mixed gradients are out of scope (see _COLOR_STOP):+ # no single ink token reads on both ends. High Contrast's a:hover green+ # on the green end is the 1.00:1 worst case.+ ("metrics.css", ".ldr-nav-link-btn.ldr-nav-info"): (+ "high-contrast",+ 1.0,+ 125,+ "eaa179253f4115a3",+ ),+ ("styles.css", ".ldr-nav-link-btn.ldr-nav-info"): (+ "high-contrast",+ 1.0,+ 125,+ "eaa179253f4115a3",+ ),+ ("document_details.css", ".ldr-btn-info"): (+ "high-contrast",+ 1.0,+ 141,+ "99d509c948be137e",+ ),+ # White on --accent-tertiary: the Library "View Text" action link.+ ("library.css", ".ldr-action-btn-txt"): (+ "high-contrast",+ 1.0,+ 115,+ "22f243fdfd560c22",+ ),+ # White on --btn-secondary-bg (--text-muted): the Document Chunks back+ # link, 3.37:1 with the :root palette.+ ("document_details.css", ".ldr-back-button"): (+ "high-contrast",+ 1.33,+ 115,+ "a93388242b77096d",+ ),+}+++def _gap_measurement(found):+ """A KNOWN_ANCHOR_FILL_GAPS measurement from its failing scenarios+ ``[(ratio, palette, state, classes, context)]``: the worst palette and+ ratio, the number of failing scenarios, and a digest of every failing+ scenario with its ratio, so that a scenario that starts or stops+ failing, or any failing ratio that moves (worse or better), changes+ the measurement even when the worst case and the count do not."""+ lines = sorted(f"{ratio:.2f}|" + "|".join(rest) for ratio, *rest in found)+ digest = hashlib.sha256("\n".join(lines).encode()).hexdigest()[:16]+ worst = min(found)+ return worst[1], round(worst[0], 2), len(found), digest+++def _filled_anchor_offenders():+ """``(offenders, scenarios, failing, gaps)`` for the filled-anchor+ replay (``test_filled_anchors_keep_readable_ink``); ``failing`` holds+ the failing scenarios of each KNOWN_ANCHOR_FILL_GAPS entry and ``gaps``+ their measurements (``_gap_measurement``)."""+ anchors = _anchor_class_sets()+ base = _prepare(-1, BOOTSTRAP_BTN_CSS) + _prepare(+ 0, (CSS_ROOT / "styles.css").read_text(encoding="utf-8")+ )+ root = _root_defaults()+ themes = [(None, "", [], root)]+ for path in THEME_FILES:+ css = path.read_text(encoding="utf-8")+ props = dict(root)+ props.update(_custom_properties(css))+ themes.append((path.stem, _theme_name(path), _prepare(1, css), props))+ offenders, scenarios, failing = [], set(), {}+ for name, css in _stylesheets():+ own = [] if name == "styles.css" else _prepare(2, css)+ # A template's <style> block only reaches that template's anchors.+ local = name.endswith(".html")+ parsed = list(_parse_rules(css))+ inks = {+ selector: decls["color"]+ for selector_list, decls in parsed+ if "color" in decls and not selector_list.startswith("@")+ for selector in _split_top(selector_list, ",")+ }+ for selector_list, decls in parsed:+ background = decls.get("background-color", decls.get("background"))+ if selector_list.startswith("@") or not background:+ continue+ if {"background-clip", "-webkit-background-clip"} & set(decls):+ continue+ for selector in _split_top(selector_list, ","):+ if (name, selector) in DEAD_ACCENT_RULES:+ continue+ chain_ink = next(+ (inks[s] for s in _selector_chain(selector) if s in inks),+ None,+ )+ if not _anchor_fill_trigger(background, chain_ink):+ continue+ context, subject = _subject_split(selector)+ tokens = _simples(subject)+ if not tokens or any(+ t.startswith(("::", "#")) or t in (":before", ":after")+ for t in tokens+ ):+ continue+ if tokens[0][0].isalpha() and tokens[0] != "a":+ continue+ fill_classes = {t[1:] for t in tokens if t.startswith(".")}+ if not fill_classes - _STATE_CLASSES:+ continue+ needed = {+ t[1:].partition("(")[0] for t in tokens if t.startswith(":")+ } & _INTERACTIVE+ status_gap = KNOWN_STATUS_FILL_GAPS.get((name, selector))+ mixed = _status_fill_kinds(background) - {"error"}+ for where, classes in anchors.items():+ if local and not where.startswith(f"{name}:"):+ continue+ if not fill_classes - _STATE_CLASSES <= classes:+ continue+ if _sheet_off_page(name, where):+ continue+ element = classes | fill_classes+ for state_name, state in _STATES.items():+ if not needed <= state:+ continue+ for stem, theme, rules, props in themes:+ key = (name, element, state_name, context, stem)+ if key in scenarios:+ continue+ scenarios.add(key)+ values = _cascade_winners(+ base + rules + own,+ element,+ state,+ context,+ theme,+ )+ if state & {"hover", "active"} and (+ values.get("pointer-events") == "none"+ ):+ # Not hoverable or pressable+ # (``.ldr-page-link.disabled``).+ continue+ ink = values.get("color")+ fill = values.get("background")+ if not fill:+ continue+ if (+ ink is not None+ and _ink(ink) == ACCENT_INK+ and _is_accent_fill(fill)+ ):+ # The pair test_accent_ink_contrast checks.+ continue+ # Whatever ink and fill win must read: the fill+ # composited over the page and card backgrounds+ # (a translucent or transparent winner lets them+ # show through). An ink or fill that does not+ # resolve fails.+ ink_rgb = ink and _resolve_color(_ink(ink), props)+ stops = _fill_stops(fill, props)+ where_text = (+ f"{name} {selector} on <a> {where} "+ f"[{state_name}, {stem or ':root'}]: "+ f"{ink} on {fill}"+ )+ if not ink_rgb or stops is None:+ offenders.append(f"{where_text} unresolved")+ continue+ backdrops = [+ _resolve(token, props) for token in _BACKDROPS+ ]+ worst = min(+ _contrast(ink_rgb, surface)+ for surface in _over(backdrops, stops)+ )+ if worst >= 4.5 or (+ status_gap+ and mixed+ and round(worst, 2) >= status_gap[1]+ ):+ continue+ if (+ name,+ selector,+ ) in KNOWN_ANCHOR_FILL_GAPS and _gap_exemptable(+ background+ ):+ failing.setdefault((name, selector), []).append(+ (+ worst,+ stem or ":root",+ state_name,+ " ".join(sorted(element)),+ context,+ )+ )+ continue+ offenders.append(f"{where_text} {worst:.2f}:1")+ gaps = {key: _gap_measurement(found) for key, found in failing.items()}+ return offenders, scenarios, failing, gaps+++def test_filled_anchors_keep_readable_ink():+ """Every filled control class on an ``<a>`` (templates and script+ markup) keeps a readable ink at rest, on hover, on keyboard focus, when+ visited and when pressed, in every theme and with the bare ``:root``+ palette. A filled control is any fill rule ``_anchor_fill_trigger``+ picks: accent, error, warning and success fills, any other colour or+ literal fill, and any fill paired with an on-fill ink. The cascade is+ rebuilt from Bootstrap's button rules (``BOOTSTRAP_BTN_CSS``, rank -1),+ styles.css (rank 0), the theme file (rank 1) and the sheet declaring+ the fill (rank 2): by importance, specificity and load order, so+ ``a:hover`` (0,1,1) and ``[data-theme="high-contrast"] a`` (0,1,1) beat+ a bare ``.ldr-skip-link`` (0,1,0), High Contrast's ``a:hover`` (0,2,1)+ beats ``.ldr-nav-link-btn.ldr-nav-success`` (0,2,0), and Bootstrap's+ ``.btn:focus-visible`` (0,2,0) beats ``.btn-primary`` (0,1,0).+ ``var(--bs-btn-*)`` values are resolved against the variables the same+ cascade gives the anchor (an undefined one leaves the ink unknown and+ the fill transparent). Whatever ink and fill win must reach 4.5:1 on+ every stop of the fill, composited over the page and card backgrounds+ (a translucent or transparent winner lets them show through);+ ``var(--text-on-accent)`` on an accent fill passes, since+ ``test_accent_ink_contrast`` checks that pair. An ink or fill that does+ not resolve fails. The only exemptions are a mixed status fill down to+ its KNOWN_STATUS_FILL_GAPS floor and the exact pre-existing+ measurements in KNOWN_ANCHOR_FILL_GAPS; an entry whose measurement+ changes (a failing scenario added or dropped, or its ratio moved)+ fails as stale. A sheet is not applied to an anchor in a full page+ that does not load it (``_sheet_off_page``; a template's own+ ``<style>`` block always reaches its own anchors), and a hover or+ press is not replayed on an anchor whose cascade sets+ ``pointer-events: none``.++ Limits: rules whose ancestors are neither a theme scope nor the fill's+ own ancestors are not applied (``.ldr-alert a`` inside an alert, see+ ``test_links_in_filled_containers_stay_readable``;+ ``.ldr-sidebar-nav li a``; Bootstrap's ``.btn-check + .btn``), id+ selectors never match, classes set from JavaScript after render (other+ than the state classes in ``_STATE_CLASSES``) and inline styles on the+ anchor are not seen, rules from other page sheets the same page loads+ are not combined, ``@media`` blocks are applied+ unconditionally, and Bootstrap is modelled for ``.btn`` and+ ``.btn-primary`` only (other variants and reboot's ``a`` rules are not+ transcribed). Fill rules whose subject carries no class other than the+ state classes (``a.active``, ``[aria-current]``, a type selector) are+ skipped, since no static class ties them to an anchor, and a neutral+ surface fill under a theme text ink is not a filled control."""+ offenders, scenarios, failing, gaps = _filled_anchor_offenders()+ assert len(scenarios) >= 3000, "too few filled anchors were checked"+ assert not offenders, offenders+ stale = {+ key: (recorded, gaps.get(key), sorted(failing.get(key, [])))+ for key, recorded in KNOWN_ANCHOR_FILL_GAPS.items()+ if gaps.get(key) != recorded+ }+ assert not stale, f"entries to update (recorded, now, scenarios): {stale}"+++def test_anchor_replay_covers_every_status_fill():+ """The replay reaches anchors filled with each status colour, so a+ narrowed trigger (accent and error only) fails here: the View Text+ link (success), the Metrics Cost Analytics link (success) and the+ Metrics warning-to-error link."""+ _, scenarios, _, _ = _filled_anchor_offenders()+ filled = {(name, frozenset(element)) for name, element, *_ in scenarios}+ for sheet, classes in (+ ("document_details.css", {"ldr-btn", "ldr-btn-success"}),+ ("metrics.css", {"ldr-nav-link-btn", "ldr-nav-success"}),+ ("styles.css", {"ldr-nav-link-btn", "ldr-nav-success"}),+ ("metrics.css", {"ldr-nav-link-btn", "ldr-nav-warning"}),+ ("library.css", {"ldr-action-btn", "ldr-action-btn-pdf"}),+ ):+ assert (sheet, frozenset(classes)) in filled, (sheet, classes)+ # The off-page filter only drops pairs it can prove: collection+ # details' .ldr-btn-success never reaches the document page's link.+ assert _sheet_off_page(+ "collection_details.css", "templates/pages/document_details.html:37"+ )+ assert not _sheet_off_page(+ "document_details.css", "templates/pages/document_details.html:37"+ )+ assert not _sheet_off_page(+ "collection_details.css", "static/js/collections.js:1"+ )+ assert not _sheet_off_page(+ "chat.css", "templates/pages/document_details.html:37"+ )+ # A template's own <style> block reaches its own anchors.+ assert not _sheet_off_page(+ "templates/pages/note_detail.html",+ "templates/pages/note_detail.html:1536",+ )+++def _script_pages():+ """``{script key: page keys}``: the full pages whose markup+ (``_page_closure``) names the script. A script no page names, or one+ whose file name another script or Python code mentions (so it may be+ imported or loaded from there), maps to None: its pages are+ unknown."""+ named_in_code = {}+ for path in [+ *(WEB_ROOT / "static" / "js").rglob("*.js"),+ *(REPO_ROOT / "src").rglob("*.py"),+ ]:+ for name in re.findall(r"([\w.-]+\.js)\b", path.read_text("utf-8")):+ if name != path.name:+ named_in_code[name] = True+ found = {}+ for key, path in _markup_files():+ if path.suffix != ".js":+ continue+ tail = key.removeprefix("static/")+ pages = {+ page+ for page, (_, _, scripts) in _page_closure().items()+ for ref in scripts+ if tail == ref.lstrip("./").removeprefix("static/")+ or tail.endswith("/" + ref.lstrip("./").removeprefix("static/"))+ }+ found[key] = None if not pages or path.name in named_in_code else pages+ return found+++def _anchor_pages(where):+ """The full pages an anchor at ``where`` (``file key:line``) renders on:+ the pages whose template closure holds its template, or that load its+ script (``_script_pages``); None when they are unknown (a fragment+ fetched by script, a template no page includes, a script loaded from+ other code)."""+ key = where.rpartition(":")[0]+ if key.endswith(".js"):+ pages = _script_pages().get(key)+ else:+ pages = {+ page+ for page, (_, templates, _) in _page_closure().items()+ if key in templates+ }+ return sorted(pages) if pages else None+++def _page_rules(page):+ """``_prepare(2, ...)`` rules of every stylesheet and ``<style>`` block+ that reaches ``page`` (``_page_closure``, plus the sheets named in+ code), or of every one when the page is unknown (None); styles.css is+ the replay's base and is left out."""+ if page is None:+ reach = None+ else:+ sheets, templates, _ = _page_closure()[page]+ reach = sheets | templates | _sheets_named_in_code()+ return [+ rule+ for name, css in _stylesheets()+ if name != "styles.css" and (reach is None or name in reach)+ for rule in _prepare(2, css)+ ]+++def _classed_link_subjects(selectors):+ """The ``(ancestors, subject, class set)`` of each selector whose subject+ is a classed link (``.x``, ``a.x:hover``): only classes, an ``a`` and+ pseudo-classes, with a class outside ``_STATE_CLASSES``."""+ found = []+ for ancestors, subject, _ in selectors:+ tokens = _simples(subject) or []+ if any(t[0].isalpha() and t != "a" for t in tokens):+ continue+ classes = {t[1:] for t in tokens if t.startswith(".")}+ if classes - _STATE_CLASSES:+ found.append((ancestors, subject, classes))+ return found+++def _theme_override_offenders(replace=None):+ """``(offenders, scenarios)`` for+ ``test_theme_link_overrides_read_on_every_page``; ``replace`` is an+ optional ``(theme file stem, css)`` that stands in for that theme's+ file."""+ anchors = _anchor_class_sets()+ base = _prepare(-1, BOOTSTRAP_BTN_CSS) + _prepare(+ 0, (CSS_ROOT / "styles.css").read_text(encoding="utf-8")+ )+ root = _root_defaults()+ page_rules = functools.cache(_page_rules)+ offenders, scenarios = [], set()+ for path in THEME_FILES:+ css = path.read_text(encoding="utf-8")+ if replace and replace[0] == path.stem:+ css = replace[1]+ props = dict(root)+ props.update(_custom_properties(css))+ match = re.search(r"\[data-theme=[\"']?([\w-]+)", css)+ theme = match.group(1) if match else path.stem+ theme_rules = _prepare(1, css)+ backdrops = [_resolve(token, props) for token in _BACKDROPS]+ # Theme rules that set the ink of a classed link, with the class+ # sets they need.+ overrides = [+ (index, [classes for _, _, classes in subjects])+ for index, (_, selectors, decls) in enumerate(theme_rules)+ if "color" in decls+ and (subjects := _classed_link_subjects(selectors))+ ]+ for index, _ in overrides:+ selectors = theme_rules[index][1]+ for ancestors, subject, classes in _classed_link_subjects(+ selectors+ ):+ scope = _SCOPE.fullmatch(ancestors)+ context = "" if scope and scope.group(0) else ancestors+ for where, anchor_classes in anchors.items():+ if not classes - _STATE_CLASSES <= anchor_classes:+ continue+ element = anchor_classes | classes+ # The ink before the overrides (the cascade without+ # every theme override that can reach this anchor) is+ # reported for context only; the winning ink is judged.+ dropped = {+ other+ for other, needs in overrides+ if any(+ need - _STATE_CLASSES <= anchor_classes+ for need in needs+ )+ }+ others = [+ rule+ for other, rule in enumerate(theme_rules)+ if other not in dropped+ ]+ for page in _anchor_pages(where) or [None]:+ for state_name, state in _STATES.items():+ if not _compound_matches(subject, element, state):+ continue+ key = (path.stem, subject, where, page, state_name)+ scenarios.add(key)+ sheet_rules = page_rules(page)+ values = _cascade_winners(+ base + theme_rules + sheet_rules,+ element,+ state,+ context,+ theme,+ )+ if state & {"hover", "active"} and (+ values.get("pointer-events") == "none"+ ):+ continue+ before = _cascade_winners(+ base + others + sheet_rules,+ element,+ state,+ context,+ theme,+ )+ ink = values.get("color")+ fill = values.get("background")+ if (+ ink is not None+ and fill+ and _ink(ink) == ACCENT_INK+ and _is_accent_fill(fill)+ ):+ continue++ def worst(ink, fill):+ rgb = ink and _resolve_color(_ink(ink), props)+ stops = _fill_stops(fill, props) if fill else []+ if not rgb or stops is None:+ return None+ return min(+ _contrast(rgb, surface)+ for surface in _over(backdrops, stops)+ )++ now = worst(ink, fill)+ was = worst(+ before.get("color"), before.get("background")+ )+ text = (+ f"{path.name} {ancestors} {subject} on <a> "+ f"{where} (page {page or 'unknown'}) "+ f"[{state_name}]: {ink} on {fill or 'the page'}"+ )+ if now is None:+ offenders.append(f"{text} unresolved")+ elif now < 4.5:+ offenders.append(+ f"{text} {now:.2f}:1 (was "+ f"{'unresolved' if was is None else f'{was:.2f}:1'})"+ )+ return offenders, scenarios+++def test_theme_link_overrides_read_on_every_page():+ """A theme rule that sets the ink of a classed link (High Contrast's+ keep-ink overrides, ``a.btn-primary:hover``) applies on every page,+ to every ``<a>`` carrying its classes, not only on the page whose+ sheet fills that class: a class name two sheets give different+ meanings (an accent chip on one page, a plain text link on another)+ gets the override's on-fill ink on both. For each such rule, each+ anchor it matches, each full page the anchor renders on+ (``_anchor_pages``; every sheet when unknown) and each interaction+ state, the cascade is replayed with that page's sheets combined+ (``_page_rules``); wherever the override decides the ink, the ink must+ reach 4.5:1 on the winning fill composited over the page and card+ backgrounds, or on those backgrounds alone when nothing fills the+ link. Wherever the override matches, the winning ink is judged, even+ when another override gives the same ink; there is no "no worse than+ before" exemption. An ink or fill+ that does not resolve fails.++ Limits: sheets combined for one page are applied in name order, not+ load order; an anchor whose pages are unknown gets every sheet at+ once, so another page's fill for the same class can stand in for the+ one it really renders on; a fill or link colour set on an ancestor container is not+ seen (the backdrops stand in for it); an override with an ancestor+ other than the theme scope is applied as if the ancestor matched."""+ offenders, scenarios = _theme_override_offenders()+ assert len(scenarios) >= 100, "too few theme overrides were replayed"+ assert not offenders, offenders+++def test_theme_link_override_replay_judges_duplicate_overrides():+ """Two theme rules giving the same link the same on-fill ink both+ decide it: neither is skipped because the other already sets that+ ink. Moving High Contrast's chip override back onto the plain+ ``.ldr-research-link`` and adding a second, unqualified copy fails."""+ path = next(p for p in THEME_FILES if p.stem == "high-contrast")+ css = path.read_text(encoding="utf-8")+ assert "a.ldr-research-chip:hover" in css+ mutated = css.replace(+ "a.ldr-research-chip:hover", "a.ldr-research-link:hover"+ ) + (+ '\n[data-theme="high-contrast"] .ldr-research-link:hover {\n'+ " color: var(--text-on-accent);\n}\n"+ )+ offenders, _ = _theme_override_offenders(("high-contrast", mutated))+ assert any("ldr-research-link:hover" in o for o in offenders)+ assert any(+ ".ldr-research-link:hover on" in o and "a.ldr-research" not in o+ for o in offenders+ )+++def test_theme_override_replay_reaches_every_page_of_a_class():+ """The override replay sees an anchor on each page it renders on: the+ skip link (base.html) on the Metrics page, and a script-built anchor on+ the page that loads the script."""+ _, scenarios = _theme_override_offenders()+ seen = {(where, page) for _, _, where, page, _ in scenarios}+ pages = {page for _, page in seen}+ assert "templates/pages/metrics.html" in pages+ assert any(+ where.startswith("templates/base.html:")+ and page.endswith("metrics.html")+ for where, page in seen+ if page+ )+ assert _anchor_pages("static/js/pages/link_analytics_render.js:1") == [+ "templates/pages/link_analytics.html"+ ]+ assert _anchor_pages("templates/pages/cost_analytics.html:1") == [+ "templates/pages/cost_analytics.html"+ ]+++def test_alert_wrapped_collection_links_keep_accent_ink():+ """The create and upload result links (collection_create.js,+ collection_upload.js) are ``.ldr-btn-collections-primary`` anchors inside+ an ``.ldr-alert``, whose ``.ldr-alert a`` (0,1,1) and ``.ldr-alert+ a:hover`` (0,2,1) colours the sweep above does not apply."""+ sources = {+ name: text+ for name, text in _stylesheets()+ if name in ("styles.css", "collection_details.css")+ }+ assert ".ldr-alert a:hover" in _strip_comments(sources["styles.css"])+ base = _prepare(0, sources["styles.css"])+ own = _prepare(2, sources["collection_details.css"])+ element = frozenset({"ldr-btn-collections", "ldr-btn-collections-primary"})+ offenders = []+ themes = [(None, "", [])] + [+ (+ path.stem,+ _theme_name(path),+ _prepare(1, path.read_text(encoding="utf-8")),+ )+ for path in THEME_FILES+ ]+ for state_name, state in _STATES.items():+ for stem, theme, theme_rules in themes:+ ink, fill = _cascade(+ base + theme_rules + own, element, state, ".ldr-alert", theme+ )+ assert fill and _is_accent_fill(fill), (state_name, stem, fill)+ if ink is None or _ink(ink) != ACCENT_INK:+ offenders.append(f"{state_name} {stem or ':root'}: {ink}")+ assert not offenders, offenders+++def test_anchor_scan_finds_accent_controls():+ """An empty scan would make the cascade check pass vacuously."""+ anchors = _anchor_class_sets()+ seen = set().union(*anchors.values())+ assert {+ "ldr-skip-link",+ "ldr-btn-collections-primary",+ "ldr-action-btn-rag",+ "ldr-page-link",+ "btn-primary",+ } <= seen+ created = [+ where+ for where in anchors+ if where.startswith("static/js/components/annotation_surface.js")+ ]+ assert created, "createElement('a') anchors are not scanned"+++# --- Links inside filled containers ----------------------------------------+#+# A container filled from a status token (an alert's warning tint, the news+# priority banner's solid warning fill) styles its links with ``.box a``+# (0,1,1), which a theme's ``a:hover`` (0,2,1) or the container's own+# ``.box a:hover`` can recolour. The check below replays the cascade for the+# links in every such container.++_STATUS_TOKENS = frozenset(+ {+ "accent-primary",+ "accent-secondary",+ "accent-tertiary",+ "warning-color",+ "success-color",+ "error-color",+ }+)+# The surfaces a container sits on: the page and a card.+_BACKDROPS = ("bg-primary", "bg-secondary")+_RGBA_TOKEN = re.compile(+ r"rgba?\(\s*var\(--([\w-]+)-rgb\)\s*(?:,\s*([\d.]+)\s*)?\)"+)+_LINK_SUBJECT = re.compile(r"a(?::[\w-]+(?:\([^()]*\))?)*")++# Classed links rendered inside a container (beside a bare ``<a>``, which+# every container is checked with): research_form.js's action link,+# collection_create.js's result buttons, news.js's progress link.+IN_CONTAINER_ANCHORS = {+ "ldr-alert": [+ frozenset({"ldr-alert-action"}),+ frozenset({"ldr-btn-collections", "ldr-btn-collections-primary"}),+ frozenset({"ldr-btn-collections", "ldr-btn-collections-secondary"}),+ ],+ "ldr-priority-alert": [frozenset({"ms-2"})],+}++# Pre-existing link gaps: (theme, container class or modifier, ink) ->+# the worst ratio measured for that ink over the container's fill (across+# the links, states, fills and backdrops checked). Only that exact triple+# is exempt, and only down to its recorded ratio; any other ink, container+# or theme, or a lower ratio, fails. An entry that is no longer observed,+# or whose ratio has changed, fails as stale so the list stays exact. The+# accent ink and the status inks (FILL_INKS) are never exempt.+KNOWN_LINK_GAPS = {+ # --text-primary is the lightest ink these themes define, so no token+ # reads better on their 10-20% status tints over --bg-secondary.+ ("everforest-dark", "ldr-alert-info", "var(--text-primary)"): 4.48,+ ("everforest-dark", "ldr-alert-success", "var(--text-primary)"): 4.38,+ ("everforest-dark", "ldr-alert-warning", "var(--text-primary)"): 4.28,+ ("one-dark", "ldr-alert-success", "var(--text-primary)"): 4.34,+ ("one-dark", "ldr-alert-warning", "var(--text-primary)"): 4.16,+ ("palenight", "ldr-alert-danger", "var(--text-primary)"): 4.40,+ ("palenight", "ldr-alert-info", "var(--text-primary)"): 3.42,+ ("palenight", "ldr-alert-success", "var(--text-primary)"): 3.33,+ ("palenight", "ldr-alert-warning", "var(--text-primary)"): 3.44,+ # settings.css .ldr-community-note a draws --accent-tertiary, which in+ # these themes is under 4.5:1 on the bare page already (2.13:1 in+ # midnight); the note's 8% accent tint lowers it a little further.+ ("everforest-dark", "ldr-community-note", "var(--accent-tertiary)"): 4.28,+ ("flexoki-dark", "ldr-community-note", "var(--accent-tertiary)"): 3.96,+ ("gruvbox-dark", "ldr-community-note", "var(--accent-tertiary)"): 3.83,+ ("lavender", "ldr-community-note", "var(--accent-tertiary)"): 2.25,+ ("midnight", "ldr-community-note", "var(--accent-tertiary)"): 1.73,+ ("nord", "ldr-community-note", "var(--accent-tertiary)"): 2.16,+ ("rose", "ldr-community-note", "var(--accent-tertiary)"): 3.10,+ ("solarized-dark", "ldr-community-note", "var(--accent-tertiary)"): 3.67,+}+++# Colour syntax _COLOR_STOP does not read: colour functions other than+# rgb()/rgba(), currentColor, and the CSS named colours other than white,+# black and transparent. A fill using any of them is unresolved rather+# than read as drawing nothing.+_NAMED_COLORS = frozenset(+ """aliceblue antiquewhite aqua aquamarine azure beige bisque+ blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse+ chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan+ darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta+ darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen+ darkslateblue darkslategray darkslategrey darkturquoise darkviolet+ deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite+ forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green+ greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender+ lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan+ lightgoldenrodyellow lightgray lightgreen lightgrey lightpink+ lightsalmon lightseagreen lightskyblue lightslategray lightslategrey+ lightsteelblue lightyellow lime limegreen linen magenta maroon+ mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen+ mediumslateblue mediumspringgreen mediumturquoise mediumvioletred+ midnightblue mintcream mistyrose moccasin navajowhite navy oldlace+ olive olivedrab orange orangered orchid palegoldenrod palegreen+ paleturquoise palevioletred papayawhip peachpuff peru pink plum+ powderblue purple rebeccapurple red rosybrown royalblue saddlebrown+ salmon sandybrown seagreen seashell sienna silver skyblue slateblue+ slategray slategrey snow springgreen steelblue tan teal thistle tomato+ turquoise violet wheat whitesmoke yellow yellowgreen""".split()+)+_UNREAD_COLOR = re.compile(+ r"(?<![\w-])(?:(?:hsla?|hwb|lab|lch|oklab|oklch|color|color-mix|"+ r"light-dark)\(|currentcolor(?![\w-])|(?:"+ + "|".join(sorted(_NAMED_COLORS))+ + r")(?![\w-]))",+ re.IGNORECASE,+)+++def _fill_stops(value, props):+ """``[(rgb, alpha)]`` for each colour stop of a fill (the alternatives a+ gradient draws), ``[]`` when it draws nothing, ``None`` when a stop+ does not resolve under ``props`` or the fill uses a colour syntax the+ stop pattern does not read (``hsl()``, ``color-mix()``, a named+ colour; see ``_UNREAD_COLOR``)."""+ value = _ink(value)+ if value in ("transparent", "none", "inherit", "initial", "unset"):+ return []+ # url(...) and var() names cannot hold a colour the check would miss.+ bare = re.sub(r"url\([^()]*\)|var\(--[\w-]+", " ", value)+ if _UNREAD_COLOR.search(bare):+ return None+ stops = []+ for stop in _COLOR_STOP.findall(value):+ if stop == "transparent":+ continue+ rgba = _RGBA_TOKEN.fullmatch(stop)+ literal = _parse_color(stop)+ if rgba:+ rgb = _resolve_color(f"var(--{rgba.group(1)})", props)+ alpha = float(rgba.group(2)) if rgba.group(2) else 1.0+ elif literal:+ rgb, alpha = literal+ else:+ rgb, alpha = _resolve_color(stop, props), 1.0+ if rgb is None:+ return None+ stops.append((rgb, alpha))+ return stops+++def _over(backgrounds, stops):+ if not stops:+ return backgrounds+ return [+ tuple(alpha * f + (1 - alpha) * b for f, b in zip(rgb, background))+ for background in backgrounds+ for rgb, alpha in stops+ ]+++def _status_fill(value):+ tokens = re.findall(r"var\(--([\w-]+?)(?:-rgb)?\)", _ink(value))+ accent, _, _ = _aliases()+ return bool(tokens) and all(+ token in _STATUS_TOKENS or token in accent for token in tokens+ )+++def _filled_link_containers():+ """``{container class: [(link sheet css, fill sheet css, modifier)]}``:+ the containers whose links a stylesheet styles (``.box a``,+ ``.box a:hover``) and whose fill, set on the container class or on a+ ``.box-*`` modifier, draws a status token."""+ sources = list(_stylesheets())+ link_sheets = {}+ for _, css in sources:+ for selector_list, decls in _parse_rules(css):+ if selector_list.startswith("@") or not _TRACKED & set(decls):+ continue+ for selector in _split_top(selector_list, ","):+ context, subject = _subject_split(selector)+ if re.fullmatch(+ r"\.[\w-]+", context+ ) and _LINK_SUBJECT.fullmatch(subject):+ link_sheets.setdefault(context[1:], []).append(css)+ found = {}+ for container, sheets in link_sheets.items():+ own = re.compile(rf"\.({re.escape(container)}(?:-[\w-]+)?)")+ for _, css in sources:+ for selector_list, decls in _parse_rules(css):+ background = decls.get(+ "background-color", decls.get("background")+ )+ if not background or not _status_fill(background):+ continue+ for selector in _split_top(selector_list, ","):+ match = own.fullmatch(selector)+ if not match:+ continue+ modifier = match.group(1)+ for link_css in dict.fromkeys(sheets):+ found.setdefault(container, []).append(+ (link_css, css, modifier)+ )+ return found+++def _container_link_offenders():+ base = _prepare(0, (CSS_ROOT / "styles.css").read_text(encoding="utf-8"))+ styles = (CSS_ROOT / "styles.css").read_text(encoding="utf-8")+ root = _root_defaults()+ themes = [(None, "", [], root)]+ for path in THEME_FILES:+ css = path.read_text(encoding="utf-8")+ props = dict(root)+ props.update(_custom_properties(css))+ themes.append((path.stem, _theme_name(path), _prepare(1, css), props))+ sheets = [css for name, css in _stylesheets() if not name.endswith(".html")]+ offenders, gaps, checked = [], {}, 0+ for container, pairs in _filled_link_containers().items():+ links = [frozenset(), *IN_CONTAINER_ANCHORS.get(container, [])]+ for link_css, fill_css, modifier in dict.fromkeys(pairs):+ box = frozenset({container, modifier})+ for stem, theme, theme_rules, props in themes:+ backdrops = [_resolve(name, props) for name in _BACKDROPS]+ outer_rules = (+ base+ + theme_rules+ + [+ rule+ for css in dict.fromkeys((fill_css, link_css))+ if css != styles+ for rule in _prepare(2, css)+ ]+ )+ outer = _cascade_winners(+ outer_rules, box, frozenset(), "", theme, "div"+ )+ box_ink = outer.get("color") or "var(--text-primary)"+ box_fill = outer.get("background") or ""+ box_stops = _fill_stops(box_fill, props)+ if box_stops is None:+ offenders.append(+ f".{modifier} [{stem or ':root'}]: unresolved fill "+ f"{box_fill}"+ )+ continue+ if not box_stops:+ # The cascade leaves this container unfilled here.+ continue+ surfaces = _over(backdrops, box_stops)+ for classes in links:+ # A classed link also takes the rules of the sheets that+ # style its classes (collection_details.css's buttons).+ rules = outer_rules + [+ rule+ for css in sheets+ if css not in (styles, fill_css, link_css)+ and any(+ re.search(rf"\.{re.escape(c)}(?![\w-])", css)+ for c in classes+ )+ for rule in _prepare(2, css)+ ]+ for state_name, state in _STATES.items():+ values = _cascade_winners(+ rules, classes, state, f".{container}", theme+ )+ ink = values.get("color")+ if ink is None or _ink(ink) in (+ "inherit",+ "currentColor",+ ):+ ink = box_ink+ where = (+ f".{modifier} a.{'.'.join(sorted(classes))} "+ f"[{state_name}, {stem or ':root'}]"+ )+ ink_rgb = _resolve_color(_ink(ink), props)+ link_stops = _fill_stops(+ values.get("background") or "", props+ )+ if ink_rgb is None or link_stops is None:+ offenders.append(f"{where}: unresolved {ink}")+ continue+ checked += 1+ own_fill = values.get("background")+ if (+ _ink(ink) == ACCENT_INK+ and own_fill+ and _is_accent_fill(_ink(own_fill))+ and all(a == 1 for _, a in link_stops)+ ):+ # Accent ink on an opaque accent fill: the pair+ # test_accent_ink_contrast checks.+ worst = 21.0+ else:+ worst = min(+ _contrast(ink_rgb, surface)+ for surface in _over(surfaces, link_stops)+ )+ if worst < 4.5:+ key = (stem, modifier, _ink(ink))+ floor = KNOWN_LINK_GAPS.get(key)+ if (+ floor is not None+ and _ink(ink) not in FILL_INKS+ and round(worst, 2) >= floor+ ):+ gaps[key] = min(gaps.get(key, 21.0), worst)+ else:+ offenders.append(+ f"{where}: {ink} {worst:.2f}:1"+ )+ outline = values.get("outline")+ if "focus" not in state or not outline:+ continue+ if "currentcolor" in outline.lower():+ ring = ink_rgb+ else:+ stops = _COLOR_STOP.findall(_ink(outline))+ ring = stops and _resolve_color(stops[0], props)+ if not ring:+ continue+ worst = min(_contrast(ring, s) for s in surfaces)+ if worst < 3:+ offenders.append(+ f"{where}: focus outline {outline} {worst:.2f}:1"+ )+ return offenders, gaps, checked+++def test_links_in_filled_containers_stay_readable():+ """Links inside a container filled from a status token (``.ldr-alert``+ and its tints, ``.ldr-priority-alert``) keep at least 4.5:1 against the+ container's fill, composited over the page and card backgrounds, at+ rest, on hover, on keyboard focus, when visited and when pressed, in+ every theme; a focus outline keeps 3:1. A link or container fill that+ does not resolve fails. The only exemptions are the exact pre-existing+ (theme, container, ink) gaps in KNOWN_LINK_GAPS, each down to its+ recorded ratio. The cascade is styles.css+ (rank 0), the theme (rank 1), and the sheets declaring the link rule+ and the fill (rank 2), so ``[data-theme="high-contrast"] a:hover``+ (0,2,1) meets ``.ldr-priority-alert a`` (0,1,1). An ``inherit`` ink+ takes the container's.++ Limits: containers are found from ``.box a`` rules with a single-class+ ancestor and a fill on ``.box`` or a ``.box-*`` modifier; the classed+ links checked besides a bare ``<a>`` are those in IN_CONTAINER_ANCHORS;+ nested containers and the page's own fills under the backdrop tokens+ are not modelled."""+ offenders, gaps, checked = _container_link_offenders()+ assert checked >= 1000, "too few container links were checked"+ assert not offenders, offenders+ stale = {+ key: (floor, round(gaps[key], 2) if key in gaps else None)+ for key, floor in KNOWN_LINK_GAPS.items()+ if key not in gaps or round(gaps[key], 2) != floor+ }+ assert not stale, (+ f"KNOWN_LINK_GAPS entries to update (recorded, now): {stale}"+ )+++def test_container_link_scan_finds_the_alerts():+ """An empty scan would make the container check pass vacuously."""+ found = _filled_link_containers()+ assert {"ldr-alert", "ldr-priority-alert"} <= set(found)+ modifiers = {+ modifier for pairs in found.values() for _, _, modifier in pairs+ }+ assert {"ldr-alert-warning", "ldr-alert-danger", "ldr-priority-alert"} <= (+ modifiers+ )+ seen = set().union(*_anchor_class_sets().values())+ listed = set().union(+ *(set().union(*v) for v in IN_CONTAINER_ANCHORS.values())+ )+ assert listed <= seen, listed - seendiff --git a/tests/theme_tests/test_control_affordances.py b/tests/theme_tests/test_control_affordances.pynew file mode 100644index 0000000000..1634fb864f--- /dev/null+++ b/tests/theme_tests/test_control_affordances.py@@ -0,0 +1,131 @@+# allow: no-sut-import — guardian; statically parses shipped CSS/templates+# for missing-control regressions rather than exercising Python code+"""Controls the light-theme pass restored must stay visible.++- Downloads and Library filter selects keep a native dropdown arrow (Bootstrap's+ ``.form-control`` removes it and nothing draws a replacement).+- The Downloads search input's left padding must beat the filter-group+ padding shorthand, or the search icon overlaps the placeholder.+- Font Awesome icon classes must not carry the ``ldr-`` prefix+ (``fa-ldr-star`` renders nothing); Metrics shows real stars.+"""++import re+from pathlib import Path++import pytest++WEB_ROOT = (+ Path(__file__).resolve().parents[2] / "src" / "local_deep_research" / "web"+)+CSS_ROOT = WEB_ROOT / "static" / "css"+TEMPLATES = WEB_ROOT / "templates"+++def _strip_comments(css: str) -> str:+ return re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)+++def _declarations(block: str) -> dict[str, str]:+ decls = {}+ for part in block.split(";"):+ prop, sep, value = part.partition(":")+ if sep:+ decls[prop.strip().lower()] = " ".join(value.split())+ return decls+++def _rules(css: str):+ """Yield (index, selector, declarations) for flat (non-nested) rules."""+ for index, match in enumerate(+ re.finditer(r"([^{}]*)\{([^{}]*)\}", _strip_comments(css))+ ):+ selector = " ".join(match.group(1).split())+ for part in selector.split(","):+ yield index, part.strip(), _declarations(match.group(2))+++def _specificity(selector: str) -> tuple[int, int, int]:+ """Specificity of a simple selector (no :not()/:is() arguments)."""+ ids = len(re.findall(r"#[\w-]+", selector))+ classes = len(+ re.findall(r"\.[\w-]+|\[[^\]]*\]|(?<!:):(?!:)[\w-]+", selector)+ )+ stripped = re.sub(r"#[\w-]+|\.[\w-]+|\[[^\]]*\]|::?[\w-]+", " ", selector)+ elements = len(re.findall(r"(?<![\w-])[a-zA-Z][\w-]*", stripped))+ return ids, classes, elements+++def _download_css() -> str:+ return (CSS_ROOT / "download_manager.css").read_text(encoding="utf-8")+++ "template,stylesheet",+ [+ ("download_manager.html", "download_manager.css"),+ ("library.html", "library.css"),+ ],+)+def test_filter_selects_keep_native_arrow(template, stylesheet):+ markup = (TEMPLATES / "pages" / template).read_text(encoding="utf-8")+ # Premise: the filters are Bootstrap form-control selects inside+ # .ldr-filter-group, and the page loads the stylesheet checked below.+ assert re.search(r'<select id="filter-[\w-]+" class="form-control"', markup)+ assert f"/static/css/{stylesheet}" in markup++ appearance = [+ (index, decls["appearance"])+ for index, selector, decls in _rules(+ (CSS_ROOT / stylesheet).read_text(encoding="utf-8")+ )+ if "appearance" in decls+ and re.search(r"\.ldr-filter-group\b.*\bselect\b", selector)+ ]+ assert appearance, (+ f"{stylesheet} must restore the native arrow on "+ ".ldr-filter-group selects (appearance: auto)"+ )+ assert max(appearance)[1] == "auto"+++def test_download_search_padding_clears_icon():+ padding_rules = [+ (_specificity(selector), index, selector, decls)+ for index, selector, decls in _rules(_download_css())+ if (+ ".ldr-search-wrapper" in selector or ".ldr-filter-group" in selector+ )+ and ("padding" in decls or "padding-left" in decls)+ and ("input" in selector or ".form-control" in selector)+ and "select" not in selector+ ]+ search = [+ rule for rule in padding_rules if ".ldr-search-wrapper" in rule[2]+ ]+ assert search, "no padding rule for the Downloads search input found"+ winner = max(padding_rules, key=lambda rule: (rule[0], rule[1]))+ assert ".ldr-search-wrapper" in winner[2], (+ f"{winner[2]!r} overrides the search input padding, so the search "+ "icon overlaps the placeholder"+ )+ left = winner[3].get("padding-left", "")+ assert left.endswith("px") and int(left[:-2]) >= 30, left+++def test_no_ldr_prefixed_font_awesome_icons():+ offenders = []+ for path in list(TEMPLATES.rglob("*.html")) + list(+ (WEB_ROOT / "static" / "js").rglob("*.js")+ ):+ if "node_modules" in path.parts:+ continue+ text = path.read_text(encoding="utf-8", errors="ignore")+ if re.search(r"\bfa-ldr-[\w-]+", text):+ offenders.append(path.relative_to(WEB_ROOT).as_posix())+ assert not offenders, f"invalid fa-ldr-* icon classes in {offenders}"+++def test_metrics_satisfaction_uses_star_icon():+ markup = (TEMPLATES / "pages" / "metrics.html").read_text(encoding="utf-8")+ assert len(re.findall(r'class="fas fa-star"', markup)) >= 2diff --git a/tests/theme_tests/test_light_theme_contrast.py b/tests/theme_tests/test_light_theme_contrast.pynew file mode 100644index 0000000000..652c6de089--- /dev/null+++ b/tests/theme_tests/test_light_theme_contrast.py@@ -0,0 +1,336 @@+"""Light palettes must stay readable on cards, inputs and tinted status panels."""++import re+from pathlib import Path++import pytest++from local_deep_research.web.themes import theme_registry+from local_deep_research.web.themes.loader import ThemeLoader+from local_deep_research.web.themes.schema import (+ LIGHT_THEME_REQUIRED_VARIABLES,+)++# Use the same discovery and classification as the rendered theme selector.+LIGHT_THEMES = sorted(+ (+ theme+ for theme in theme_registry.themes.values()+ if theme.type == "light"+ ),+ key=lambda theme: theme.id,+)+++def test_light_themes_are_discovered():+ """An empty LIGHT_THEMES would make the parametrized check below skip+ ("got empty parameter set") instead of failing, e.g. if frontmatter+ parsing broke and every theme fell back to type "dark"."""+ assert "sepia" in {theme.id for theme in LIGHT_THEMES}+ assert len(LIGHT_THEMES) >= 2+++def _rgb(color):+ return tuple(int(color[index : index + 2], 16) for index in (1, 3, 5))+++def _luminance(rgb):+ channels = [channel / 255 for channel in rgb]+ linear = [+ channel / 12.92+ if channel <= 0.04045+ else ((channel + 0.055) / 1.055) ** 2.4+ for channel in channels+ ]+ return sum(+ value * weight+ for value, weight in zip(linear, (0.2126, 0.7152, 0.0722))+ )+++def _contrast(foreground, background):+ dark, light = sorted((_luminance(foreground), _luminance(background)))+ return (light + 0.05) / (dark + 0.05)++[email protected]("theme", LIGHT_THEMES, ids=lambda theme: theme.id)+def test_light_theme_text_contrast(theme):+ """Normal text needs 4.5:1 even on the darkest input/card surface."""+ assert theme.css_path is not None+ # Ignore commented-out declarations: the browser does, so a token that+ # only exists inside /* */ must count as missing here too.+ css = re.sub(+ r"/\*.*?\*/",+ "",+ theme.css_path.read_text(encoding="utf-8"),+ flags=re.DOTALL,+ )+ colors = {+ key: _rgb(value)+ for key, value in re.findall(r"--([\w-]+):\s*(#[\da-fA-F]{6});", css)+ }+ # Dark palettes inherit these from styles.css; light palettes must not.+ missing = [+ var+ for var in LIGHT_THEME_REQUIRED_VARIABLES+ if var.removeprefix("--") not in colors+ ]+ assert not missing, (+ f"light theme {theme.id} must define {missing} as #rrggbb "+ "(see LIGHT_THEME_REQUIRED_VARIABLES in web/themes/schema.py)"+ )+ # Tints are drawn from the --*-rgb twins; they must match the hex tokens+ # this test checks, or a darkened hex would pass while pills render the+ # old color.+ triplets = {+ key: tuple(int(part) for part in value.split(","))+ for key, value in re.findall(+ r"--([\w-]+)-rgb:\s*(\d+\s*,\s*\d+\s*,\s*\d+)\s*;", css+ )+ }+ for token in (+ "accent-primary",+ "accent-secondary",+ "accent-tertiary",+ "success-color",+ "warning-color",+ "error-color",+ ):+ assert token in triplets, f"{theme.id} must define --{token}-rgb"+ assert triplets[token] == colors[token], (+ f"{theme.id}: --{token}-rgb {triplets[token]} does not match "+ f"--{token} {colors[token]}"+ )+ backgrounds = [+ colors[f"bg-{surface}"]+ for surface in ("primary", "secondary", "tertiary")+ ]+ # Essential control boundaries must remain visible independently of text.+ for background in backgrounds:+ assert _contrast(colors["control-border"], background) >= 3.0++ text_tokens = (+ "text-primary",+ "text-secondary",+ "text-muted",+ "accent-primary",+ "accent-secondary",+ "accent-tertiary",+ "success-color",+ "warning-color",+ "error-color",+ )+ for token in text_tokens:+ for background in backgrounds:+ assert _contrast(colors[token], background) >= 4.5, token++ # Alerts, status pills and selected controls tint the surface with their+ # own ink (rgba(var(--token-rgb), alpha) behind color: var(--token)).+ # This models the strongest *flat, same-rule* tint of that shape found in+ # the component CSS for each token (a stronger tint lowers contrast, so+ # weaker flat tints of that shape are covered too). Most of these surfaces+ # (status pills, settings alerts) only appear with data or after an+ # action, so the rendered axe run cannot be relied on for them. The+ # browser composites to 8-bit channels, so check the rounded blend too.+ #+ # Known gaps, NOT modelled here (pre-existing, accent-primary ink on a+ # stronger gradient tint of itself, most below 4.5:1 on bg-tertiary but+ # rendered on lighter card surfaces):+ # notes.css .ldr-note-tag (20% gradient stop),+ # notes.css .ldr-similarity-badge (15%),+ # note_detail.html .ldr-note-tag / .ldr-wiki-link (15%, :hover 25%),+ # note_detail.html .ldr-suggested-tag:hover (success-color, 25%).+ # Tints whose ink and background come from different rules are modelled+ # only where listed in SPLIT_RULE_HIGHLIGHTS below.+ strongest_self_tint = {+ "accent-primary": 0.12, # .ldr-tag+ "accent-tertiary": 0.2, # .ldr-status-indicator, settings alert+ "success-color": 0.2, # .ldr-status-indicator, settings alert+ "warning-color": 0.2, # settings .ldr-alert-warning+ "error-color": 0.2, # .ldr-status-indicator, settings alert+ }+ for token, alpha in strongest_self_tint.items():+ ink = colors[token]+ for background in backgrounds:+ tinted = tuple(+ alpha * fg + (1 - alpha) * bg for fg, bg in zip(ink, background)+ )+ for surface in (tinted, tuple(round(c) for c in tinted)):+ assert _contrast(ink, surface) >= 4.5, (+ f"{token} on a {alpha:.0%} tint of its own color"+ )++ # Existing filled controls use white labels; warning badges have a token.+ for token in (+ "accent-primary",+ "accent-secondary",+ "accent-tertiary",+ "success-color",+ "error-color",+ ):+ assert _contrast((255, 255, 255), colors[token]) >= 4.5, (+ f"label on {token}"+ )+ assert _contrast(colors["text-on-warning"], colors["warning-color"]) >= 4.5+ assert _contrast(colors["text-on-error"], colors["error-color"]) >= 4.5+ assert _contrast(colors["text-on-success"], colors["success-color"]) >= 4.5+++CSS_ROOT = (+ Path(__file__).resolve().parents[2]+ / "src"+ / "local_deep_research"+ / "web"+ / "static"+ / "css"+)++# Search-match highlights whose ink, list surface, row tint and highlight+# tint come from different rules (and files). Each entry names+# (file, selector, property) for: the ink, the list surface, the+# hover/active row tint the highlight stacks on, and the highlight tint.+SPLIT_RULE_HIGHLIGHTS = {+ "custom dropdown filter highlight": {+ "ink": (+ "styles.css",+ ".ldr-custom-dropdown-item .ldr-highlight",+ "color",+ ),+ "surface": (+ "custom_dropdown.css",+ ".ldr-custom-dropdown-list",+ "background-color",+ ),+ "row_tint": (+ "custom_dropdown.css",+ ".ldr-custom-dropdown-item.active",+ "background-color",+ ),+ "tint": (+ "custom_dropdown.css",+ ".ldr-custom-dropdown-item .ldr-highlight",+ "background-color",+ ),+ },+ "note wiki-link picker highlight": {+ "ink": ("notes.css", ".ldr-wiki-link-item-title", "color"),+ "surface": ("notes.css", ".ldr-wiki-link-dropdown", "background"),+ "row_tint": ("notes.css", ".ldr-wiki-link-item.active", "background"),+ "tint": (+ "notes.css",+ ".ldr-wiki-link-item-title .ldr-highlight",+ "background",+ ),+ },+}+++def _css_values(filename, selector, prop):+ """Every value ``prop`` takes in a rule listing ``selector``."""+ css = re.sub(+ r"/\*.*?\*/",+ "",+ (CSS_ROOT / filename).read_text(encoding="utf-8"),+ flags=re.DOTALL,+ )+ values = []+ for match in re.finditer(r"([^{}]*)\{([^{}]*)\}", css):+ selectors = [+ " ".join(part.split()) for part in match.group(1).split(",")+ ]+ if selector not in selectors:+ continue+ for decl in match.group(2).split(";"):+ name, sep, value = decl.partition(":")+ if sep and name.strip().lower() == prop:+ values.append(" ".join(value.split()))+ assert values, f"{filename}: no {prop} in a rule for {selector!r}"+ return values+++def _token(filename, selector, prop):+ tokens = {+ match.group(1)+ for value in _css_values(filename, selector, prop)+ for match in [re.match(r"var\(--([\w-]+)", value)]+ if match+ }+ assert len(tokens) == 1, (+ f"{filename} {selector} {prop}: expected one var(--token), "+ f"got {_css_values(filename, selector, prop)}"+ )+ return tokens.pop()+++def _accent_tint(filename, selector, prop):+ """Strongest rgba(var(--accent-primary-rgb), a) alpha for the rule."""+ alphas = []+ for value in _css_values(filename, selector, prop):+ match = re.fullmatch(+ r"rgba\(\s*var\(--accent-primary-rgb\)\s*,\s*([\d.]+)\s*\)"+ r"(?:\s*!important)?",+ value,+ )+ assert match, (+ f"{filename} {selector} {prop}: {value!r} is not a flat "+ "accent-primary tint; update SPLIT_RULE_HIGHLIGHTS"+ )+ alphas.append(float(match.group(1)))+ return max(alphas)+++def _blend(foreground, background, alpha):+ return tuple(+ alpha * fg + (1 - alpha) * bg for fg, bg in zip(foreground, background)+ )++[email protected]("theme", LIGHT_THEMES, ids=lambda theme: theme.id)[email protected]("name", sorted(SPLIT_RULE_HIGHLIGHTS))+def test_split_rule_highlight_contrast(theme, name):+ """A search-match highlight must stay 4.5:1 on its tint, including when+ the tint stacks on the hovered/active row's own accent tint."""+ spec = SPLIT_RULE_HIGHLIGHTS[name]+ css = re.sub(+ r"/\*.*?\*/",+ "",+ theme.css_path.read_text(encoding="utf-8"),+ flags=re.DOTALL,+ )+ colors = {+ key: _rgb(value)+ for key, value in re.findall(r"--([\w-]+):\s*(#[\da-fA-F]{6});", css)+ }+ ink = colors[_token(*spec["ink"])]+ surface = colors[_token(*spec["surface"])]+ accent = colors["accent-primary"]+ row_alpha = _accent_tint(*spec["row_tint"])+ tint_alpha = _accent_tint(*spec["tint"])+ for under in (surface, _blend(accent, surface, row_alpha)):+ for rounded in (False, True):+ base = tuple(round(c) for c in under) if rounded else under+ tinted = _blend(accent, base, tint_alpha)+ if rounded:+ tinted = tuple(round(c) for c in tinted)+ ratio = _contrast(ink, tinted)+ assert ratio >= 4.5, (+ f"{name}: {ratio:.2f}:1 on a {tint_alpha:.0%} accent tint "+ f"(row tint {row_alpha:.0%}) in {theme.id}"+ )+++def test_declared_custom_properties_matches_real_declarations_only():+ """The loader's light-theme warning relies on this declaration scan."""+ loader = ThemeLoader(Path(__file__).parent)+ declared = loader.declared_custom_properties(+ '[data-theme="x"] { --control-border: #111; --text-on-warning: #fff; }'+ "\n.y {\n --a: #111;\n border: 1px solid var(--used-only);\n"+ " --control-border-hover: #222;\n}\n"+ "/* --commented-out: #333; */",+ )+ assert declared == {+ "--control-border",+ "--text-on-warning",+ "--a",+ "--control-border-hover",+ }diff --git a/tests/theme_tests/test_select_forced_colors.py b/tests/theme_tests/test_select_forced_colors.pynew file mode 100644index 0000000000..1fe2526468--- /dev/null+++ b/tests/theme_tests/test_select_forced_colors.py@@ -0,0 +1,221 @@+# allow: no-sut-import — guardian; statically parses the shipped CSS files+# for a forced-colors regression rather than exercising Python production code+"""Custom select chevrons must survive Windows High Contrast (forced colors).++``select.ldr-form-control`` and ``.ldr-settings-select`` remove the native+arrow with ``appearance: none`` and draw their own chevron from+``linear-gradient`` layers. Forced-colors mode computes every non-``url()``+``background-image`` to ``none``, so without a fallback those selects lose+their only arrow there. Each stylesheet must hand the arrow back to the+platform inside ``@media (forced-colors: active)``.++The themed modal close icons draw their X from ``::before``/``::after`` bars+painted with ``background: currentColor``. Forced-colors mode repaints+background-color with Canvas, which would erase the X, so those bars must+opt out and paint in a system text color there.+"""++import re+from pathlib import Path++import pytest++CSS_ROOT = (+ Path(__file__).resolve().parents[2]+ / "src"+ / "local_deep_research"+ / "web"+ / "static"+ / "css"+)++JS_ROOT = CSS_ROOT.parent / "js"++GRADIENT_CHEVRON_SELECTS = [+ ("styles.css", "select.ldr-form-control"),+ ("settings.css", ".ldr-settings-select"),+]++FORCED_COLORS_MEDIA = re.compile(+ r"@media\s*\(\s*forced-colors\s*:\s*active\s*\)\s*\{"+)+++def _strip_comments(css: str) -> str:+ return re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)+++def _declarations(block: str) -> dict[str, str]:+ decls = {}+ for part in block.split(";"):+ prop, sep, value = part.partition(":")+ if sep:+ decls[prop.strip().lower()] = " ".join(value.split())+ return decls+++def _top_level_rules(css: str):+ """Yield (selector, body) for rules outside any at-rule block."""+ depth = 0+ start = 0+ selector = ""+ for index, char in enumerate(css):+ if char == "{":+ if depth == 0:+ selector = " ".join(css[start:index].split())+ body_start = index + 1+ depth += 1+ elif char == "}":+ depth -= 1+ if depth == 0:+ yield selector, css[body_start:index]+ start = index + 1+++def _forced_colors_rules(css: str):+ for selector, body in _top_level_rules(css):+ if FORCED_COLORS_MEDIA.match(selector + "{"):+ yield from _top_level_rules(body)+++ "filename,selector",+ GRADIENT_CHEVRON_SELECTS,+ ids=[f"{f}:{s}" for f, s in GRADIENT_CHEVRON_SELECTS],+)+def test_gradient_chevron_select_has_forced_colors_fallback(filename, selector):+ css = _strip_comments((CSS_ROOT / filename).read_text(encoding="utf-8"))++ # Guard the premise: the base rule still draws a non-url() chevron on an+ # appearance:none select. If that changes, revisit this test.+ base = [+ _declarations(body)+ for sel, body in _top_level_rules(css)+ if sel == selector+ and "linear-gradient" in _declarations(body).get("background-image", "")+ ]+ assert base, f"{filename}: gradient chevron rule for {selector} not found"+ assert base[-1].get("appearance") == "none"++ fallbacks = [+ _declarations(body)+ for sel, body in _forced_colors_rules(css)+ if selector in [part.strip() for part in sel.split(",")]+ ]+ assert fallbacks, (+ f"{filename}: {selector} needs an @media (forced-colors: active) "+ "rule restoring the native arrow"+ )+ assert any(+ decls.get("appearance") == "auto"+ or "url(" in decls.get("background-image", "")+ for decls in fallbacks+ ), (+ f"{filename}: forced-colors rule for {selector} must set "+ "appearance: auto (or a url() chevron)"+ )+++def _followup_modal_css() -> str:+ source = (JS_ROOT / "followup.js").read_text(encoding="utf-8")+ match = re.search(+ r"<style id=\"followup-modal-styles\">(.*?)</style>", source, re.DOTALL+ )+ assert match, "followup.js: followup-modal-styles <style> block not found"+ return match.group(1)+++def _notes_css() -> str:+ return (CSS_ROOT / "notes.css").read_text(encoding="utf-8")+++# (label, CSS source loader, close-button selector)+BAR_DRAWN_CLOSE_ICONS = [+ ("notes.css", _notes_css, ".ldr-btn-close-white"),+ ("followup.js", _followup_modal_css, "#followUpModal .btn-close"),+]++SYSTEM_TEXT_COLORS = {"canvastext", "buttontext"}+++ "label,load_css,selector",+ BAR_DRAWN_CLOSE_ICONS,+ ids=[f"{label}:{selector}" for label, _, selector in BAR_DRAWN_CLOSE_ICONS],+)+def test_bar_drawn_close_icon_survives_forced_colors(label, load_css, selector):+ css = _strip_comments(load_css())+ bars = (f"{selector}::before", f"{selector}::after")++ # Guard the premise: the X is drawn from background-painted pseudo bars.+ base = [+ _declarations(body)+ for sel, body in _top_level_rules(css)+ if all(bar in [part.strip() for part in sel.split(",")] for bar in bars)+ ]+ assert base, f"{label}: pseudo-element bars for {selector} not found"+ assert base[-1].get("background") == "currentColor"++ for bar in bars:+ fallbacks = [+ _declarations(body)+ for sel, body in _forced_colors_rules(css)+ if bar in [part.strip() for part in sel.split(",")]+ ]+ assert any(+ decls.get("forced-color-adjust") == "none"+ and decls.get("background", "").lower() in SYSTEM_TEXT_COLORS+ for decls in fallbacks+ ), (+ f"{label}: {bar} needs an @media (forced-colors: active) rule "+ "with forced-color-adjust: none and a system text color "+ "background (CanvasText), or the X vanishes in High Contrast"+ )+++def _leaf_rules(css: str):+ """Yield (selector parts, declarations) for every innermost rule,+ including rules nested in @media blocks."""+ for match in re.finditer(r"([^{}]*)\{([^{}]*)\}", css):+ parts = [" ".join(part.split()) for part in match.group(1).split(",")]+ yield parts, _declarations(match.group(2))+++ "label,load_css,selector",+ BAR_DRAWN_CLOSE_ICONS,+ ids=[f"{label}:{selector}" for label, _, selector in BAR_DRAWN_CLOSE_ICONS],+)+def test_bar_drawn_close_icon_is_not_filtered(label, load_css, selector):+ """The original bug: ``filter: invert(...)`` on the button turned the X+ white on the light modal. Computed colors ignore ``filter``, so the+ rendered contrast check cannot see it; forbid it statically here."""+ css = _strip_comments(load_css())+ # A selector part targets the close button (or its bars/states) if it+ # contains the close selector not followed by more of an identifier.+ targets = re.compile(re.escape(selector) + r"(?![\w-])")+ offenders = []+ base_filters = []+ for parts, decls in _leaf_rules(css):+ hits = [part for part in parts if targets.search(part)]+ if not hits:+ continue+ for prop in ("filter", "--bs-btn-close-filter"):+ value = decls.get(prop)+ if value is None:+ continue+ if selector in parts and prop == "filter":+ base_filters.append(value)+ if value.lower() != "none":+ offenders.append((hits, prop, value))+ assert not offenders, (+ f"{label}: {selector} must not be filtered (a filter such as "+ f"invert() recolors the X past every computed-color check): "+ f"{offenders}"+ )+ # Bootstrap's .btn-close sets filter: var(--bs-btn-close-filter), and+ # .btn-close-white / dark-mode rules can set an invert; the base rule+ # must pin it off explicitly rather than rely on the cascade.+ assert base_filters == ["none"], (+ f"{label}: {selector} must declare filter: none (got {base_filters})"+ )diff --git a/tests/theme_tests/test_warning_surface_ink.py b/tests/theme_tests/test_warning_surface_ink.pynew file mode 100644index 0000000000..2e52b54374--- /dev/null+++ b/tests/theme_tests/test_warning_surface_ink.py@@ -0,0 +1,260 @@+# allow: no-sut-import — guardian; statically parses the shipped CSS files+# for a warning-ink regression rather than exercising Python production code+"""A filled warning surface must use the warning ink token, not a literal.++test_light_theme_contrast.py checks the *values* themes assign to+--warning-color and --text-on-warning, but the component CSS (news.css,+styles.css, ...) only ever writes the tokens, e.g.+``background: var(--warning-color); color: var(--text-on-warning);``. A+regression there -- reverting to a literal ``color: #000`` or ``color:+white`` -- can't be caught by computing contrast from theme files, because+the literal never appears in any theme; it appears in the component+stylesheet itself. This statically greps every component stylesheet under+``web/static/css`` for rules whose background is exactly+``var(--warning-color)`` and asserts the same rule pairs it with the warning+ink token. Warning surfaces styled from template ``<style>`` blocks or JS+inline styles are outside this sweep.++Selectors this repo already knows don't need (or can't yet have) that+pairing are excluded explicitly below, with a reason, instead of silently+skipping or asserting something unverified about them.+"""++import re+from pathlib import Path++import pytest++CSS_ROOT = (+ Path(__file__).resolve().parents[2]+ / "src"+ / "local_deep_research"+ / "web"+ / "static"+ / "css"+)++# Git-ignored ``themes.css``, written by the FastAPI lifespan+# (``web/fastapi_app.py``) from ``themes/*/*.css`` on every boot: it exists+# only once the app has started (e.g. in CI), and duplicates the theme+# sources out of scope. test_accent_ink_contrast guards that it is generated.+GENERATED_SHEETS = {"themes.css"}++WARNING_INK_TOKEN = "var(--text-on-warning)"++# (relative CSS path, selector) -> why it's excluded from the "must use+# var(--text-on-warning)" rule below, instead of just being silently+# skipped or force-asserted as correct.+ALLOWLIST: dict[tuple[str, str], str] = {+ # Pre-existing rules #6684 did not touch (its diff only reworked+ # news.css/styles.css warning surfaces). They use+ # `var(--bg-primary)` as a knockout ink, or have no text content at+ # all (a decorative dot/underline). Neither claim has been verified+ # against every theme's actual colors here, so they're excluded+ # rather than asserted as passing.+ (+ "collection_details.css",+ ".ldr-btn-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "collection_details.css",+ ".ldr-stat-warning::before",+ ): "decorative, no text",+ (+ "collection_details.css",+ ".ldr-badge-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "collection_details.css",+ ".ldr-btn-collections-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "collection_details.css",+ ".ldr-btn-outline-warning:hover",+ ): "pre-existing, out of scope for #6684",+ (+ "benchmark.css",+ ".ldr-processing-status.ldr-processing",+ ): "pre-existing, out of scope for #6684",+ (+ "subscriptions.css",+ ".ldr-status-indicator.ldr-checking",+ ): "decorative dot, no text",+ (+ "collections.css",+ ".ldr-btn-collections-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "collections.css",+ ".ldr-btn-outline-warning:hover",+ ): "pre-existing, out of scope for #6684",+ (+ "download_manager.css",+ ".ldr-download-buttons .btn.btn-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "download_manager.css",+ ".ldr-download-buttons .btn.btn-warning:hover:not(:disabled)",+ ): "no color override in this rule",+ (+ "download_manager.css",+ ".ldr-research-actions .btn.btn-warning",+ ): "pre-existing, out of scope for #6684",+ (+ "download_manager.css",+ ".ldr-research-actions .btn.btn-warning:hover:not(:disabled)",+ ): "no color override in this rule",+ (+ "document_details.css",+ ".ldr-badge-warning",+ ): "pre-existing, out of scope for #6684",+ # #6684 reverted this rule's ink back to its pre-PR literal because+ # `.ldr-library-status-bar .badge-warning` (no `ldr-` prefix) is never+ # emitted by any template or JS -- the rendered badge is+ # `ldr-badge ldr-badge-warning`, styled by styles.css instead.+ (+ "library.css",+ ".ldr-library-status-bar .badge-warning",+ ): "dead selector (see styles.css .ldr-badge-warning for the live rule)",+}++# Selectors this test must positively confirm use the warning ink token --+# the ones #6684 fixed. If any of these silently drops out of the sweep+# (e.g. the rule is deleted or the selector text changes) the coverage+# check below fails loudly instead of the sweep just going quiet.+REQUIRED_SELECTORS: set[tuple[str, str]] = {+ ("news.css", ".ldr-priority-alert"),+ ("news.css", ".ldr-history-status.ldr-status-in_progress"),+ ("styles.css", ".ldr-metrics-btn-overflow .ldr-badge-overflow"),+ # news.js currently emits the unprefixed `impact-medium`, so this rule+ # is not rendered yet (#6821); it is inked now so fixing the class name+ # cannot ship dark text on the darkened light-theme warning fill.+ ("news.css", ".ldr-impact-medium"),+ # benchmark.html renders "<n> results" in this badge; the base rule's+ # white ink was ~1.1-3.2:1 on the dark themes' bright warning fill.+ ("benchmark.css", ".ldr-search-count-badge.ldr-warning"),+}+++def _strip_comments(css: str) -> str:+ return re.sub(r"/\*.*?\*/", "", css, flags=re.DOTALL)+++def _declarations(decl_block: str) -> dict[str, str]:+ """Parse `prop: value;` pairs from one rule body into a dict."""+ decls = {}+ for part in decl_block.split(";"):+ part = part.strip()+ if not part or ":" not in part:+ continue+ prop, _, value = part.partition(":")+ decls[prop.strip().lower()] = " ".join(value.split())+ return decls+++def _iter_rules(css: str):+ """Yield (selector, declarations) for every leaf `sel { decls }` block.++ Repeatedly peels off the innermost (no nested `{`) block so arbitrary+ nesting (e.g. an `@media` wrapper) doesn't confuse a flat regex: once a+ leaf is removed, its wrapper's own text becomes a (harmless,+ declaration-less) leaf on the next pass.+ """+ leaf = re.compile(r"([^{}]*)\{([^{}]*)\}")+ remaining = css+ while True:+ match = leaf.search(remaining)+ if not match:+ return+ selector = " ".join(match.group(1).split())+ yield selector, _declarations(match.group(2))+ remaining = remaining[: match.start()] + remaining[match.end() :]+++def _iter_warning_background_rules():+ """Yield (relative_path, selector, declarations) for every rule whose+ background/background-color is exactly `var(--warning-color)`."""+ for path in sorted(CSS_ROOT.rglob("*.css")):+ if path.relative_to(CSS_ROOT).as_posix() in GENERATED_SHEETS:+ continue+ css = _strip_comments(path.read_text(encoding="utf-8"))+ for selector, decls in _iter_rules(css):+ if not selector:+ continue+ background = decls.get("background") or decls.get(+ "background-color"+ )+ if background == "var(--warning-color)":+ yield path.relative_to(CSS_ROOT).as_posix(), selector, decls+++WARNING_BACKGROUND_RULES = list(_iter_warning_background_rules())+++def test_found_warning_background_rules():+ """Sanity check the parser itself still finds rules to check."""+ assert WARNING_BACKGROUND_RULES, (+ "no `background: var(--warning-color)` rule found under "+ f"{CSS_ROOT}; either the parser regressed or every such rule was "+ "removed (update this test either way)"+ )+++ "path,selector,decls",+ WARNING_BACKGROUND_RULES,+ ids=[f"{p}:{s}" for p, s, _ in WARNING_BACKGROUND_RULES],+)+def test_warning_background_pairs_with_warning_ink(path, selector, decls):+ """Every non-allowlisted `background: var(--warning-color)` rule must+ also set `color: var(--text-on-warning)` in the same rule."""+ reason = ALLOWLIST.get((path, selector))+ if reason is not None:+ pytest.skip(reason)+ assert decls.get("color") == WARNING_INK_TOKEN, (+ f"{path}: {selector!r} sets background: var(--warning-color) but "+ f"color is {decls.get('color')!r}, not {WARNING_INK_TOKEN!r}. "+ "If this is intentional (dead code, decorative, or a "+ "pre-existing/out-of-scope pattern), add it to ALLOWLIST with a "+ "reason instead of a literal color."+ )+++def test_required_selectors_are_covered_and_passing():+ """The selectors #6684 fixed stay both present and correctly inked."""+ found = {+ (path, selector): decls+ for path, selector, decls in WARNING_BACKGROUND_RULES+ }+ missing = REQUIRED_SELECTORS - found.keys()+ assert not missing, (+ f"expected warning-background rules not found: {missing}"+ )+ for key in REQUIRED_SELECTORS:+ assert found[key].get("color") == WARNING_INK_TOKEN, (+ f"{key} must set color: {WARNING_INK_TOKEN}"+ )+++def test_allowlist_entries_are_not_stale():+ """Each allowlisted selector must still be a warning-background rule, so+ a renamed or deleted rule cannot leave a silent exemption behind."""+ found = {(path, selector) for path, selector, _ in WARNING_BACKGROUND_RULES}+ stale = sorted(set(ALLOWLIST) - found)+ assert not stale, (+ "ALLOWLIST entries no longer match any `background: "+ f"var(--warning-color)` rule; remove or update them: {stale}"+ )+++def test_priority_alert_link_inherits_alert_ink():+ """`.ldr-priority-alert a` must inherit its parent's ink, not hardcode+ a fixed color that could drift out of sync with the alert background."""+ css = _strip_comments((CSS_ROOT / "news.css").read_text(encoding="utf-8"))+ rules = dict(_iter_rules(css))+ decls = rules.get(".ldr-priority-alert a")+ assert decls is not None, ".ldr-priority-alert a rule not found in news.css"+ assert decls.get("color") == "inherit", (+ ".ldr-priority-alert a must set color: inherit so it always "+ f"matches .ldr-priority-alert's ink; got {decls.get('color')!r}"+ )diff --git a/tests/ui_tests/test_egress_policy_ui.js b/tests/ui_tests/test_egress_policy_ui.jsindex 68e73d1c19..4b9b8f5928 100644--- a/tests/ui_tests/test_egress_policy_ui.js+++ b/tests/ui_tests/test_egress_policy_ui.js@@ -536,19 +536,37 @@ async function main() {});// ------------------------------------------------------------ // 11. Privacy panel header icon adopts the scope cue+ // 11. Privacy panel frame carries the scope cue; the header keeps+ // theme text so it stays readable on every palette.// ------------------------------------------------------------ await run('11. Privacy panel header reflects scope colour', async () => {+ await run('11. Privacy panel frame shows scope, header uses theme text', async () => {await selectScope(page, 'private_only');- const headerColor = await page.evaluate(() => {- const el = document.querySelector('.ldr-privacy-panel-header');- if (!el) return null;- return window.getComputedStyle(el).color;+ await sleep(300); // panel border-color transition is 0.15s+ const panel = await page.evaluate(() => {+ const el = document.querySelector('.ldr-privacy-panel');+ const header = document.querySelector('.ldr-privacy-panel-header');+ if (!el || !header) return null;+ // Resolve --text-primary to a computed rgb() for comparison.+ const probe = document.createElement('span');+ probe.style.color = 'var(--text-primary)';+ el.appendChild(probe);+ const textPrimary = window.getComputedStyle(probe).color;+ probe.remove();+ return {+ border: window.getComputedStyle(el).borderTopColor,+ header: window.getComputedStyle(header).color,+ textPrimary,+ };});record(- 'header-color-set',- !!headerColor && headerColor !== 'rgb(0, 0, 0)',- `header.color=${headerColor}`,+ 'panel-frame-private',+ !!panel && panel.border === SCOPE_PALETTE.private_only.border,+ `panel.border=${panel && panel.border}`,+ );+ record(+ 'header-uses-theme-text',+ !!panel && panel.header === panel.textPrimary,+ `header.color=${panel && panel.header} text-primary=${panel && panel.textPrimary}`,);await screenshot(page, '11-panel-header-private');});diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.pyindex 4959eeea6d..976e05e508 100644--- a/tests/web/test_js_fetch_parity.py+++ b/tests/web/test_js_fetch_parity.py@@ -962,7 +962,7 @@ LIVE_CASES = (bad={"engineId": "zzz_no_such_engine"},),LiveCase(- js_ref="followup.js:279",+ js_ref="followup.js:312",method="POST",url="/api/followup/prepare",good={"parent_research_id": NOPE_UUID, "question": "q"},