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.

refactor: extract IIFE-locked JS helpers to testable utility modules (#3451)

LearningCircuit7b7e0fa3d2f3
diff --git a/src/local_deep_research/web/static/js/components/details.js b/src/local_deep_research/web/static/js/components/details.js
index b50a9c500f..8f5977cbee 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -6,6 +6,9 @@
(function() {
'use strict';
+ // Shared formatting helpers live on window.formatting (services/formatting.js)
+ const { formatNumber, formatCurrency, generateChartColors } = window.formatting;
+
let researchId = null;
let metricsData = null;
let timelineChart = null;
@@ -44,49 +47,6 @@
};
}
- // Format large numbers with commas
- function formatNumber(num) {
- return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
- }
-
- // Format currency
- function formatCurrency(amount) {
- if (amount < 0.01) {
- return `$${amount.toFixed(6)}`;
- } else if (amount < 1) {
- return `$${amount.toFixed(4)}`;
- } else {
- return `$${amount.toFixed(2)}`;
- }
- }
-
- // Helper function to generate colors for dynamic number of categories
- function generateChartColors(count) {
- const baseColors = [
- 'rgba(107, 70, 193, 0.8)', // Purple
- 'rgba(245, 158, 11, 0.8)', // Orange
- 'rgba(59, 130, 246, 0.8)', // Blue
- 'rgba(16, 185, 129, 0.8)', // Green
- 'rgba(239, 68, 68, 0.8)', // Red
- 'rgba(139, 69, 19, 0.8)', // Brown
- 'rgba(255, 192, 203, 0.8)', // Pink
- 'rgba(128, 128, 128, 0.8)', // Gray
- 'rgba(255, 165, 0, 0.8)', // Orange
- 'rgba(75, 0, 130, 0.8)' // Indigo
- ];
-
- const background = [];
- const border = [];
-
- for (let i = 0; i < count; i++) {
- const colorIndex = i % baseColors.length;
- background.push(baseColors[colorIndex]);
- border.push(baseColors[colorIndex].replace('0.8', '1'));
- }
-
- return { background, border };
- }
-
// Get research ID from URL
function getResearchIdFromUrl() {
const id = URLBuilder.extractResearchIdFromPattern('details');
diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.js
index 2a6ed5523f..c37339fca2 100644
--- a/src/local_deep_research/web/static/js/components/logpanel.js
+++ b/src/local_deep_research/web/static/js/components/logpanel.js
@@ -9,6 +9,14 @@
const escapeHtmlFallback = (str) => String(str || '').replace(/[&<>"']/g, (m) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'})[m]);
const escapeHtml = window.escapeHtml || escapeHtmlFallback;
+ // Shared log helpers extracted to utils/log-helpers.js for testability
+ const {
+ checkLogVisibility,
+ hashString,
+ normalizeMessage,
+ normalizeTimestamps,
+ } = window.LdrLogHelpers;
+
// Maximum number of log entries to keep in DOM to prevent unbounded growth
const MAX_LOG_ENTRIES = 500;
@@ -611,92 +619,6 @@
}
}
- /**
- * Normalize a message for deduplication comparison
- * @param {string} message - The message to normalize
- * @returns {string} - Normalized message for comparison
- */
- function normalizeMessage(message) {
- if (!message) return '';
- // Remove extra whitespace and lowercase
- return message.trim().toLowerCase();
- }
-
- /**
- * Normalize timestamps across logs to ensure consistent ordering
- * @param {Array} logs - The logs to normalize
- */
- function normalizeTimestamps(logs) {
- // Find the most common date in the logs (ignoring the time)
- const dateFrequency = new Map();
-
- logs.forEach(log => {
- try {
- const date = new Date(log.time);
- // Extract just the date part (YYYY-MM-DD)
- const dateStr = date.toISOString().split('T')[0];
- dateFrequency.set(dateStr, (dateFrequency.get(dateStr) || 0) + 1);
- } catch (e) {
- SafeLogger.error('Error parsing date:', log.time);
- }
- });
-
- // Find the most frequent date
- let mostCommonDate = null;
- let highestFrequency = 0;
-
- dateFrequency.forEach((count, date) => {
- if (count > highestFrequency) {
- highestFrequency = count;
- mostCommonDate = date;
- }
- });
-
- SafeLogger.log(`Most common date: ${mostCommonDate} with ${highestFrequency} occurrences`);
-
- if (!mostCommonDate) return; // Can't normalize without a common date
-
- // Normalize all logs to the most common date
- logs.forEach(log => {
- try {
- const date = new Date(log.time);
- const dateStr = date.toISOString().split('T')[0];
-
- // If this log is from a different date, adjust it to the most common date
- // while preserving the time portion
- if (dateStr !== mostCommonDate) {
- const [year, month, day] = mostCommonDate.split('-');
- date.setFullYear(parseInt(year));
- date.setMonth(parseInt(month) - 1); // Months are 0-indexed
- date.setDate(parseInt(day));
-
- // Update the log time
- log.time = date.toISOString();
- log.id = `${log.time}-${hashString(log.message)}`;
- SafeLogger.log(`Normalized timestamp for "${log.message.substring(0, 30)}..." from ${dateStr} to ${mostCommonDate}`);
- }
- } catch (e) {
- SafeLogger.error('Error normalizing date:', log.time);
- }
- });
- }
-
- /**
- * Simple hash function for strings
- * @param {string} str - String to hash
- * @returns {string} - Hashed string for use as ID
- */
- function hashString(str) {
- if (!str) return '0';
- let hash = 0;
- for (let i = 0; i < str.length; i++) {
- const char = str.charCodeAt(i);
- hash = ((hash << 5) - hash) + char;
- hash = hash & hash; // Convert to 32bit integer
- }
- return hash.toString();
- }
-
/**
* Add a log entry to the console - public API
* @param {string} message - Log message
@@ -975,32 +897,6 @@
}
}
- /**
- * Check if a log entry should be visible based on filter type
- * @param {string} logType - The type of log (info, milestone, error)
- * @param {string} filterType - The selected filter (all, info, milestone, error)
- * @returns {boolean} - Whether the log should be visible
- */
- function checkLogVisibility(logType, filterType) {
- switch (filterType) {
- case 'all':
- return true;
- case 'info':
- return logType === 'info' || logType === 'warning' || logType === 'milestone' || logType === 'error';
- case 'milestone':
- case 'milestones': // Handle plural form too
- return logType === 'milestone';
- case 'warning':
- case 'warnings':
- return logType === 'warning' || logType === 'error';
- case 'error':
- case 'errors': // Handle plural form too
- return logType === 'error';
- default:
- return true; // Default to showing everything
- }
- }
-
/**
* Filter logs by type
* @param {string} filterType - The type to filter by (all, info, milestone, error)
diff --git a/src/local_deep_research/web/static/js/components/settings.js b/src/local_deep_research/web/static/js/components/settings.js
index b7407ffc39..adb0cd5987 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -5,6 +5,14 @@
(function() {
'use strict';
+ // Shared value helpers extracted to utils/value-helpers.js for testability
+ const {
+ areValuesEqual,
+ areObjectsEqual,
+ formatPropertyName,
+ formatValueForDisplay,
+ } = window.LdrValueHelpers;
+
// DOM elements and global variables
let settingsForm;
let settingsContent;
@@ -484,53 +492,6 @@
// --- MODIFICATION END ---
}
- /**
- * Compare two values for equality, handling different types
- * @param {any} value1 - First value
- * @param {any} value2 - Second value
- * @returns {boolean} - Whether the values are equal
- */
- function areValuesEqual(value1, value2) {
- // Handle null/undefined
- if (value1 === null && value2 === null) return true;
- if (value1 === undefined && value2 === undefined) return true;
- if (value1 === null && value2 === undefined) return true;
- if (value1 === undefined && value2 === null) return true;
-
- // If one is null/undefined but the other isn't
- if ((value1 === null || value1 === undefined) && (value2 !== null && value2 !== undefined)) return false;
- if ((value2 === null || value2 === undefined) && (value1 !== null && value1 !== undefined)) return false;
-
- // Handle different types
- const type1 = typeof value1;
- const type2 = typeof value2;
-
- // If types are different, they're not equal
- // Except for numbers and strings that might be equivalent
- if (type1 !== type2) {
- // Special case for numeric strings vs numbers
- if ((type1 === 'number' && type2 === 'string') || (type1 === 'string' && type2 === 'number')) {
- return String(value1) === String(value2);
- }
- return false;
- }
-
- // Handle objects (including arrays)
- if (type1 === 'object') {
- // Handle arrays
- if (Array.isArray(value1) && Array.isArray(value2)) {
- if (value1.length !== value2.length) return false;
- return JSON.stringify(value1) === JSON.stringify(value2);
- }
-
- // Handle objects
- return JSON.stringify(value1) === JSON.stringify(value2);
- }
-
- // Handle primitives
- return value1 === value2;
- }
-
/**
* Handle input to raw JSON fields for validation
* @param {Event} e - The input event
@@ -765,33 +726,6 @@
}
}
- /**
- * Compare two objects for equality
- * @param {Object} obj1 - First object
- * @param {Object} obj2 - Second object
- * @returns {boolean} - Whether the objects are equal
- */
- function areObjectsEqual(obj1, obj2) {
- // Get the keys of both objects
- const keys1 = Object.keys(obj1);
- const keys2 = Object.keys(obj2);
-
- // If the number of keys is different, they're not equal
- if (keys1.length !== keys2.length) return false;
-
- // Check each key/value pair
- for (const key of keys1) {
- // If the key doesn't exist in obj2, not equal
- if (!obj2.hasOwnProperty(key)) return false;
-
- // If the values are not equal, not equal
- if (!areValuesEqual(obj1[key], obj2[key])) return false;
- }
-
- // All keys/values match
- return true;
- }
-
/**
* Initialize specific settings page form handlers
*/
@@ -2376,33 +2310,6 @@
return html;
}
- /**
- * Parse form values to boolean (server-side consistency)
- * @param {any} value - The value to convert
- * @returns {boolean} - The boolean value
- */
- function parseFormBoolean(value) {
- if (typeof value === 'boolean') return value;
- if (value === null || value === undefined) return false;
- if (typeof value === 'string') {
- const lower = value.toLowerCase().trim();
- return ['on', 'true', '1', 'yes'].includes(lower);
- }
- return Boolean(value);
- }
-
- /**
- * Format property name to be more user-friendly
- * @param {string} name - The property name
- * @returns {string} - The formatted property name
- */
- function formatPropertyName(name) {
- // Replace underscores with spaces and capitalize each word
- return name.split('_')
- .map(word => word.charAt(0).toUpperCase() + word.slice(1))
- .join(' ');
- }
-
/**
* Handle settings form submission (for the entire form)
* @param {Event} e - The submit event
@@ -2805,29 +2712,6 @@
});
}
- /**
- * Format a value for display in notifications
- * @param {any} value - The value to format
- * @returns {string} - Formatted value for display
- */
- function formatValueForDisplay(value) {
- if (value === null || value === undefined) {
- return 'empty';
- } else if (typeof value === 'boolean') {
- return value ? 'enabled' : 'disabled';
- } else if (typeof value === 'object') {
- // For objects, show a simplified representation
- return '{...}';
- } else if (typeof value === 'string' && value.length > 20) {
- // Truncate long strings
- return `"${value.substring(0, 18)}..."`;
- } else if (typeof value === 'string') {
- return `"${value}"`;
- } else {
- return String(value);
- }
- }
-
/**
* Handle search input for filtering settings
*/
diff --git a/src/local_deep_research/web/static/js/services/formatting.js b/src/local_deep_research/web/static/js/services/formatting.js
index 0c7125c9c7..dde80cf33e 100644
--- a/src/local_deep_research/web/static/js/services/formatting.js
+++ b/src/local_deep_research/web/static/js/services/formatting.js
@@ -102,6 +102,53 @@ function formatNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
+/**
+ * Format a dollar amount, using more decimal places for small numbers.
+ * @param {number} amount - Amount in dollars
+ * @returns {string} Formatted currency string (e.g. "$0.000123", "$12.34")
+ */
+function formatCurrency(amount) {
+ if (amount < 0.01) {
+ return `$${amount.toFixed(6)}`;
+ } else if (amount < 1) {
+ return `$${amount.toFixed(4)}`;
+ } else {
+ return `$${amount.toFixed(2)}`;
+ }
+}
+
+/**
+ * Generate background/border colors for a chart with `count` categories,
+ * cycling through a fixed base palette.
+ * @param {number} count - Number of colors needed
+ * @returns {{background: string[], border: string[]}}
+ */
+function generateChartColors(count) {
+ const baseColors = [
+ 'rgba(107, 70, 193, 0.8)', // Purple
+ 'rgba(245, 158, 11, 0.8)', // Orange
+ 'rgba(59, 130, 246, 0.8)', // Blue
+ 'rgba(16, 185, 129, 0.8)', // Green
+ 'rgba(239, 68, 68, 0.8)', // Red
+ 'rgba(139, 69, 19, 0.8)', // Brown
+ 'rgba(255, 192, 203, 0.8)', // Pink
+ 'rgba(128, 128, 128, 0.8)', // Gray
+ 'rgba(255, 165, 0, 0.8)', // Orange
+ 'rgba(75, 0, 130, 0.8)' // Indigo
+ ];
+
+ const background = [];
+ const border = [];
+
+ for (let i = 0; i < count; i++) {
+ const colorIndex = i % baseColors.length;
+ background.push(baseColors[colorIndex]);
+ border.push(baseColors[colorIndex].replace('0.8', '1'));
+ }
+
+ return { background, border };
+}
+
// Export the functions to make them available to other modules
window.formatting = {
formatStatus,
@@ -109,5 +156,7 @@ window.formatting = {
formatDate,
formatDuration,
formatNumber,
+ formatCurrency,
+ generateChartColors,
capitalizeFirstLetter
};
diff --git a/src/local_deep_research/web/static/js/utils/log-helpers.js b/src/local_deep_research/web/static/js/utils/log-helpers.js
new file mode 100644
index 0000000000..2d853db450
--- /dev/null
+++ b/src/local_deep_research/web/static/js/utils/log-helpers.js
@@ -0,0 +1,140 @@
+/**
+ * Shared helpers for the log panel component.
+ *
+ * Extracted from components/logpanel.js so they can be unit-tested
+ * (the logpanel.js IIFE is otherwise unreachable from tests).
+ *
+ * Exposes window.LdrLogHelpers. Consumers should destructure at the top
+ * of their IIFE, e.g.
+ * const { checkLogVisibility, hashString } = window.LdrLogHelpers;
+ */
+(function() {
+ 'use strict';
+
+ /**
+ * Decide whether a log entry of the given type should be visible
+ * under a filter selection. Matches the plural/singular variants the
+ * UI may emit (e.g. "milestones" vs "milestone").
+ * @param {string} logType - 'info' | 'milestone' | 'warning' | 'error'
+ * @param {string} filterType - selected filter ('all', 'info', 'milestone', ...)
+ * @returns {boolean}
+ */
+ function checkLogVisibility(logType, filterType) {
+ switch (filterType) {
+ case 'all':
+ return true;
+ case 'info':
+ return logType === 'info' || logType === 'warning' || logType === 'milestone' || logType === 'error';
+ case 'milestone':
+ case 'milestones': // Handle plural form too
+ return logType === 'milestone';
+ case 'warning':
+ case 'warnings':
+ return logType === 'warning' || logType === 'error';
+ case 'error':
+ case 'errors': // Handle plural form too
+ return logType === 'error';
+ default:
+ return true; // Default to showing everything
+ }
+ }
+
+ /**
+ * Deterministic 32-bit string hash, used to build stable IDs for
+ * deduping log entries.
+ * @param {string} str
+ * @returns {string} The hash as a decimal string.
+ */
+ function hashString(str) {
+ if (!str) return '0';
+ let hash = 0;
+ for (let i = 0; i < str.length; i++) {
+ const char = str.charCodeAt(i);
+ hash = ((hash << 5) - hash) + char;
+ hash = hash & hash; // Convert to 32bit integer
+ }
+ return hash.toString();
+ }
+
+ /**
+ * Trim and lowercase a log message for deduplication comparison.
+ * Null/undefined become the empty string.
+ * @param {string} message
+ * @returns {string}
+ */
+ function normalizeMessage(message) {
+ if (!message) return '';
+ return message.trim().toLowerCase();
+ }
+
+ /**
+ * Normalize timestamps across a batch of logs so stray entries from
+ * a different calendar day (clock skew, retries) are re-anchored to
+ * the date most logs already share. Mutates `logs` in place.
+ *
+ * Uses a frequency count: the most common YYYY-MM-DD wins; logs on
+ * other dates have their date re-stamped while preserving the time.
+ * @param {Array<{time: string, message?: string, id?: string}>} logs
+ */
+ function normalizeTimestamps(logs) {
+ // Find the most common date in the logs (ignoring the time)
+ const dateFrequency = new Map();
+
+ logs.forEach(log => {
+ try {
+ const date = new Date(log.time);
+ // Extract just the date part (YYYY-MM-DD)
+ const dateStr = date.toISOString().split('T')[0];
+ dateFrequency.set(dateStr, (dateFrequency.get(dateStr) || 0) + 1);
+ } catch (e) {
+ SafeLogger.error('Error parsing date:', log.time);
+ }
+ });
+
+ // Find the most frequent date
+ let mostCommonDate = null;
+ let highestFrequency = 0;
+
+ dateFrequency.forEach((count, date) => {
+ if (count > highestFrequency) {
+ highestFrequency = count;
+ mostCommonDate = date;
+ }
+ });
+
+ SafeLogger.log(`Most common date: ${mostCommonDate} with ${highestFrequency} occurrences`);
+
+ if (!mostCommonDate) return; // Can't normalize without a common date
+
+ // Normalize all logs to the most common date
+ logs.forEach(log => {
+ try {
+ const date = new Date(log.time);
+ const dateStr = date.toISOString().split('T')[0];
+
+ // If this log is from a different date, adjust it to the most common date
+ // while preserving the time portion
+ if (dateStr !== mostCommonDate) {
+ const [year, month, day] = mostCommonDate.split('-');
+ date.setFullYear(parseInt(year));
+ date.setMonth(parseInt(month) - 1); // Months are 0-indexed
+ date.setDate(parseInt(day));
+
+ // Update the log time
+ log.time = date.toISOString();
+ log.id = `${log.time}-${hashString(log.message)}`;
+ SafeLogger.log(`Normalized timestamp for "${log.message.substring(0, 30)}..." from ${dateStr} to ${mostCommonDate}`);
+ }
+ } catch (e) {
+ SafeLogger.error('Error normalizing date:', log.time);
+ }
+ });
+ }
+
+ window.LdrLogHelpers = {
+ checkLogVisibility,
+ hashString,
+ normalizeMessage,
+ normalizeTimestamps,
+ };
+})();
diff --git a/src/local_deep_research/web/static/js/utils/value-helpers.js b/src/local_deep_research/web/static/js/utils/value-helpers.js
new file mode 100644
index 0000000000..c2f789c4c5
--- /dev/null
+++ b/src/local_deep_research/web/static/js/utils/value-helpers.js
@@ -0,0 +1,127 @@
+/**
+ * Shared value comparison and display helpers.
+ *
+ * Extracted from components/settings.js so the logic can be unit-tested
+ * (the settings.js IIFE is otherwise unreachable from tests).
+ *
+ * Exposes window.LdrValueHelpers. Consumers should destructure at the top
+ * of their IIFE, e.g.
+ * const { areValuesEqual, formatPropertyName } = window.LdrValueHelpers;
+ *
+ * Note: embedding_settings.js intentionally retains its own local copies
+ * of areValuesEqual and formatValueForDisplay because their semantics
+ * differ visibly (different truncation lengths, array handling, and
+ * equality rules). Unifying them would cause UX drift.
+ */
+(function() {
+ 'use strict';
+
+ /**
+ * Compare two values for equality, handling different types.
+ * @param {any} value1
+ * @param {any} value2
+ * @returns {boolean}
+ */
+ function areValuesEqual(value1, value2) {
+ // Handle null/undefined
+ if (value1 === null && value2 === null) return true;
+ if (value1 === undefined && value2 === undefined) return true;
+ if (value1 === null && value2 === undefined) return true;
+ if (value1 === undefined && value2 === null) return true;
+
+ // If one is null/undefined but the other isn't
+ if ((value1 === null || value1 === undefined) && (value2 !== null && value2 !== undefined)) return false;
+ if ((value2 === null || value2 === undefined) && (value1 !== null && value1 !== undefined)) return false;
+
+ // Handle different types
+ const type1 = typeof value1;
+ const type2 = typeof value2;
+
+ // If types are different, they're not equal
+ // Except for numbers and strings that might be equivalent
+ if (type1 !== type2) {
+ // Special case for numeric strings vs numbers
+ if ((type1 === 'number' && type2 === 'string') || (type1 === 'string' && type2 === 'number')) {
+ return String(value1) === String(value2);
+ }
+ return false;
+ }
+
+ // Handle objects (including arrays)
+ if (type1 === 'object') {
+ // Handle arrays
+ if (Array.isArray(value1) && Array.isArray(value2)) {
+ if (value1.length !== value2.length) return false;
+ return JSON.stringify(value1) === JSON.stringify(value2);
+ }
+
+ // Handle objects
+ return JSON.stringify(value1) === JSON.stringify(value2);
+ }
+
+ // Handle primitives
+ return value1 === value2;
+ }
+
+ /**
+ * Deep-compare two objects using areValuesEqual for each value.
+ * @param {Object} obj1
+ * @param {Object} obj2
+ * @returns {boolean}
+ */
+ function areObjectsEqual(obj1, obj2) {
+ const keys1 = Object.keys(obj1);
+ const keys2 = Object.keys(obj2);
+
+ if (keys1.length !== keys2.length) return false;
+
+ for (const key of keys1) {
+ if (!obj2.hasOwnProperty(key)) return false;
+ if (!areValuesEqual(obj1[key], obj2[key])) return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * Convert a snake_case property name to Title Case.
+ * @param {string} name
+ * @returns {string}
+ */
+ function formatPropertyName(name) {
+ return name.split('_')
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1))
+ .join(' ');
+ }
+
+ /**
+ * Format a value for display in settings notifications.
+ * Strings are quoted, long strings are truncated, objects are elided.
+ * @param {any} value
+ * @returns {string}
+ */
+ function formatValueForDisplay(value) {
+ if (value === null || value === undefined) {
+ return 'empty';
+ } else if (typeof value === 'boolean') {
+ return value ? 'enabled' : 'disabled';
+ } else if (typeof value === 'object') {
+ // For objects, show a simplified representation
+ return '{...}';
+ } else if (typeof value === 'string' && value.length > 20) {
+ // Truncate long strings
+ return `"${value.substring(0, 18)}..."`;
+ } else if (typeof value === 'string') {
+ return `"${value}"`;
+ } else {
+ return String(value);
+ }
+ }
+
+ window.LdrValueHelpers = {
+ areValuesEqual,
+ areObjectsEqual,
+ formatPropertyName,
+ formatValueForDisplay,
+ };
+})();
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index d11c1ea002..9f84c65c2f 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -178,8 +178,10 @@
<!-- Form Utilities -->
<script defer src="/static/js/utils/form-validation.js"></script>
<script defer src="/static/js/utils/sse-completion.js"></script>
+ <script defer src="/static/js/utils/value-helpers.js"></script>
<!-- Shared Components -->
+ <script defer src="/static/js/utils/log-helpers.js"></script>
<script defer src="/static/js/components/logpanel.js"></script>
<!-- Page-specific Components -->
diff --git a/tests/js/services/formatting.test.js b/tests/js/services/formatting.test.js
index 3f20bef8cd..64d464ad95 100644
--- a/tests/js/services/formatting.test.js
+++ b/tests/js/services/formatting.test.js
@@ -147,4 +147,58 @@ describe('formatting', () => {
expect(fmt.formatStatus('in_progress')).toBe('In Progress');
});
});
+
+ describe('formatCurrency', () => {
+ it('uses 6 decimal places for tiny amounts (< $0.01)', () => {
+ expect(fmt.formatCurrency(0.000123)).toBe('$0.000123');
+ expect(fmt.formatCurrency(0.005)).toBe('$0.005000');
+ });
+
+ it('uses 4 decimal places for amounts < $1 (boundary: 0.01)', () => {
+ expect(fmt.formatCurrency(0.01)).toBe('$0.0100');
+ expect(fmt.formatCurrency(0.5)).toBe('$0.5000');
+ expect(fmt.formatCurrency(0.9999)).toBe('$0.9999');
+ });
+
+ it('uses 2 decimal places for amounts >= $1', () => {
+ expect(fmt.formatCurrency(1)).toBe('$1.00');
+ expect(fmt.formatCurrency(12.345)).toBe('$12.35');
+ expect(fmt.formatCurrency(1000)).toBe('$1000.00');
+ });
+
+ it('zero uses the tiny-amount branch', () => {
+ expect(fmt.formatCurrency(0)).toBe('$0.000000');
+ });
+ });
+
+ describe('generateChartColors', () => {
+ it('returns empty arrays for count=0', () => {
+ const r = fmt.generateChartColors(0);
+ expect(r.background).toEqual([]);
+ expect(r.border).toEqual([]);
+ });
+
+ it('returns `count` colors', () => {
+ const r = fmt.generateChartColors(3);
+ expect(r.background).toHaveLength(3);
+ expect(r.border).toHaveLength(3);
+ });
+
+ it('cycles through the palette when count exceeds base length', () => {
+ const r = fmt.generateChartColors(15);
+ expect(r.background).toHaveLength(15);
+ // First and 11th entries should be identical (palette of 10)
+ expect(r.background[0]).toBe(r.background[10]);
+ });
+
+ it('border colors are opaque versions of background colors', () => {
+ const r = fmt.generateChartColors(2);
+ for (let i = 0; i < 2; i++) {
+ // background should use alpha 0.8, border alpha 1
+ expect(r.background[i]).toContain('0.8');
+ expect(r.border[i]).not.toContain('0.8');
+ expect(r.border[i]).toContain(', 1)');
+ }
+ });
+ });
});
diff --git a/tests/js/utils/log-helpers.test.js b/tests/js/utils/log-helpers.test.js
new file mode 100644
index 0000000000..f47a18c268
--- /dev/null
+++ b/tests/js/utils/log-helpers.test.js
@@ -0,0 +1,185 @@
+/**
+ * Tests for utils/log-helpers.js
+ *
+ * The log panel filters and dedups thousands of log entries during a
+ * research run. These helpers power that — an off-by-one in
+ * checkLogVisibility means warnings disappear; a collision in
+ * hashString means dedupe drops real entries.
+ */
+
+import '@js/utils/log-helpers.js';
+
+const {
+ checkLogVisibility,
+ hashString,
+ normalizeMessage,
+ normalizeTimestamps,
+} = window.LdrLogHelpers;
+
+describe('checkLogVisibility', () => {
+ it("filter 'all' shows every type", () => {
+ for (const type of ['info', 'milestone', 'warning', 'error']) {
+ expect(checkLogVisibility(type, 'all')).toBe(true);
+ }
+ });
+
+ it("filter 'info' shows info, milestone, warning, and error", () => {
+ expect(checkLogVisibility('info', 'info')).toBe(true);
+ expect(checkLogVisibility('milestone', 'info')).toBe(true);
+ expect(checkLogVisibility('warning', 'info')).toBe(true);
+ expect(checkLogVisibility('error', 'info')).toBe(true);
+ });
+
+ it("filter 'milestone' only shows milestones", () => {
+ expect(checkLogVisibility('milestone', 'milestone')).toBe(true);
+ expect(checkLogVisibility('info', 'milestone')).toBe(false);
+ expect(checkLogVisibility('warning', 'milestone')).toBe(false);
+ expect(checkLogVisibility('error', 'milestone')).toBe(false);
+ });
+
+ it("accepts plural 'milestones' as an alias", () => {
+ expect(checkLogVisibility('milestone', 'milestones')).toBe(true);
+ expect(checkLogVisibility('info', 'milestones')).toBe(false);
+ });
+
+ it("filter 'warning' shows warnings and errors", () => {
+ expect(checkLogVisibility('warning', 'warning')).toBe(true);
+ expect(checkLogVisibility('error', 'warning')).toBe(true);
+ expect(checkLogVisibility('info', 'warning')).toBe(false);
+ expect(checkLogVisibility('milestone', 'warning')).toBe(false);
+ });
+
+ it("accepts plural 'warnings' as an alias", () => {
+ expect(checkLogVisibility('warning', 'warnings')).toBe(true);
+ expect(checkLogVisibility('error', 'warnings')).toBe(true);
+ expect(checkLogVisibility('info', 'warnings')).toBe(false);
+ });
+
+ it("filter 'error' only shows errors", () => {
+ expect(checkLogVisibility('error', 'error')).toBe(true);
+ expect(checkLogVisibility('warning', 'error')).toBe(false);
+ expect(checkLogVisibility('info', 'error')).toBe(false);
+ expect(checkLogVisibility('milestone', 'error')).toBe(false);
+ });
+
+ it("accepts plural 'errors' as an alias", () => {
+ expect(checkLogVisibility('error', 'errors')).toBe(true);
+ expect(checkLogVisibility('warning', 'errors')).toBe(false);
+ });
+
+ it('unknown filter defaults to showing everything', () => {
+ expect(checkLogVisibility('info', 'bogus')).toBe(true);
+ expect(checkLogVisibility('error', '')).toBe(true);
+ expect(checkLogVisibility('milestone', undefined)).toBe(true);
+ });
+});
+
+describe('hashString', () => {
+ it('returns "0" for empty/null/undefined', () => {
+ expect(hashString('')).toBe('0');
+ expect(hashString(null)).toBe('0');
+ expect(hashString(undefined)).toBe('0');
+ });
+
+ it('is deterministic: same input → same output', () => {
+ const a = hashString('log entry one');
+ const b = hashString('log entry one');
+ expect(a).toBe(b);
+ });
+
+ it('produces different hashes for different inputs', () => {
+ expect(hashString('log entry one')).not.toBe(hashString('log entry two'));
+ expect(hashString('a')).not.toBe(hashString('b'));
+ });
+
+ it('handles long strings', () => {
+ const long = 'x'.repeat(10000);
+ expect(hashString(long)).toMatch(/^-?\d+$/);
+ });
+
+ it('handles unicode characters', () => {
+ // Should not throw and should differ from its ASCII analogue
+ expect(hashString('café')).toMatch(/^-?\d+$/);
+ expect(hashString('café')).not.toBe(hashString('cafe'));
+ });
+});
+
+describe('normalizeMessage', () => {
+ it('returns empty string for falsy input', () => {
+ expect(normalizeMessage('')).toBe('');
+ expect(normalizeMessage(null)).toBe('');
+ expect(normalizeMessage(undefined)).toBe('');
+ });
+
+ it('trims whitespace', () => {
+ expect(normalizeMessage(' hello ')).toBe('hello');
+ expect(normalizeMessage('\t\nhello\r\n')).toBe('hello');
+ });
+
+ it('lowercases', () => {
+ expect(normalizeMessage('HELLO World')).toBe('hello world');
+ });
+
+ it('trims and lowercases in combination', () => {
+ expect(normalizeMessage(' HELLO ')).toBe('hello');
+ });
+});
+
+describe('normalizeTimestamps', () => {
+ it('is a no-op when all logs share the same date', () => {
+ const logs = [
+ {time: '2026-04-01T10:00:00Z', message: 'a'},
+ {time: '2026-04-01T11:00:00Z', message: 'b'},
+ {time: '2026-04-01T12:00:00Z', message: 'c'},
+ ];
+ const before = JSON.parse(JSON.stringify(logs));
+ normalizeTimestamps(logs);
+ expect(logs).toEqual(before);
+ });
+
+ it('re-stamps an outlier date to the majority date', () => {
+ const logs = [
+ {time: '2026-04-01T10:00:00.000Z', message: 'a'},
+ {time: '2026-04-01T11:00:00.000Z', message: 'b'},
+ {time: '2026-04-01T12:00:00.000Z', message: 'c'},
+ {time: '2026-04-02T15:30:00.000Z', message: 'outlier'},
+ ];
+ const originalTime = logs[3].time;
+ normalizeTimestamps(logs);
+ const outlier = logs[3];
+ // The outlier's date portion should now be 2026-04-01
+ expect(outlier.time.startsWith('2026-04-01')).toBe(true);
+ // The time should have changed from the original
+ expect(outlier.time).not.toBe(originalTime);
+ // ID should be regenerated from the new timestamp + hash
+ expect(outlier.id).toMatch(/^2026-04-01.*-/);
+ });
+
+ it('does nothing when logs is empty', () => {
+ const logs = [];
+ expect(() => normalizeTimestamps(logs)).not.toThrow();
+ expect(logs).toEqual([]);
+ });
+
+ it('does nothing when every log has an unparseable time', () => {
+ const logs = [
+ {time: 'not-a-date', message: 'a'},
+ {time: 'also-not-a-date', message: 'b'},
+ ];
+ // Should not throw; mostCommonDate would remain null
+ expect(() => normalizeTimestamps(logs)).not.toThrow();
+ });
+
+ it('handles a tie by picking one date deterministically (first seen wins via iteration order)', () => {
+ // Two days with equal count — either is acceptable, just shouldn't crash
+ const logs = [
+ {time: '2026-04-01T10:00:00Z', message: 'a'},
+ {time: '2026-04-02T10:00:00Z', message: 'b'},
+ ];
+ expect(() => normalizeTimestamps(logs)).not.toThrow();
+ // Both should end up on the same day
+ const d1 = logs[0].time.split('T')[0];
+ const d2 = logs[1].time.split('T')[0];
+ expect(d1).toBe(d2);
+ });
+});
diff --git a/tests/js/utils/value-helpers.test.js b/tests/js/utils/value-helpers.test.js
new file mode 100644
index 0000000000..edf39b2a88
--- /dev/null
+++ b/tests/js/utils/value-helpers.test.js
@@ -0,0 +1,164 @@
+/**
+ * Tests for utils/value-helpers.js
+ *
+ * These helpers back the settings page's "did the user change this?"
+ * detection and its "old → new" change notifications. Broken equality
+ * rules cause settings to look unchanged (silent drops) or cause
+ * spurious save notifications — both surfaced as real bugs before.
+ */
+
+import '@js/utils/value-helpers.js';
+
+const {
+ areValuesEqual,
+ areObjectsEqual,
+ formatPropertyName,
+ formatValueForDisplay,
+} = window.LdrValueHelpers;
+
+describe('areValuesEqual', () => {
+ it('treats null and undefined as interchangeable (symmetric)', () => {
+ expect(areValuesEqual(null, null)).toBe(true);
+ expect(areValuesEqual(undefined, undefined)).toBe(true);
+ expect(areValuesEqual(null, undefined)).toBe(true);
+ expect(areValuesEqual(undefined, null)).toBe(true);
+ });
+
+ it('returns false when only one side is null/undefined', () => {
+ expect(areValuesEqual(null, 0)).toBe(false);
+ expect(areValuesEqual(0, null)).toBe(false);
+ expect(areValuesEqual(undefined, '')).toBe(false);
+ expect(areValuesEqual('', undefined)).toBe(false);
+ expect(areValuesEqual(null, false)).toBe(false);
+ });
+
+ it('handles primitive equality', () => {
+ expect(areValuesEqual(1, 1)).toBe(true);
+ expect(areValuesEqual('a', 'a')).toBe(true);
+ expect(areValuesEqual(true, true)).toBe(true);
+ expect(areValuesEqual(1, 2)).toBe(false);
+ expect(areValuesEqual('a', 'b')).toBe(false);
+ });
+
+ it('coerces numeric strings to numbers for comparison', () => {
+ expect(areValuesEqual(1000, '1000')).toBe(true);
+ expect(areValuesEqual('1000', 1000)).toBe(true);
+ expect(areValuesEqual(1.5, '1.5')).toBe(true);
+ expect(areValuesEqual(1000, '1001')).toBe(false);
+ });
+
+ it('returns false for mismatched types other than number/string', () => {
+ expect(areValuesEqual(true, 1)).toBe(false);
+ expect(areValuesEqual(false, 0)).toBe(false);
+ expect(areValuesEqual({}, 'object')).toBe(false);
+ });
+
+ it('compares arrays by length then deep equality', () => {
+ expect(areValuesEqual([1, 2, 3], [1, 2, 3])).toBe(true);
+ expect(areValuesEqual([], [])).toBe(true);
+ expect(areValuesEqual([1, 2], [1, 2, 3])).toBe(false);
+ expect(areValuesEqual([1, 2, 3], [1, 3, 2])).toBe(false); // order matters
+ expect(areValuesEqual([{a: 1}], [{a: 1}])).toBe(true);
+ });
+
+ it('compares objects by JSON stringification', () => {
+ expect(areValuesEqual({a: 1, b: 2}, {a: 1, b: 2})).toBe(true);
+ expect(areValuesEqual({a: 1}, {a: 2})).toBe(false);
+ expect(areValuesEqual({}, {})).toBe(true);
+ });
+
+ it('does not confuse an array with an equivalent object', () => {
+ // [] stringifies as "[]" and {} as "{}", so these differ
+ expect(areValuesEqual([], {})).toBe(false);
+ });
+});
+
+describe('areObjectsEqual', () => {
+ it('treats empty objects as equal', () => {
+ expect(areObjectsEqual({}, {})).toBe(true);
+ });
+
+ it('returns false when key counts differ', () => {
+ expect(areObjectsEqual({a: 1}, {a: 1, b: 2})).toBe(false);
+ expect(areObjectsEqual({a: 1, b: 2}, {a: 1})).toBe(false);
+ });
+
+ it('returns false when a key is missing on the other side', () => {
+ expect(areObjectsEqual({a: 1}, {b: 1})).toBe(false);
+ });
+
+ it('delegates value comparison to areValuesEqual', () => {
+ // Numeric string coercion works via areValuesEqual
+ expect(areObjectsEqual({port: 8080}, {port: '8080'})).toBe(true);
+ });
+
+ it('recurses through nested objects via areValuesEqual', () => {
+ expect(areObjectsEqual(
+ {nested: {a: 1, b: [2, 3]}},
+ {nested: {a: 1, b: [2, 3]}}
+ )).toBe(true);
+ expect(areObjectsEqual(
+ {nested: {a: 1}},
+ {nested: {a: 2}}
+ )).toBe(false);
+ });
+});
+
+describe('formatPropertyName', () => {
+ it('converts snake_case to Title Case', () => {
+ expect(formatPropertyName('llm_provider')).toBe('Llm Provider');
+ expect(formatPropertyName('max_output_tokens')).toBe('Max Output Tokens');
+ });
+
+ it('handles a single word', () => {
+ expect(formatPropertyName('provider')).toBe('Provider');
+ });
+
+ it('handles an already-capitalized word', () => {
+ expect(formatPropertyName('Provider')).toBe('Provider');
+ });
+});
+
+describe('formatValueForDisplay', () => {
+ it('returns "empty" for null and undefined', () => {
+ expect(formatValueForDisplay(null)).toBe('empty');
+ expect(formatValueForDisplay(undefined)).toBe('empty');
+ });
+
+ it('returns "enabled"/"disabled" for booleans', () => {
+ expect(formatValueForDisplay(true)).toBe('enabled');
+ expect(formatValueForDisplay(false)).toBe('disabled');
+ });
+
+ it('wraps short strings in quotes', () => {
+ expect(formatValueForDisplay('hello')).toBe('"hello"');
+ expect(formatValueForDisplay('')).toBe('""');
+ });
+
+ it('truncates strings longer than 20 chars', () => {
+ const long = 'a'.repeat(25);
+ const result = formatValueForDisplay(long);
+ expect(result).toBe('"' + 'a'.repeat(18) + '..."');
+ expect(result.length).toBeLessThan(long.length + 2);
+ });
+
+ it('keeps 20-char strings as-is (boundary)', () => {
+ const twenty = 'a'.repeat(20);
+ expect(formatValueForDisplay(twenty)).toBe(`"${twenty}"`);
+ });
+
+ it('truncates 21-char strings (off-by-one boundary)', () => {
+ const twentyOne = 'a'.repeat(21);
+ expect(formatValueForDisplay(twentyOne)).toBe('"' + 'a'.repeat(18) + '..."');
+ });
+
+ it('shows objects as "{...}"', () => {
+ expect(formatValueForDisplay({a: 1})).toBe('{...}');
+ });
+
+ it('coerces numbers to their string form', () => {
+ expect(formatValueForDisplay(42)).toBe('42');
+ expect(formatValueForDisplay(0)).toBe('0');
+ expect(formatValueForDisplay(3.14)).toBe('3.14');
+ });
+});