~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
refactor(benchmark): extract YAML export helpers into a unit-tested module (#4584)
LearningCircuit269870216786
diff --git a/changelog.d/+benchmark-yaml-export-module.misc.md b/changelog.d/+benchmark-yaml-export-module.misc.mdnew file mode 100644index 0000000000..9ba9dbca43--- /dev/null+++ b/changelog.d/+benchmark-yaml-export-module.misc.md@@ -0,0 +1 @@+Extracted the benchmark YAML export helpers (`yamlEscape` / `formatSettingValue` / `formatSettingsSnapshot`) from the inline `benchmark_results.html` template into a unit-tested module (`static/js/utils/yaml_export.js`, loaded via `<script src>` like the other shared JS utils). No behavior change — it adds regression coverage (`tests/js/utils/yaml_export.test.js`) for the escaping that guards every benchmark YAML download, so a future change to `yamlEscape` can't silently corrupt exports.diff --git a/src/local_deep_research/web/static/js/utils/yaml_export.js b/src/local_deep_research/web/static/js/utils/yaml_export.jsnew file mode 100644index 0000000000..9b9080f454--- /dev/null+++ b/src/local_deep_research/web/static/js/utils/yaml_export.js@@ -0,0 +1,84 @@+/**+ * YAML serialization helpers for the benchmark export (and any other page+ * that builds YAML client-side).+ *+ * Extracted from benchmark_results.html so the escaping is unit-testable —+ * these functions are load-bearing for export correctness (a regression in+ * yamlEscape would silently corrupt every downloaded benchmark YAML).+ *+ * Loaded as a classic <script src> (functions become browser globals) with a+ * module.exports shim at the bottom so vitest can import them — same dual-use+ * pattern as security/url-validator.js, config/urls.js, etc.+ */++// Escape a string for use inside a YAML double-quoted scalar. Backslash MUST+// be escaped first, otherwise the backslashes added by the later replacements+// would themselves get doubled.+function yamlEscape(str) {+ if (str == null) return '';+ return String(str)+ .replace(/\\/g, '\\\\')+ .replace(/"/g, '\\"')+ .replace(/\n/g, '\\n')+ .replace(/\r/g, '\\r')+ .replace(/\t/g, '\\t');+}++// Format a single setting value as a YAML scalar / flow node.+// Booleans/numbers emit bare; null as `null`; arrays/objects as inline JSON+// (valid YAML 1.2 flow syntax — JSON is a YAML 1.2 superset). Strings are+// always double-quoted via yamlEscape so colons, hashes, leading dashes,+// and YAML reserved words (true/no/null/~) are unambiguous.+function formatSettingValue(value) {+ if (value === null || value === undefined) return 'null';+ if (typeof value === 'boolean') return value ? 'true' : 'false';+ if (typeof value === 'number') {+ if (!Number.isFinite(value)) return 'null';+ return String(value);+ }+ if (Array.isArray(value) || typeof value === 'object') {+ try {+ return JSON.stringify(value);+ } catch (_e) {+ // Defensive: circular references etc. Fall back to null.+ return 'null';+ }+ }+ return `"${yamlEscape(value)}"`;+}++// Build a `settings:` YAML block from a redacted settings snapshot dict.+// Snapshot is the {key: {value, ui_element, type, ...}} nested-with-metadata+// shape produced by SettingsManager.get_all_settings(). Tolerates flat+// snapshots and missing `value` keys without crashing.+function formatSettingsSnapshot(snapshot) {+ if (snapshot == null) {+ return 'settings: null # snapshot not captured for this run\n';+ }+ const keys = Object.keys(snapshot).sort();+ if (keys.length === 0) return 'settings: {}\n';+ let out = 'settings:\n';+ for (const key of keys) {+ const entry = snapshot[key];+ const raw = (entry && typeof entry === 'object' && 'value' in entry)+ ? entry.value+ : (entry && typeof entry === 'object' ? null : entry);+ // Quote keys containing YAML-significant chars. Plain dotted keys+ // (e.g. `llm.model`) are valid plain scalars — no quoting needed.+ const needsQuote = /[:#\s[\]{},&*!|>'"%@`]/.test(key) || /^[-?]/.test(key);+ const formattedKey = needsQuote ? `"${yamlEscape(key)}"` : key;+ out += ` ${formattedKey}: ${formatSettingValue(raw)}\n`;+ }+ return out;+}++// Browser: expose as globals (classic <script> already does this for top-level+// declarations, but be explicit). Node/vitest: export for unit tests.+if (typeof window !== 'undefined') {+ window.yamlEscape = yamlEscape;+ window.formatSettingValue = formatSettingValue;+ window.formatSettingsSnapshot = formatSettingsSnapshot;+}+if (typeof module !== 'undefined' && module.exports) {+ module.exports = { yamlEscape, formatSettingValue, formatSettingsSnapshot };+}diff --git a/src/local_deep_research/web/templates/pages/benchmark_results.html b/src/local_deep_research/web/templates/pages/benchmark_results.htmlindex 8ae5888034..7e116e83e8 100644--- a/src/local_deep_research/web/templates/pages/benchmark_results.html+++ b/src/local_deep_research/web/templates/pages/benchmark_results.html@@ -76,6 +76,10 @@</div></div>+<!-- YAML serialization helpers (yamlEscape / formatSettingValue /+ formatSettingsSnapshot) — extracted so the export escaping is unit-tested.+ Must load before the inline script below, which calls them as globals. -->+<script src="/static/js/utils/yaml_export.js"></script><script>let benchmarkRuns = [];let filteredRuns = [];@@ -583,63 +587,9 @@ async function cancelAndDeleteBenchmarkRun(runId) {}}-function yamlEscape(str) {- if (str == null) return '';- return String(str)- .replace(/\\/g, '\\\\')- .replace(/"/g, '\\"')- .replace(/\n/g, '\\n')- .replace(/\r/g, '\\r')- .replace(/\t/g, '\\t');-}--// Format a single setting value as a YAML scalar / flow node.-// Booleans/numbers emit bare; null as `null`; arrays/objects as inline JSON-// (valid YAML 1.2 flow syntax — JSON is a YAML 1.2 superset). Strings are-// always double-quoted via yamlEscape so colons, hashes, leading dashes,-// and YAML reserved words (true/no/null/~) are unambiguous.-function formatSettingValue(value) {- if (value === null || value === undefined) return 'null';- if (typeof value === 'boolean') return value ? 'true' : 'false';- if (typeof value === 'number') {- if (!Number.isFinite(value)) return 'null';- return String(value);- }- if (Array.isArray(value) || typeof value === 'object') {- try {- return JSON.stringify(value);- } catch (e) {- // Defensive: circular references etc. Fall back to null.- return 'null';- }- }- return `"${yamlEscape(value)}"`;-}--// Build a `settings:` YAML block from a redacted settings snapshot dict.-// Snapshot is the {key: {value, ui_element, type, ...}} nested-with-metadata-// shape produced by SettingsManager.get_all_settings(). Tolerates flat-// snapshots and missing `value` keys without crashing.-function formatSettingsSnapshot(snapshot) {- if (snapshot == null) {- return 'settings: null # snapshot not captured for this run\n';- }- const keys = Object.keys(snapshot).sort();- if (keys.length === 0) return 'settings: {}\n';- let out = 'settings:\n';- for (const key of keys) {- const entry = snapshot[key];- const raw = (entry && typeof entry === 'object' && 'value' in entry)- ? entry.value- : (entry && typeof entry === 'object' ? null : entry);- // Quote keys containing YAML-significant chars. Plain dotted keys- // (e.g. `llm.model`) are valid plain scalars — no quoting needed.- const needsQuote = /[:#\s\[\]\{\},&*!|>'"%@`]/.test(key) || /^[-?]/.test(key);- const formattedKey = needsQuote ? `"${yamlEscape(key)}"` : key;- out += ` ${formattedKey}: ${formatSettingValue(raw)}\n`;- }- return out;-}+// yamlEscape / formatSettingValue / formatSettingsSnapshot are defined in+// /static/js/utils/yaml_export.js (loaded via <script src> above) as globals,+// so the YAML escaping is unit-tested (tests/js/utils/yaml_export.test.js).async function downloadBenchmarkYAML(runId, includeExamples = false, includeSettings = false) {try {diff --git a/tests/js/utils/yaml_export.test.js b/tests/js/utils/yaml_export.test.jsnew file mode 100644index 0000000000..546549a6a6--- /dev/null+++ b/tests/js/utils/yaml_export.test.js@@ -0,0 +1,114 @@+/**+ * Tests for utils/yaml_export.js — the YAML serialization helpers used by the+ * benchmark export (yamlEscape / formatSettingValue / formatSettingsSnapshot).+ *+ * These are load-bearing for export correctness: a regression in yamlEscape+ * would silently corrupt every downloaded benchmark YAML (and could let a+ * model name / URL with YAML-special chars inject an unintended key). This+ * pins the escaping behaviour now that the function is importable.+ */++import '@js/utils/yaml_export.js';++const { yamlEscape, formatSettingValue, formatSettingsSnapshot } = window;++describe('yamlEscape', () => {+ it('returns empty string for null/undefined', () => {+ expect(yamlEscape(null)).toBe('');+ expect(yamlEscape(undefined)).toBe('');+ });++ it('leaves plain strings untouched', () => {+ expect(yamlEscape('qwen3.6')).toBe('qwen3.6');+ });++ it('escapes backslash FIRST so later escapes are not double-escaped', () => {+ // A lone backslash must become exactly two, not four.+ expect(yamlEscape('a\\b')).toBe('a\\\\b');+ // Backslash + quote: backslash doubled, quote escaped — order matters.+ expect(yamlEscape('\\"')).toBe('\\\\\\"');+ });++ it('escapes double quotes, newlines, CR and tabs', () => {+ expect(yamlEscape('he said "hi"')).toBe('he said \\"hi\\"');+ expect(yamlEscape('a\nb')).toBe('a\\nb');+ expect(yamlEscape('a\rb')).toBe('a\\rb');+ expect(yamlEscape('a\tb')).toBe('a\\tb');+ });++ it('coerces non-strings via String()', () => {+ expect(yamlEscape(42)).toBe('42');+ });+});++describe('formatSettingValue', () => {+ it('emits null for null/undefined', () => {+ expect(formatSettingValue(null)).toBe('null');+ expect(formatSettingValue(undefined)).toBe('null');+ });++ it('emits bare booleans and finite numbers', () => {+ expect(formatSettingValue(true)).toBe('true');+ expect(formatSettingValue(false)).toBe('false');+ expect(formatSettingValue(128000)).toBe('128000');+ });++ it('emits null for non-finite numbers', () => {+ expect(formatSettingValue(Infinity)).toBe('null');+ expect(formatSettingValue(NaN)).toBe('null');+ });++ it('emits inline JSON for arrays and objects', () => {+ expect(formatSettingValue([1, 'a'])).toBe('[1,"a"]');+ expect(formatSettingValue({ a: 1 })).toBe('{"a":1}');+ });++ it('double-quotes and escapes strings', () => {+ expect(formatSettingValue('gpt-4')).toBe('"gpt-4"');+ // A value with a YAML-special char must stay a single safe scalar.+ expect(formatSettingValue('a: b # c')).toBe('"a: b # c"');+ expect(formatSettingValue('inject\nkey: pwned')).toBe(+ '"inject\\nkey: pwned"',+ );+ });+});++describe('formatSettingsSnapshot', () => {+ it('renders a sentinel comment for a null snapshot', () => {+ expect(formatSettingsSnapshot(null)).toBe(+ 'settings: null # snapshot not captured for this run\n',+ );+ });++ it('renders an empty flow map for {}', () => {+ expect(formatSettingsSnapshot({})).toBe('settings: {}\n');+ });++ it('renders sorted keys with formatted values (metadata shape)', () => {+ const out = formatSettingsSnapshot({+ 'llm.model': { value: 'qwen3.6', ui_element: 'select' },+ 'a.flag': { value: true, ui_element: 'checkbox' },+ });+ // a.flag sorts before llm.model; string quoted, bool bare.+ expect(out).toBe(+ 'settings:\n a.flag: true\n llm.model: "qwen3.6"\n',+ );+ });++ it('quotes keys that contain YAML-significant characters', () => {+ const out = formatSettingsSnapshot({ 'has space': { value: 'x' } });+ expect(out).toContain('"has space": "x"');+ });++ it('passes flat (non-metadata) scalar values through', () => {+ const out = formatSettingsSnapshot({ 'llm.model': 'qwen3.6' });+ expect(out).toBe('settings:\n llm.model: "qwen3.6"\n');+ });++ it('renders null for a metadata object missing its `value` key', () => {+ const out = formatSettingsSnapshot({+ 'llm.model': { ui_element: 'select' },+ });+ expect(out).toBe('settings:\n llm.model: null\n');+ });+});