~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(js): extract research status constants and predicate helpers (#3296)
LearningCircuitd6ec804ca162
diff --git a/src/local_deep_research/constants.py b/src/local_deep_research/constants.pyindex 73a5368b53..5ab8803743 100644--- a/src/local_deep_research/constants.py+++ b/src/local_deep_research/constants.py@@ -21,6 +21,10 @@ BROWSER_USER_AGENT = (# --- Research status values ---+# Frontend helpers: src/local_deep_research/web/static/js/config/constants.js+# Injected via: src/local_deep_research/web/app_factory.py (inject_frontend_constants)+# Template: src/local_deep_research/web/templates/base.html+# If you add/remove/rename a status here, the frontend picks it up automatically.class ResearchStatus(StrEnum):"""Status values for research records.diff --git a/src/local_deep_research/web/app_factory.py b/src/local_deep_research/web/app_factory.pyindex 1688f37ace..377fa03892 100644--- a/src/local_deep_research/web/app_factory.py+++ b/src/local_deep_research/web/app_factory.py@@ -546,6 +546,27 @@ def apply_middleware(app):app.before_request(flush_log_queue)logger.info("Log flushing middleware registered")+ # Inject backend constants into Jinja2 templates for frontend JS.+ # This is the Flask-documented pattern for sharing Python enums with JavaScript.+ # Source of truth: src/local_deep_research/constants.py::ResearchStatus+ # Frontend helpers: src/local_deep_research/web/static/js/config/constants.js+ # Template injection: src/local_deep_research/web/templates/base.html+ from ..constants import ResearchStatus++ @app.context_processor+ def inject_frontend_constants():+ terminal = [+ ResearchStatus.COMPLETED,+ ResearchStatus.SUSPENDED,+ ResearchStatus.FAILED,+ ResearchStatus.ERROR,+ ResearchStatus.CANCELLED,+ ]+ return {+ "research_status_enum": {m.name: m.value for m in ResearchStatus},+ "research_terminal_states": [str(s) for s in terminal],+ }+# Clean up database sessions after each request@app.teardown_appcontextdef cleanup_db_session(exception=None):diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex cc814b59dc..b7fb20f67b 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -375,15 +375,15 @@ function startPolling() {updateProgressFromStatus(data);// Stop polling if indexing is done- if (['completed', 'failed', 'cancelled', 'idle'].includes(data.status)) {+ if (ResearchStates.isTerminal(data.status) || data.status === 'idle') {clearInterval(indexingPollInterval);indexingPollInterval = null;- if (data.status === 'completed') {+ if (ResearchStates.isCompleted(data.status)) {addLogEntry(data.progress_message || 'Indexing completed!', 'success');- } else if (data.status === 'failed') {+ } else if (ResearchStates.isFailed(data.status)) {addLogEntry(`Indexing failed: ${data.error_message || 'Unknown error'}`, 'error');- } else if (data.status === 'cancelled') {+ } else if (ResearchStates.isCancelled(data.status)) {addLogEntry('Indexing was cancelled', 'warning');}diff --git a/src/local_deep_research/web/static/js/components/fallback/formatting.js b/src/local_deep_research/web/static/js/components/fallback/formatting.jsindex 82109524f5..8ca9a0dd9d 100644--- a/src/local_deep_research/web/static/js/components/fallback/formatting.js+++ b/src/local_deep_research/web/static/js/components/fallback/formatting.js@@ -41,18 +41,7 @@* @returns {string} Formatted status*/function formatStatus(status) {- if (!status) return 'Unknown';-- const statusMap = {- 'in_progress': 'In Progress',- 'completed': 'Completed',- 'failed': 'Failed',- 'suspended': 'Suspended',- 'pending': 'Pending',- 'error': 'Error'- };-- return statusMap[status] || status;+ return ResearchStates.formatStatus(status);}/**diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.jsindex 07aea1b08c..97a6e549b9 100644--- a/src/local_deep_research/web/static/js/components/history.js+++ b/src/local_deep_research/web/static/js/components/history.js@@ -252,7 +252,7 @@handleRerun(itemData);} else {// Item-level click (navigate to results/progress)- if (itemData.status === 'completed') {+ if (ResearchStates.isCompleted(itemData.status)) {URLValidator.safeAssign(window.location, 'href', URLBuilder.resultsPage(itemId));} else {URLValidator.safeAssign(window.location, 'href', URLBuilder.progressPage(itemId));@@ -356,22 +356,10 @@}/**- * Format status safely using the formatter if available+ * Format status safely using ResearchStates helper*/function formatStatus(status) {- if (window.formatting && window.formatting.formatStatus) {- return window.formatting.formatStatus(status);- }-- // Simple fallback formatting- const statusMap = {- 'in_progress': 'In Progress',- 'completed': 'Completed',- 'failed': 'Failed',- 'suspended': 'Suspended'- };-- return statusMap[status] || status;+ return ResearchStates.formatStatus(status);}/**@@ -437,19 +425,19 @@${isNewsItem ? '<span class="ldr-news-indicator"><i class="fas fa-newspaper"></i> News</span>' : ''}</div><div class="ldr-history-item-actions">- ${item.status === 'completed' ?+ ${ResearchStates.isCompleted(item.status) ?`<button class="btn btn-sm ldr-btn-outline ldr-view-btn"><i class="fas fa-eye"></i><span> View</span></button>` : ''}- ${item.status === 'completed' && item.document_count > 0 ?+ ${ResearchStates.isCompleted(item.status) && item.document_count > 0 ?`<button class="btn btn-sm ldr-btn-outline ldr-library-btn"><i class="fas fa-book"></i><span> Library (${esc(String(item.document_count))})</span></button>` : ''}- ${isNewsItem && item.status === 'completed' ?+ ${isNewsItem && ResearchStates.isCompleted(item.status) ?`<button class="btn btn-sm ldr-btn-outline ldr-subscribe-btn" data-research-id="${esc(item.id)}" data-query="${esc(encodeURIComponent(item.query))}"><i class="fas fa-bell"></i><span> Subscribe</span></button>` : ''}- ${item.status === 'completed' ?+ ${ResearchStates.isCompleted(item.status) ?`<button class="btn btn-sm ldr-btn-outline ldr-rerun-btn" title="Re-run this research"><i class="fas fa-redo"></i><span> Re-run</span></button>` : ''}diff --git a/src/local_deep_research/web/static/js/components/history_search.js b/src/local_deep_research/web/static/js/components/history_search.jsindex 6230b40194..8dc7d75480 100644--- a/src/local_deep_research/web/static/js/components/history_search.js+++ b/src/local_deep_research/web/static/js/components/history_search.js@@ -242,20 +242,20 @@ function startPolling() {}// Stop polling on terminal states- if (['completed', 'failed', 'cancelled', 'idle'].includes(data.status)) {+ if (ResearchStates.isTerminal(data.status) || data.status === 'idle') {clearInterval(indexingPollInterval);indexingPollInterval = null;isIndexing = false;- if (data.status === 'completed') {+ if (ResearchStates.isCompleted(data.status)) {if (progressBar) progressBar.style.width = '100%';if (progressText) progressText.textContent = data.progress_message || 'Indexing complete!';- } else if (data.status === 'failed') {+ } else if (ResearchStates.isFailed(data.status)) {if (progressText) {progressText.textContent = `Indexing failed: ${data.error_message || 'Unknown error'}`;progressText.style.color = 'var(--error-color)';}- } else if (data.status === 'cancelled') {+ } else if (ResearchStates.isCancelled(data.status)) {if (progressText) progressText.textContent = 'Indexing was cancelled.';}diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.jsindex 10efc2f1ca..9b868e4c44 100644--- a/src/local_deep_research/web/static/js/components/progress.js+++ b/src/local_deep_research/web/static/js/components/progress.js@@ -346,7 +346,7 @@}// Check if research is completed- if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ if (ResearchStates.isTerminal(data.status)) {handleResearchCompletion(data);}@@ -360,25 +360,6 @@// This prevents tasks from being overwritten by empty updates}- /**- * Determine log level based on status- * @param {string} status - The research status- * @returns {string} Log level (info, milestone, error, etc)- */- function determineLogLevel(status) {- if (!status) return 'info';-- if (status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'error') {- return 'milestone';- }-- if (status === 'error' || status.includes('error')) {- return 'error';- }-- return 'info';- }-/*** Check research progress via API*/@@ -399,7 +380,7 @@updateProgressUI(data);// Check if research is completed- if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ if (ResearchStates.isTerminal(data.status)) {handleResearchCompletion(data);} else {// Set up polling for status updates as backup for socket@@ -467,28 +448,13 @@// Update status text with better formattingif (data.status && statusText) {let formattedStatus;- if (window.formatting && typeof window.formatting.formatStatus === 'function') {+ if (ResearchStates.isInProgress(data.status)) {+ // Don't show "In Progress" at all in status text+ formattedStatus = null;+ } else if (window.formatting && typeof window.formatting.formatStatus === 'function') {formattedStatus = window.formatting.formatStatus(data.status);} else {- // Manual status formatting for better display- switch (data.status) {- case 'in_progress':- // Don't show "In Progress" at all in status text- formattedStatus = null; // Don't update status text for in_progress- break;- case 'completed':- formattedStatus = 'Completed';- break;- case 'failed':- formattedStatus = 'Failed';- break;- case 'cancelled':- formattedStatus = 'Cancelled';- break;- default:- formattedStatus = data.status.charAt(0).toUpperCase() +- data.status.slice(1).replace(/_/g, ' ');- }+ formattedStatus = ResearchStates.formatStatus(data.status);}// Only update status text if we have a non-empty formatted status@@ -584,7 +550,7 @@case 'reviewing':statusMsg = 'Reviewing and finalizing report...';break;- case 'in_progress':+ case window.RESEARCH_STATUS.IN_PROGRESS:// Don't overwrite existing content with generic "In Progress" messageif (!currentTaskText.dataset.lastMessage || currentTaskText.textContent === '') {statusMsg = 'Performing research...';@@ -615,18 +581,18 @@// Update favicon based on statusif (window.ui && typeof window.ui.updateFavicon === 'function') {- window.ui.updateFavicon(data.status || 'in_progress');+ window.ui.updateFavicon(data.status || window.RESEARCH_STATUS.IN_PROGRESS);}// Show notification if enabled- if (data.status === 'completed' && notificationsEnabled) {+ if (ResearchStates.isCompleted(data.status) && notificationsEnabled) {showNotification('Research Completed', 'Your research has been completed successfully.');}// Ensure log entry is added if message exists but no specific log_entryif (data.message && window.addConsoleLog && !data.log_entry) {SafeLogger.log('Adding message to console log:', data.message);- window.addConsoleLog(data.message, determineLogLevel(data.status));+ window.addConsoleLog(data.message, ResearchStates.logLevel(data.status));}}@@ -645,7 +611,7 @@}// Update UI for completion- if (data.status === 'completed') {+ if (ResearchStates.isCompleted(data.status)) {// Show view results buttonif (viewResultsButton) {viewResultsButton.style.display = 'inline-block';@@ -659,9 +625,9 @@// Check for context overflow and show warning toastcheckContextOverflowOnCompletion();- } else if (data.status === 'failed' || data.status === 'cancelled') {+ } else if (ResearchStates.isFailed(data.status) || ResearchStates.isCancelled(data.status)) {// For failed research, try to show the error report if available- if (data.status === 'failed') {+ if (ResearchStates.isFailed(data.status)) {if (viewResultsButton) {viewResultsButton.textContent = 'View Error Report';URLValidator.safeAssign(viewResultsButton, 'href', URLBuilder.resultsPage(currentResearchId));@@ -915,11 +881,11 @@// Process statusif (status) {// If complete, show complete UI- if (status.status === 'completed') {+ if (ResearchStates.isCompleted(status.status)) {handleResearchComplete({ research_id: currentResearchId });}- // If error, show error UI- else if (status.status === 'error') {+ // If failed/error, show error UI+ else if (ResearchStates.isFailed(status.status)) {handleResearchError({research_id: currentResearchId,error: status.message || 'Unknown error'@@ -950,7 +916,7 @@// Update UIsetProgressValue(100);- setStatus('completed');+ setStatus(window.RESEARCH_STATUS.COMPLETED);setCurrentTask('Research completed successfully');// Hide cancel button@@ -985,7 +951,7 @@// Update UI to error statesetProgressValue(100);- setStatus('error');+ setStatus(window.RESEARCH_STATUS.ERROR);setCurrentTask(`Error: ${data.error || 'Unknown error'}`);// Add error class to progress bar@@ -1054,28 +1020,7 @@function setStatus(status) {if (!statusText) return;- let statusDisplay = 'Unknown';-- // Map status to display text- switch (status) {- case 'not_started':- statusDisplay = 'Not Started';- break;- case 'in_progress':- statusDisplay = 'In Progress';- break;- case 'completed':- statusDisplay = 'Completed';- break;- case 'cancelled':- statusDisplay = 'Cancelled';- break;- case 'error':- statusDisplay = 'Error';- break;- default:- statusDisplay = status ? status.charAt(0).toUpperCase() + status.slice(1) : 'Unknown';- }+ const statusDisplay = ResearchStates.formatStatus(status) || 'Unknown';statusText.textContent = statusDisplay;}@@ -1096,7 +1041,7 @@function setErrorState(message) {// Update progress UIsetProgressValue(100);- setStatus('error');+ setStatus(window.RESEARCH_STATUS.ERROR);setCurrentTask(`Error: ${message}`);// Add error class to progress bardiff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.jsindex b5028965a9..0141f01ae8 100644--- a/src/local_deep_research/web/static/js/components/research.js+++ b/src/local_deep_research/web/static/js/components/research.js@@ -2383,10 +2383,10 @@}).then(response => response.json()).then(data => {- if (data.status === 'success' || data.status === 'queued') {+ if (data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) {SafeLogger.log('Research started:', data);- if (data.status === 'queued') {+ if (data.status === window.RESEARCH_STATUS.QUEUED) {showAlert(data.message || 'Your research has been queued.', 'info');}diff --git a/src/local_deep_research/web/static/js/config/constants.js b/src/local_deep_research/web/static/js/config/constants.jsindex 10f2b0c868..bce6f69826 100644--- a/src/local_deep_research/web/static/js/config/constants.js+++ b/src/local_deep_research/web/static/js/config/constants.js@@ -1,6 +1,19 @@/*** Shared constants for the Local Deep Research frontend.* Loaded globally via base.html — available to all pages.+ *+ * Research status values (window.RESEARCH_STATUS) are injected from+ * the Python backend via Jinja2 context processor in:+ * src/local_deep_research/web/app_factory.py (inject_frontend_constants)+ *+ * The single source of truth for all status values is:+ * src/local_deep_research/constants.py::ResearchStatus+ *+ * The template injection happens in:+ * src/local_deep_research/web/templates/base.html+ *+ * No fallback strings are used — if RESEARCH_STATUS is not injected,+ * the app is broken anyway (base.html renders every page).*/if (typeof LDR_CONSTANTS !== 'undefined') {@@ -16,3 +29,83 @@ if (typeof LDR_CONSTANTS !== 'undefined') {},};}++/**+ * Research status predicate helpers and formatting utilities.+ *+ * Uses window.RESEARCH_STATUS (injected from Python via base.html)+ * and window.RESEARCH_TERMINAL_STATES for O(1) terminal-state lookups.+ *+ * Usage:+ * if (ResearchStates.isTerminal(data.status)) { ... }+ * if (ResearchStates.isCancelled(data.status)) { ... }+ * label.textContent = ResearchStates.formatStatus(data.status);+ */+window.ResearchStates = Object.freeze({+ /** True for completed, suspended, failed, error, cancelled */+ isTerminal: function(status) {+ return window.RESEARCH_TERMINAL_STATES.has(status);+ },++ /** True only for successfully completed research */+ isCompleted: function(status) {+ return status === window.RESEARCH_STATUS.COMPLETED;+ },++ /** True for failed research (unrecoverable error, includes legacy 'error' status) */+ isFailed: function(status) {+ return status === window.RESEARCH_STATUS.FAILED+ || status === window.RESEARCH_STATUS.ERROR;+ },++ /** True for user-cancelled research (cancelled or suspended) */+ isCancelled: function(status) {+ return status === window.RESEARCH_STATUS.CANCELLED+ || status === window.RESEARCH_STATUS.SUSPENDED;+ },++ /** True only for research currently executing (not queued/pending) */+ isInProgress: function(status) {+ return status === window.RESEARCH_STATUS.IN_PROGRESS;+ },++ /** True for actively running or waiting research */+ isActive: function(status) {+ return status === window.RESEARCH_STATUS.IN_PROGRESS+ || status === window.RESEARCH_STATUS.QUEUED+ || status === window.RESEARCH_STATUS.PENDING;+ },++ /** Map status to human-readable display label */+ formatStatus: function(status) {+ var RS = window.RESEARCH_STATUS;+ var labels = {};+ labels[RS.IN_PROGRESS] = 'In Progress';+ labels[RS.COMPLETED] = 'Completed';+ labels[RS.FAILED] = 'Failed';+ labels[RS.SUSPENDED] = 'Cancelled';+ labels[RS.CANCELLED] = 'Cancelled';+ labels[RS.QUEUED] = 'Queued';+ labels[RS.PENDING] = 'Pending';+ labels[RS.ERROR] = 'Error';+ labels['not_started'] = 'Not Started';++ return labels[status] || (status+ ? status.charAt(0).toUpperCase() + status.slice(1).replace(/_/g, ' ')+ : 'Unknown');+ },++ /** Determine log level for a given research status */+ logLevel: function(status) {+ if (!status) return 'info';+ // Check error before terminal — 'error' is in terminal set but should log as error+ if (status === window.RESEARCH_STATUS.ERROR+ || (typeof status === 'string' && status.includes('error'))) {+ return 'error';+ }+ if (window.RESEARCH_TERMINAL_STATES.has(status)) {+ return 'milestone';+ }+ return 'info';+ },+});diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex d0c8593e5b..1845747a1a 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -512,7 +512,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', modelconst data = await response.json();SafeLogger.log('Research API response:', data);- if ((data.status === 'success' || data.status === 'queued') && data.research_id) {+ if ((data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) && data.research_id) {showAlert('Analyzing news... Results will appear below when ready.', 'info');// Show loading state in news feed FIRST@@ -1509,7 +1509,7 @@ async function checkPriorityStatus() {const data = await response.json();// Filter out news searches from active research displayconst activeResearch = data.items?.filter(item =>- item.status === 'in_progress' &&+ ResearchStates.isActive(item.status) &&!item.metadata?.is_news_search) || [];@@ -2473,7 +2473,7 @@ async function monitorResearch(researchId, query = null) {</div><div class="ldr-news-meta"><span><i class="bi bi-info-circle"></i> Research ID: ${escapeHtml(researchId)}</span>- <span><i class="bi bi-clock"></i> ${statusData.status === 'in_progress' ? 'In progress' : 'Started just now'}</span>+ <span><i class="bi bi-clock"></i> ${ResearchStates.isInProgress(statusData.status) ? 'In progress' : 'Started just now'}</span></div><div class="ldr-news-summary"><div class="progress" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="${Number(statusData.progress) || 10}" aria-label="Research progress">@@ -2505,7 +2505,7 @@ async function monitorResearch(researchId, query = null) {// Update progress cardconst progressCard = document.querySelector(`[data-research-id="${researchId}"]`);- if (progressCard && data.status === 'in_progress') {+ if (progressCard && ResearchStates.isInProgress(data.status)) {const progressValue = data.progress || 10;// Update ARIA on container and width on fillconst progressContainer = progressCard.querySelector('[role="progressbar"]');@@ -2522,7 +2522,7 @@ async function monitorResearch(researchId, query = null) {}}- if (data.status === 'completed') {+ if (ResearchStates.isCompleted(data.status)) {clearInterval(checkInterval);localStorage.removeItem('active_news_research'); // Clear from localStorageSafeLogger.log('Research completed, reloading news feed');@@ -2541,7 +2541,7 @@ async function monitorResearch(researchId, query = null) {setTimeout(() => {loadNewsFeed();}, 1000);- } else if (data.status === 'failed' || data.status === 'error') {+ } else if (ResearchStates.isFailed(data.status)) {clearInterval(checkInterval);localStorage.removeItem('active_news_research'); // Clear from localStorage// Remove progress card@@ -2588,10 +2588,10 @@ async function checkActiveNewsResearch() {const status = await statusResponse.json();- if (status.status === 'in_progress') {+ if (ResearchStates.isInProgress(status.status)) {// Use monitorResearch to show the progress card and handle pollingmonitorResearch(researchId, query);- } else if (status.status === 'completed') {+ } else if (ResearchStates.isCompleted(status.status)) {// Research completed while user was awaylocalStorage.removeItem('active_news_research');showAlert('Your news analysis has completed! Loading results...', 'success');@@ -2649,7 +2649,7 @@ async function pollForNewsResearchResults(researchId, originalQuery, isResume =}}- if (status.status === 'completed') {+ if (ResearchStates.isCompleted(status.status)) {clearInterval(pollInterval);localStorage.removeItem('active_news_research');@@ -2665,7 +2665,7 @@ async function pollForNewsResearchResults(researchId, originalQuery, isResume =setTimeout(() => {loadNewsFeed();}, 1000);- } else if (status.status === 'error' || status.status === 'failed' || status.status === 'suspended') {+ } else if (ResearchStates.isTerminal(status.status) && !ResearchStates.isCompleted(status.status)) {clearInterval(pollInterval);localStorage.removeItem('active_news_research');showAlert(`Research ${status.status}: ${status.metadata?.error || 'Unknown error'}`, 'error');diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.jsindex ab2a57c997..95b93fcbb4 100644--- a/src/local_deep_research/web/static/js/pages/subscriptions.js+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js@@ -333,7 +333,7 @@ async function runSubscriptionNow(subscriptionId) {const data = await response.json();SafeLogger.log('Research API response:', data);- if ((data.status === 'success' || data.status === 'queued') && data.research_id) {+ if ((data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) && data.research_id) {// Validate research_id is a safe UUID format before using in URLconst safeResearchId = String(data.research_id).replace(/[^a-zA-Z0-9-]/g, '');showAlert(`Research started! <a href="/progress/${safeResearchId}" style="color: white; text-decoration: underline;">View progress</a>`, 'success');diff --git a/src/local_deep_research/web/static/js/services/formatting.js b/src/local_deep_research/web/static/js/services/formatting.jsindex e9b9eb9662..0c7125c9c7 100644--- a/src/local_deep_research/web/static/js/services/formatting.js+++ b/src/local_deep_research/web/static/js/services/formatting.js@@ -8,13 +8,7 @@* @returns {string} The formatted status string*/function formatStatus(status) {- switch(status) {- case 'in_progress': return 'In Progress';- case 'completed': return 'Completed';- case 'failed': return 'Failed';- case 'suspended': return 'Suspended';- default: return status.charAt(0).toUpperCase() + status.slice(1);- }+ return ResearchStates.formatStatus(status);}/**diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex e7904c82ed..156005e2c4 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -432,7 +432,7 @@ window.socket = (function() {// Record this messagewindow._processedSocketMessages.set(messageKey, Date.now());- window.addConsoleLog(data.message, determineLogLevel(data.status));+ window.addConsoleLog(data.message, ResearchStates.logLevel(data.status));}}@@ -456,25 +456,6 @@ window.socket = (function() {}}- /**- * Determine log level based on status- * @param {string} status - The research status- * @returns {string} Log level (info, milestone, error, etc)- */- function determineLogLevel(status) {- if (!status) return 'info';-- if (status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'error') {- return 'milestone';- }-- if (status === 'error' || status.includes('error')) {- return 'error';- }-- return 'info';- }-/*** Add a log entry to the console log container* @param {Object} logEntry - The log entry data@@ -583,7 +564,7 @@ window.socket = (function() {handleProgressUpdate(id, data);// Stop polling if the research is complete- if (data.status === 'completed' || data.status === 'failed' || data.status === 'cancelled') {+ if (ResearchStates.isTerminal(data.status)) {clearInterval(pollInterval);}}diff --git a/src/local_deep_research/web/static/js/services/ui.js b/src/local_deep_research/web/static/js/services/ui.jsindex 5dd0cb66f4..32eefe22c1 100644--- a/src/local_deep_research/web/static/js/services/ui.js+++ b/src/local_deep_research/web/static/js/services/ui.js@@ -388,11 +388,11 @@ function updateFavicon(status) {// Background color based on statuslet bgColor = accentColor; // Default accent- if (status === 'completed') {+ if (ResearchStates.isCompleted(status)) {bgColor = successColor;- } else if (status === 'failed' || status === 'error') {+ } else if (ResearchStates.isFailed(status)) {bgColor = errorColor;- } else if (status === 'cancelled') {+ } else if (ResearchStates.isCancelled(status)) {bgColor = mutedColor;}diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.htmlindex 64b1668b0d..ed665fe15b 100644--- a/src/local_deep_research/web/templates/base.html+++ b/src/local_deep_research/web/templates/base.html@@ -133,6 +133,15 @@<!-- Safe Logger (must load first — theme.js, keyboard.js, help.js call SafeLogger at exec time) --><script defer src="/static/js/security/safe-logger.js"></script>+ <!-- Backend constants injected from Python (single source of truth) -->+ <!-- Source: src/local_deep_research/constants.py::ResearchStatus -->+ <!-- Injected by: src/local_deep_research/web/app_factory.py (inject_frontend_constants) -->+ <!-- Consumed by: src/local_deep_research/web/static/js/config/constants.js (ResearchStates helpers) -->+ <script>+ window.RESEARCH_STATUS = Object.freeze({{ research_status_enum | tojson }});+ window.RESEARCH_TERMINAL_STATES = Object.freeze(new Set({{ research_terminal_states | tojson }}));+ </script>+<!-- Constants and URL Configuration --><script defer src="/static/js/config/constants.js"></script><script defer src="/static/js/config/urls.js"></script>