Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

chore(templates): remove the unused render_setting macro (#6484)

Huang-404-Q4fcb1b54eeb5
diff --git a/src/local_deep_research/web/templates/components/settings_form.html b/src/local_deep_research/web/templates/components/settings_form.html
deleted file mode 100644
index 92f8a2c0b8..0000000000
--- a/src/local_deep_research/web/templates/components/settings_form.html
+++ /dev/null
@@ -1,336 +0,0 @@
-{% macro render_setting(setting, id_prefix="") %}
- {% set setting_id = (id_prefix ~ "-" if id_prefix else "") ~ setting.key|replace(".", "-") %}
-
- <div class="ldr-settings-item form-group" data-key="{{ setting.key }}">
- <div class="ldr-settings-item-header">
- <label for="{{ setting_id }}">{{ setting.name }}</label>
- {% if setting.description %}
- <span class="ldr-settings-tooltip" title="{{ setting.description }}">
- <i aria-hidden="true" class="fas fa-info-circle"></i>
- </span>
- {% endif %}
- </div>
-
- {% if setting.ui_element == "textarea" %}
- {# Check if this is JSON content that should be expanded into controls #}
- {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
- <div class="ldr-json-expanded-controls">
- {% if setting.value is string %}
- {% set json_value = setting.value|tojson %}
- {% else %}
- {% set json_value = setting.value %}
- {% endif %}
-
- {# Store the original JSON in a hidden field #}
- <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">
-
- {# Create individual form controls for each JSON property #}
- <div class="ldr-json-property-controls">
- {% for key, value in json_value.items() %}
- <div class="ldr-json-property-item">
- <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>
-
- {% if value is boolean %}
- <div class="ldr-checkbox-label">
- <!-- Hidden input ensures unchecked state is submitted -->
- <input type="hidden"
- name="{{ setting.key }}_{{ key }}"
- id="{{ setting_id }}_{{ key }}_hidden_fallback"
- value="false"
- class="ldr-checkbox-hidden-fallback">
-
- <!-- Actual checkbox overrides hidden input when checked -->
- <input type="checkbox"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- value="true"
- class="ldr-json-property-control ldr-settings-checkbox"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"
- {% if value %}checked{% endif %}
- {% if not setting.editable %}disabled{% endif %}>
- <label for="{{ setting_id }}_{{ key }}" class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</label>
- </div>
- {% elif value is number %}
- <input type="number"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- class="ldr-settings-input ldr-form-control ldr-json-property-control"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- value="{{ value }}"
- {% if not setting.editable %}disabled{% endif %}>
- {% elif value is string and value in ["ITERATION", "NONE"] %}
- <select id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- class="ldr-settings-select ldr-form-control ldr-json-property-control"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- {% if not setting.editable %}disabled{% endif %}>
- <option value="ITERATION" {% if value == "ITERATION" %}selected{% endif %}>Iteration</option>
- <option value="NONE" {% if value == "NONE" %}selected{% endif %}>None</option>
- </select>
- {% else %}
- <input type="text"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- class="ldr-settings-input ldr-form-control ldr-json-property-control"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- value="{{ value }}"
- {% if not setting.editable %}disabled{% endif %}>
- {% endif %}
-
- <div class="ldr-input-help">{{ key|replace("_", " ")|title }}</div>
- </div>
- {% endfor %}
- </div>
- </div>
- {% else %}
- <textarea
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-textarea ldr-form-control"
- {% if not setting.editable %}disabled{% endif %}
- >{{ setting.value if setting.value is not none else "" }}</textarea>
- {% endif %}
-
- {% elif setting.ui_element == "select" %}
- {% if setting.key == "llm.provider" %}
- {% from "components/custom_dropdown.html" import render_dropdown %}
- {{ render_dropdown(
- input_id=setting.key,
- dropdown_id=setting_id + "-dropdown",
- placeholder="Select a provider",
- label=None,
- help_text=setting.description if setting.description else None,
- allow_custom=False,
- show_refresh=True,
- data_setting_key=setting.key
- ) }}
- {% else %}
- <select
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-select ldr-form-control"
- {% if not setting.editable %}disabled{% endif %}
- >
- {% for option in setting.options %}
- {% if option is mapping %}
- <option
- value="{{ option.value }}"
- {% if option.value == setting.value %}selected{% endif %}
- >
- {{ option.label if option.label else option.value }}
- </option>
- {% else %}
- <option
- value="{{ option }}"
- {% if option == setting.value %}selected{% endif %}
- >
- {{ option }}
- </option>
- {% endif %}
- {% endfor %}
- </select>
- {% endif %}
-
- {% elif setting.ui_element == "checkbox" %}
- <div class="ldr-checkbox-label">
- <!-- Hidden input ensures unchecked state is submitted -->
- <input type="hidden"
- name="{{ setting.key }}"
- id="{{ setting_id }}_hidden_fallback"
- value="false"
- class="ldr-checkbox-hidden-fallback">
-
- <!-- Actual checkbox overrides hidden input when checked -->
- <input type="checkbox"
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- value="true"
- {% if setting.value == true or setting.value == "true" %}checked{% endif %}
- {% if not setting.editable %}disabled{% endif %}
- class="ldr-settings-checkbox"
- data-hidden-fallback="{{ setting_id }}_hidden_fallback">
- <label for="{{ setting_id }}" class="ldr-checkbox-text">{{ setting.name }}</label>
- </div>
-
- {% elif setting.ui_element == "slider" or setting.ui_element == "range" %}
- {% set min_value = setting.min_value if setting.min_value is not none else 0 %}
- {% set max_value = setting.max_value if setting.max_value is not none else 100 %}
- {% set step = setting.step if setting.step is not none else 1 %}
-
- <div class="ldr-settings-range-container">
- <input
- type="range"
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-range ldr-form-control"
- value="{{ setting.value if setting.value is not none else min_value }}"
- min="{{ min_value }}"
- max="{{ max_value }}"
- step="{{ step }}"
- {% if not setting.editable %}disabled{% endif %}
- >
- <span class="ldr-settings-range-value" id="{{ setting_id }}-value">{{ setting.value if setting.value is not none else min_value }}</span>
- </div>
-
- {% elif setting.ui_element == "number" %}
- {% set min_value = setting.min_value if setting.min_value is not none else "" %}
- {% set max_value = setting.max_value if setting.max_value is not none else "" %}
- {% set step = setting.step if setting.step is not none else 1 %}
-
- <input
- type="number"
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-input ldr-form-control"
- value="{{ setting.value if setting.value is not none else '' }}"
- min="{{ min_value }}"
- max="{{ max_value }}"
- step="{{ step }}"
- {% if not setting.editable %}disabled{% endif %}
- >
-
- {% elif setting.ui_element == "password" %}
- {# Render password inputs empty so the saved value never enters
- the HTML source (anyone with View Source on the settings page
- otherwise reads plaintext API keys). The placeholder
- telegraphs configuration state without leaking the secret's
- length. autocomplete="new-password" is the standard
- cross-browser opt-out from password-manager autofill on
- settings forms. To unset a password setting, clear the
- source env var or use settings import — submitting an empty
- value is a no-op enforced by the route handler. #}
- {% set _has_value = setting.value is not none and setting.value != "" %}
- <input
- type="password"
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-input ldr-form-control"
- value=""
- autocomplete="new-password"
- placeholder="{{ '(saved — type to change)' if _has_value else '(not configured)' }}"
- {% if not setting.editable %}disabled{% endif %}
- >
-
- {% elif setting.key == "llm.model" or setting.key == "search.tool" %}
- {% from "components/custom_dropdown.html" import render_dropdown %}
- {{ render_dropdown(
- input_id=setting.key,
- dropdown_id=setting_id + "-dropdown",
- placeholder="Select or enter a value",
- label=None,
- help_text=setting.description if setting.description else None,
- allow_custom=setting.key == "llm.model",
- show_refresh=True,
- refresh_aria_label="Refresh model list" if setting.key == "llm.model" else "Refresh search engine list",
- data_setting_key=setting.key
- ) }}
- {% if setting.key == "llm.model" %}
- <span class="ldr-input-warning"
- id="llm.model-empty-warning"
- role="status"
- aria-live="polite"
- style="display: none;">
- <i class="fas fa-exclamation-triangle" aria-hidden="true"></i>
- No model selected. Choose a model from the list, or type one supported by your provider.
- </span>
- {% endif %}
-
- {% else %}
- {% if setting.value is mapping or (setting.value is string and (setting.value.startswith('{') and setting.value.endswith('}'))) %}
- <div class="ldr-json-expanded-controls">
- {% if setting.value is string %}
- {% set json_value = setting.value|tojson %}
- {% else %}
- {% set json_value = setting.value %}
- {% endif %}
-
- {# Store the original JSON in a hidden field #}
- <input type="hidden" id="{{ setting_id }}_original" name="{{ setting.key }}_original" value="{{ setting.value|tojson }}">
-
- {# Create individual form controls for each JSON property #}
- <div class="ldr-json-property-controls">
- {% for key, value in json_value.items() %}
- <div class="ldr-json-property-item">
- <label for="{{ setting_id }}_{{ key }}">{{ key|replace("_", " ")|title }}</label>
-
- {% if value is boolean %}
- <div class="ldr-checkbox-label">
- <!-- Hidden input ensures unchecked state is submitted -->
- <input type="hidden"
- name="{{ setting.key }}_{{ key }}"
- id="{{ setting_id }}_{{ key }}_hidden_fallback"
- value="false"
- class="ldr-checkbox-hidden-fallback">
-
- <!-- Actual checkbox overrides hidden input when checked -->
- <input type="checkbox"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- value="true"
- class="ldr-json-property-control ldr-settings-checkbox"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- data-hidden-fallback="{{ setting_id }}_{{ key }}_hidden_fallback"
- {% if value %}checked{% endif %}
- {% if not setting.editable %}disabled{% endif %}>
- <label for="{{ setting_id }}_{{ key }}" class="ldr-checkbox-text">{{ key|replace("_", " ")|title }}</label>
- </div>
- {% elif value is number %}
- <input type="number"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- class="ldr-settings-input ldr-form-control ldr-json-property-control"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- value="{{ value }}"
- {% if not setting.editable %}disabled{% endif %}>
- {% else %}
- <input type="text"
- id="{{ setting_id }}_{{ key }}"
- name="{{ setting.key }}_{{ key }}"
- class="ldr-settings-input ldr-form-control ldr-json-property-control"
- data-property="{{ key }}"
- data-parent-key="{{ setting.key }}"
- value="{{ value }}"
- {% if not setting.editable %}disabled{% endif %}>
- {% endif %}
-
- <div class="ldr-input-help">{{ key|replace("_", " ")|title }}</div>
- </div>
- {% endfor %}
- </div>
- </div>
- {% else %}
- <input
- type="text"
- id="{{ setting_id }}"
- name="{{ setting.key }}"
- class="ldr-settings-input ldr-form-control"
- value="{{ setting.value if setting.value is not none else '' }}"
- {% if not setting.editable %}disabled{% endif %}
- >
- {% endif %}
- {% endif %}
-
- {% if setting.description and setting.key != "llm.model" and setting.key != "search.tool" and setting.key != "llm.provider" %}
- <div class="ldr-input-help">{{ setting.description }}</div>
- {% endif %}
-
- {% if setting.key == "notifications.service_url" %}
- <div class="ldr-settings-test-button-container">
- <button type="button"
- id="test-notification-button"
- class="btn btn-secondary btn-sm"
- {% if not setting.value or setting.value.strip() == "" %}disabled{% endif %}>
- <i aria-hidden="true" class="fas fa-paper-plane"></i> Test Notification
- </button>
- <div id="test-notification-result" class="ldr-test-result" style="display: none;"></div>
- </div>
- {% endif %}
- </div>
-{% endmacro %}
diff --git a/src/local_deep_research/web/templates/settings_dashboard.html b/src/local_deep_research/web/templates/settings_dashboard.html
index 04f713bf24..e140371379 100644
--- a/src/local_deep_research/web/templates/settings_dashboard.html
+++ b/src/local_deep_research/web/templates/settings_dashboard.html
@@ -1,5 +1,9 @@
{% extends "base.html" %}
-{% from "components/settings_form.html" import render_setting %}
+
+{# Settings render client-side from the redacted /settings/api response, so this
+ page has no server-side settings markup. Any new server-side setting markup
+ must keep values out of HTML attributes; the |tojson-in-attribute census test
+ guards that. #}
{% set active_page = 'settings' %}
diff --git a/tests/js/components/settings-masked-input.test.js b/tests/js/components/settings-masked-input.test.js
new file mode 100644
index 0000000000..39caf38db3
--- /dev/null
+++ b/tests/js/components/settings-masked-input.test.js
@@ -0,0 +1,164 @@
+/**
+ * A password setting must render empty in the live settings dashboard, with the
+ * configured state telegraphed by its placeholder rather than its value.
+ *
+ * This is the client-side counterpart of the macro deleted in #6328
+ * (templates/components/settings_form.html, with
+ * tests/web/templates/test_settings_form_password_render.py). The settings page
+ * renders client-side from the redacted /settings/api response, so the contract
+ * lives in settings.js now — and until this file existed, nothing asserted it.
+ * A change there that echoed the stored value, or dropped the input to
+ * type="text", would have regressed secret handling with no test failing.
+ */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const flushPromises = async (turns = 12) => {
+ for (let turn = 0; turn < turns; turn += 1) await Promise.resolve();
+};
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function setting(overrides) {
+ return {
+ category: 'general',
+ description: '',
+ editable: true,
+ max_value: null,
+ min_value: null,
+ options: null,
+ step: null,
+ visible: true,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.ui;
+ delete window.modelProvidersRequestInProgress;
+ delete window.searchEnginesRequestInProgress;
+ delete window.modelDropdownsInitialized;
+ delete window.searchEngineDropdownInitialized;
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+ document.body.replaceChildren();
+});
+
+it('renders password settings empty and telegraphs their state in the placeholder', async () => {
+ vi.useFakeTimers();
+ document.head.insertAdjacentHTML(
+ 'beforeend',
+ '<meta name="csrf-token" content="csrf-settings-password">',
+ );
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <input id="settings-search">
+ <button type="button" class="ldr-settings-tab active" data-tab="all">All</button>
+ <div id="settings-alert"></div>
+ <div id="settings-content"></div>
+ <button id="reset-to-defaults-button" type="button">Reset defaults</button>
+ <button id="toggle-raw-config" type="button"><span id="toggle-text"></span></button>
+ <section id="raw-config" style="display: none">
+ <textarea id="raw_config_editor"></textarea>
+ </section>
+ <div id="llm.model-empty-warning" style="display: none"></div>
+ </form>
+ `;
+
+ const settings = {
+ // Configured: the API hands back the redacted sentinel, never plaintext.
+ 'llm.openai.api_key': setting({
+ category: 'llm',
+ name: 'OpenAI API Key',
+ type: 'LLM',
+ ui_element: 'password',
+ value: '[REDACTED]',
+ description: 'Authentication key for OpenAI',
+ }),
+ // Never configured.
+ 'search.brave.api_key': setting({
+ category: 'search',
+ name: 'Brave API Key',
+ type: 'SEARCH',
+ ui_element: 'password',
+ value: '',
+ }),
+ };
+
+ const fetchMock = vi.fn((url) => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(jsonResponse({ status: 'success', settings }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ return Promise.resolve(jsonResponse({ providers: {}, provider_options: [] }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
+ return Promise.resolve(jsonResponse({ engine_options: [] }));
+ }
+ if (url === '/settings/api/data-location') {
+ return Promise.resolve(jsonResponse({
+ data_directory: '/tmp/ldr',
+ security_notice: { encrypted: false },
+ }));
+ }
+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
+ return Promise.resolve(jsonResponse({ enabled: false, count: 0, backups: [] }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ window.ui = { showMessage: vi.fn() };
+ window.matchMedia = vi.fn(() => ({ matches: false }));
+ window.setupCustomDropdown = vi.fn((input) => ({
+ setValue: vi.fn(value => {
+ input.value = value;
+ }),
+ }));
+ window.updateDropdownOptions = vi.fn();
+
+ await import('@js/components/settings.js');
+ if (document.readyState === 'loading') {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+ await flushPromises();
+ await vi.advanceTimersByTimeAsync(301);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('setting-llm-openai-api_key')).not.toBeNull();
+ expect(document.getElementById('setting-search-brave-api_key')).not.toBeNull();
+ });
+
+ const configured = document.getElementById('setting-llm-openai-api_key');
+ const unconfigured = document.getElementById('setting-search-brave-api_key');
+
+ for (const input of [configured, unconfigured]) {
+ expect(input.type).toBe('password');
+ expect(input.getAttribute('autocomplete')).toBe('new-password');
+ // Empty, always: writing the stored value (or the sentinel) into the
+ // field would persist it on the next save.
+ expect(input.value).toBe('');
+ }
+
+ // The state is carried by the placeholder, which leaks neither the value
+ // nor its length.
+ expect(configured.placeholder).toContain('saved');
+ expect(unconfigured.placeholder).toContain('not configured');
+
+ // The redacted sentinel must not reach the markup either: it is what the
+ // API returns for a configured secret, and writing it into the field (or a
+ // hidden input) would let a save persist it as the value.
+ expect(document.getElementById('settings-content').innerHTML)
+ .not.toContain('[REDACTED]');
+});
diff --git a/tests/security/test_injection_and_template_safety.py b/tests/security/test_injection_and_template_safety.py
index ea1c9a7947..5c5b88eecd 100644
--- a/tests/security/test_injection_and_template_safety.py
+++ b/tests/security/test_injection_and_template_safety.py
@@ -929,51 +929,28 @@ def test_tojson_in_an_html_attribute_breaks_out_of_the_attribute():
assert "&quot;" not in rendered
-# The only template that puts |tojson in an attribute. Its macro is
-# never invoked (asserted below), so the breakout is unreachable.
-TOJSON_ATTRIBUTE_CENSUS = {"components/settings_form.html": 2}
-
-
-def test_tojson_attribute_sites_are_exactly_the_unreachable_one():
+def test_no_template_puts_tojson_in_an_html_attribute():
+ """No template may put ``|tojson`` in an HTML attribute.
+
+ The JSON's own quotes land raw inside the attribute, so the parser sees a
+ fresh attribute after the value ends — see
+ ``test_tojson_in_an_html_attribute_breaks_out_of_the_attribute``. The one
+ site this census used to pin — ``components/settings_form.html``'s
+ ``render_setting`` macro, twice — was deleted along with the macro itself,
+ so the expected census is empty and any hit is a new breakout site.
+ """
census = {
rel: len(hits)
for rel, text in _templates()
if (hits := find_tojson_in_attribute(text))
}
- assert census == TOJSON_ATTRIBUTE_CENSUS, (
- "a template now puts |tojson in an HTML attribute; see "
+ assert census == {}, (
+ "|tojson inside an HTML attribute is a live breakout; offending "
+ f"templates (path: hit count): {census}. See "
"test_tojson_in_an_html_attribute_breaks_out_of_the_attribute"
)
-def test_the_tojson_attribute_macro_is_never_rendered():
- """``render_setting`` is imported but never called — keep it so.
-
- The settings page builds its form client-side from ``/settings/api``
- and the route passes no ``settings`` context, so the macro holding
- the attribute-context ``|tojson`` never executes. If a template
- starts calling it, the breakout above becomes reachable with any
- mapping-valued setting.
- """
- macro_file = "components/settings_form.html"
- invocations = []
- for rel, text in _templates():
- for number, line in enumerate(text.splitlines(), start=1):
- if "render_setting(" not in line:
- continue
- if rel == macro_file and "macro render_setting(" in line:
- continue
- invocations.append(f"{rel}:{number}")
- assert invocations == [], (
- "render_setting() is now invoked; its hidden input renders "
- "setting.value|tojson inside a quoted HTML attribute"
- )
-
- # ...and the macro really is still there to be guarded.
- macro_text = (TEMPLATES / macro_file).read_text(encoding="utf-8")
- assert "{% macro render_setting(" in macro_text
-
-
def test_pagination_query_params_survive_the_port_url_encoded():
"""``request.args`` became ``request.query_params`` in library.html.
diff --git a/tests/web/templates/test_settings_form_password_render.py b/tests/web/templates/test_settings_form_password_render.py
deleted file mode 100644
index f67b2f7a0e..0000000000
--- a/tests/web/templates/test_settings_form_password_render.py
+++ /dev/null
@@ -1,92 +0,0 @@
-"""Tests for the password branch of the ``settings_form.html`` macro.
-
-Pins the contract that:
-- The saved password value never enters the rendered HTML (no
- ``value="sk-..."`` attribute leak via View Source on the settings page).
-- The configured/not-configured state is communicated via the
- ``placeholder`` attribute, not the value.
-- ``autocomplete="new-password"`` is set so browser password managers
- don't offer to save the empty placeholder, and don't re-fill it on
- return visits.
-
-The macro is rendered via a standalone Jinja2 environment pointing at
-the project's ``templates/`` directory — no Flask app is required.
-"""
-# allow: no-sut-import — renders the real settings_form.html macro via
-# Jinja2; the SUT here is a template file, not an importable Python module.
-
-from pathlib import Path
-
-import pytest
-from jinja2 import Environment, FileSystemLoader, select_autoescape
-
-
-REPO_ROOT = Path(__file__).resolve().parents[3]
-TEMPLATES_DIR = REPO_ROOT / "src" / "local_deep_research" / "web" / "templates"
-
-
-def env():
- """Jinja2 environment matching Flask's defaults for autoescape."""
- return Environment(
- loader=FileSystemLoader(str(TEMPLATES_DIR)),
- autoescape=select_autoescape(["html", "xml"]),
- )
-
-
-def _render_password_setting(env, value):
- """Render the macro with a password-typed setting and return the HTML."""
- tmpl = env.from_string(
- "{% from 'components/settings_form.html' import render_setting %}"
- "{{ render_setting(setting) }}"
- )
- return tmpl.render(
- setting={
- "key": "llm.openai.api_key",
- "name": "OpenAI API Key",
- "description": "Authentication key for OpenAI",
- "ui_element": "password",
- "value": value,
- "editable": True,
- }
- )
-
-
-def test_password_input_renders_empty_value(env):
- """The plaintext secret must not appear in the value attribute."""
- secret = "sk-real-secret-12345"
- html = _render_password_setting(env, secret)
-
- # The input is rendered with value=""
- assert 'value=""' in html
- # Belt-and-braces: the secret string is nowhere in the rendered HTML
- assert secret not in html
-
-
-def test_configured_state_shows_saved_placeholder(env):
- """A non-empty saved value reads as 'saved — type to change'."""
- html = _render_password_setting(env, "sk-something-set")
- assert "saved" in html.lower()
- assert "type to change" in html.lower()
-
-
-def test_not_configured_state_shows_placeholder(env):
- """An empty/None saved value reads as 'not configured'."""
- html_empty = _render_password_setting(env, "")
- html_none = _render_password_setting(env, None)
- assert "not configured" in html_empty.lower()
- assert "not configured" in html_none.lower()
-
-
-def test_autocomplete_new_password_attribute_set(env):
- """Without autocomplete='new-password' some browsers will still offer
- to autofill cached values; this is the standard cross-browser opt-out."""
- html = _render_password_setting(env, "sk-something")
- assert 'autocomplete="new-password"' in html
-
-
-def test_password_input_type_remains_password(env):
- """Sanity — the input is still type=password (we didn't accidentally
- flip it to text while reworking the value/placeholder logic)."""
- html = _render_password_setting(env, "sk-x")
- assert 'type="password"' in html