~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(ui): preserve page alerts after #6719 (#7041)
LearningCircuit12dc5a93f5e3
diff --git a/changelog.d/6585.bugfix.md b/changelog.d/6585.bugfix.mdnew file mode 100644index 0000000000..34f0424dd9--- /dev/null+++ b/changelog.d/6585.bugfix.md@@ -0,0 +1 @@+Collection, embedding-settings, and news pages display their own error and status alerts again. Shared deferred UI helpers had overwritten same-named page helpers, silently dropping feedback. The page helpers now have distinct names, and the global-name collision test covers all affected scripts.diff --git a/src/local_deep_research/web/static/js/collection_create.js b/src/local_deep_research/web/static/js/collection_create.jsindex 4977863ff9..997720c8ac 100644--- a/src/local_deep_research/web/static/js/collection_create.js+++ b/src/local_deep_research/web/static/js/collection_create.js@@ -57,7 +57,7 @@ async function handleCreateCollection(e) {const description = formData.get('description');if (!name || name.trim().length === 0) {- showError('Collection name is required');+ showCollectionCreateError('Collection name is required');return;}@@ -111,11 +111,11 @@ async function handleCreateCollection(e) {}}, 1500);} else {- showError(data.error || 'Failed to create collection');+ showCollectionCreateError(data.error || 'Failed to create collection');}} catch (error) {SafeLogger.error('Error creating collection:', error);- showError('Failed to create collection: ' + error.message);+ showCollectionCreateError('Failed to create collection: ' + error.message);} finally {submitBtn.disabled = false;submitBtn.innerHTML = '<i class="fas fa-folder-plus"></i> Create Collection';@@ -170,7 +170,7 @@ function showCreateResults(data) {/*** Show error message*/-function showError(message) {+function showCollectionCreateError(message) {const resultsDiv = document.getElementById('create-results');const escapeHtml = window.escapeHtml || escapeHtmlFallback;const html = `diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.jsindex e89e4887a9..2ac5956bc4 100644--- a/src/local_deep_research/web/static/js/collection_details.js+++ b/src/local_deep_research/web/static/js/collection_details.js@@ -875,7 +875,18 @@ function showSuccess(message) {}/**- * Show error message+ * Show error message.+ *+ * The name is deliberately page-specific. This script is loaded from+ * collection_details.html's `{% block content %}`, which base.html renders+ * BEFORE its shared deferred scripts (services/ui.js and friends), so a+ * top-level `showError` here is executed first and then overwritten by+ * ui.js's `showError(container, message)` — which reads the message as a+ * container id, finds no element, and renders nothing: every error on this+ * page was silently dropped. `showSuccess` has no shared counterpart and+ * keeps its plain name. See+ * tests/web/test_notes_js_global_shadowing.py, which sweeps this file's+ * top-level names against the shared scripts.*/function showCollectionError(message) {alert('Error: ' + message);diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.jsindex d93d295fb6..7c094634d5 100644--- a/src/local_deep_research/web/static/js/collection_upload.js+++ b/src/local_deep_research/web/static/js/collection_upload.js@@ -301,7 +301,7 @@ async function handleUploadFiles(e) {e.preventDefault();if (selectedFiles.length === 0) {- showError('Please select at least one file to upload.');+ showCollectionUploadError('Please select at least one file to upload.');return;}@@ -343,7 +343,7 @@ async function handleUploadFiles(e) {}} catch (error) {SafeLogger.error('Error uploading files:', error);- showError('Upload failed: ' + error.message);+ showCollectionUploadError('Upload failed: ' + error.message);} finally {submitBtn.disabled = false;submitBtn.innerHTML = '<i class="fas fa-upload"></i> 🚀 Upload Files';@@ -545,7 +545,7 @@ async function handleSingleUpload(updateProgressComplete(data);scheduleUploadCompletion(data, requestGeneration, selectionGeneration);} else {- showError(data.error || 'Upload failed');+ showCollectionUploadError(data.error || 'Upload failed');}}@@ -878,7 +878,7 @@ function showUploadResults(data) {* SECURITY: message receives user-controlled data (error.message at line 337,* data.error at line 512) — escapeHtml() is required to prevent XSS.*/-function showError(message) {+function showCollectionUploadError(message) {const progressDiv = document.getElementById('upload-progress');const resultsDiv = document.getElementById('upload-results');diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.jsindex cb37524cda..faa0a9e4c2 100644--- a/src/local_deep_research/web/static/js/collections_manager.js+++ b/src/local_deep_research/web/static/js/collections_manager.js@@ -359,11 +359,11 @@ async function loadCollections() {renderCollections();}} else {- showError('Failed to load collections: ' + data.error);+ showCollectionsError('Failed to load collections: ' + data.error);}} catch (error) {SafeLogger.error('Error loading collections:', error);- showError('Failed to load collections');+ showCollectionsError('Failed to load collections');}}@@ -529,7 +529,7 @@ async function triggerReindex(btn) {// poll so the button tracks the in-flight task to completion.if (response.status !== 409) {SafeLogger.error('Failed to start reindex:', data.error);- showError(data.error || 'Failed to start indexing');+ showCollectionsError(data.error || 'Failed to start indexing');setBusy(false, originalLabel);return;}@@ -544,14 +544,14 @@ async function triggerReindex(btn) {const durable = Number.isInteger(result.durable_indexed_documents)? ` Durable vector store: ${result.durable_indexed_documents} document(s), ${result.durable_indexed_chunks || 0} chunk(s).`: '';- showError((finalStatus.error_message || finalStatus.error || 'Indexing failed') + durable);+ showCollectionsError((finalStatus.error_message || finalStatus.error || 'Indexing failed') + durable);} else if (finalStatus.status === 'timeout') {- showError('Indexing is taking longer than expected. It may still be running in the background — refresh to check.');+ showCollectionsError('Indexing is taking longer than expected. It may still be running in the background — refresh to check.');}}} catch (error) {SafeLogger.error('Error starting reindex:', error);- showError('Failed to start indexing');+ showCollectionsError('Failed to start indexing');setBusy(false, originalLabel);return;}@@ -634,7 +634,7 @@ function showSuccess(message) {/*** Show error message*/-function showError(message) {+function showCollectionsError(message) {alert('Error: ' + message);}diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.jsindex 3d768ddbd7..981edc7fea 100644--- a/src/local_deep_research/web/static/js/embedding_settings.js+++ b/src/local_deep_research/web/static/js/embedding_settings.js@@ -92,12 +92,12 @@ async function loadAvailableModels() {// Update provider informationupdateProviderInfo();} else {- showError('Failed to load available models: ' + data.error);+ showEmbeddingSettingsError('Failed to load available models: ' + data.error);}} catch (error) {if (currentLoadId !== availableModelsLoadId) return;SafeLogger.error('Error loading models:', error.message || error);- showError('Failed to load available models');+ showEmbeddingSettingsError('Failed to load available models');}}@@ -479,7 +479,7 @@ async function saveSetting(key, value, displayName, oldValue) {'error');} else {- showError('Failed to save ' + displayName + ': ' + error.message);+ showEmbeddingSettingsError('Failed to save ' + displayName + ': ' + error.message);}} finally {if (pendingSettingSaveByKey.get(key) === saveRequest) {@@ -973,7 +973,7 @@ async function testConfiguration() {const testResult = document.getElementById('test-result');if (!provider || !model) {- showError('Please select a provider and model first');+ showEmbeddingSettingsError('Please select a provider and model first');return;}@@ -1026,7 +1026,7 @@ async function testConfiguration() {</div>`;// Safe: showError escapes internally- showError('Embedding test failed: ' + (data.error || 'Unknown error'));+ showEmbeddingSettingsError('Embedding test failed: ' + (data.error || 'Unknown error'));}} catch (error) {// bearer:disable javascript_lang_dangerous_insert_html@@ -1037,7 +1037,7 @@ async function testConfiguration() {</div>`;// Safe: showError escapes internally- showError('Test failed: ' + error.message);+ showEmbeddingSettingsError('Test failed: ' + error.message);} finally {// Re-enable buttontestBtn.disabled = false;@@ -1095,7 +1095,7 @@ function showInfo(message) {* Show error message.* @param {string} message - Raw, unescaped text. HTML-escaping is handled internally.*/-function showError(message) {+function showEmbeddingSettingsError(message) {const alertDiv = document.createElement('div');alertDiv.className = 'ldr-alert ldr-alert-danger';// Escape message before including in HTML templatediff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.jsindex 6dcea97bf3..eb1644661b 100644--- a/src/local_deep_research/web/static/js/pages/news.js+++ b/src/local_deep_research/web/static/js/pages/news.js@@ -208,7 +208,7 @@ async function initializeNewsPage() {sessionStorage.removeItem('activeTestRunQuery');// Show a message that research is in progress- showAlert('Your test run is in progress. Results will appear below when ready.', 'info');+ showNewsAlert('Your test run is in progress. Results will appear below when ready.', 'info');// Start monitoring this specific research with the querymonitorResearch(activeTestRunResearchId, activeTestRunQuery);@@ -320,7 +320,7 @@ function setupEventListeners() {await performAdvancedNewsSearch(query);} else {SafeLogger.error('No query found in news-subscription-query input');- showAlert('Please enter a query', 'warning');+ showNewsAlert('Please enter a query', 'warning');}});}@@ -595,7 +595,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', modelasync function executeAdvancedNewsSearch(query, strategy = 'source-based', modelConfig = null) {SafeLogger.log('performAdvancedNewsSearch called with:', { query, strategy, modelConfig });- showAlert('Performing advanced news analysis...', 'info');+ showNewsAlert('Performing advanced news analysis...', 'info');try {// Request will use settings from database if not provided@@ -648,7 +648,7 @@ async function executeAdvancedNewsSearch(query, strategy = 'source-based', modelSafeLogger.error('Research API error:', response.status, errorMessage);if (response.status === 401) {- showAlert('Authentication required. Please log in to perform research.', 'error');+ showNewsAlert('Authentication required. Please log in to perform research.', 'error');// Redirect to login after a short delay. Uses the shared helper// (api.js) so the next= param is built the same way everywhere.setTimeout(() => {@@ -657,14 +657,14 @@ async function executeAdvancedNewsSearch(query, strategy = 'source-based', modelreturn;}- showAlert(errorMessage, 'error');+ showNewsAlert(errorMessage, 'error');return;}const data = await response.json();SafeLogger.log('Research API response:', data);if ((data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) && data.research_id) {- showAlert('Analyzing news... Results will appear below when ready.', 'info');+ showNewsAlert('Analyzing news... Results will appear below when ready.', 'info');// Show loading state in news feed FIRSTconst container = document.getElementById('news-feed-content');@@ -699,11 +699,11 @@ async function executeAdvancedNewsSearch(query, strategy = 'source-based', model});} else {SafeLogger.error('Unexpected response format:', data);- showAlert('Failed to start research - unexpected response', 'error');+ showNewsAlert('Failed to start research - unexpected response', 'error');}} catch (error) {SafeLogger.error('Error in advanced search:', error);- showAlert('Error performing search', 'error');+ showNewsAlert('Error performing search', 'error');}}@@ -729,7 +729,7 @@ async function createSubscriptionFromSearch(query, researchId) {if (response.ok) {await loadSubscriptions();- showAlert('Advanced news subscription created!', 'success');+ showNewsAlert('Advanced news subscription created!', 'success');}} catch (error) {SafeLogger.error('Error creating subscription:', error);@@ -740,7 +740,7 @@ async function createSubscriptionFromSearch(query, researchId) {function createSubscriptionFromItem(newsId) {const item = newsItems.find(n => n.id === newsId);if (!item) {- showAlert('News item not found', 'error');+ showNewsAlert('News item not found', 'error');return;}@@ -766,7 +766,7 @@ function displayAdvancedResults(data) {toggleTableView(true);parseAndDisplayTable(content);} else {- showAlert('Results loaded. Check your feed!', 'success');+ showNewsAlert('Results loaded. Check your feed!', 'success');loadNewsFeed();}}@@ -829,7 +829,7 @@ function parseAndDisplayTable(content) {// Simple subscriptionasync function createSimpleSubscription(query) {- showAlert(`Creating subscription for: ${query}`, 'info');+ showNewsAlert(`Creating subscription for: ${query}`, 'info');try {const response = await fetch('/news/api/subscribe', {@@ -848,14 +848,14 @@ async function createSimpleSubscription(query) {if (response.ok) {await loadSubscriptions();await loadNewsFeed();- showAlert('Subscription created!', 'success');+ showNewsAlert('Subscription created!', 'success');document.getElementById('news-query').value = '';} else {- showAlert('Failed to create subscription', 'error');+ showNewsAlert('Failed to create subscription', 'error');}} catch (error) {SafeLogger.error('Error creating subscription:', error);- showAlert('Error creating subscription', 'error');+ showNewsAlert('Error creating subscription', 'error');}}@@ -1482,7 +1482,7 @@ async function vote(newsId, voteType) {);if (!ownsResponse()) return null;SafeLogger.error('Error voting:', error);- showAlert(+ showNewsAlert('Failed to save vote. Restoring the latest vote state.','error');@@ -1565,7 +1565,7 @@ function saveItem(newsId) {// Update UIupdateSaveButton(newsId, true);- showAlert('Item saved for later', 'success');+ showNewsAlert('Item saved for later', 'success');}}@@ -1580,7 +1580,7 @@ function unsaveItem(newsId) {// Update UIupdateSaveButton(newsId, false);- showAlert('Item removed from saved', 'info');+ showNewsAlert('Item removed from saved', 'info');}function toggleSaveItem(newsId) {@@ -1812,10 +1812,10 @@ function filterByTopic(topic) {// Toggle filter if clicking the same topicif (activeTopicFilter === topic) {activeTopicFilter = null;- showAlert('Showing all news', 'info');+ showNewsAlert('Showing all news', 'info');} else {activeTopicFilter = topic;- showAlert(`Filtering by topic: ${topic}`, 'info');+ showNewsAlert(`Filtering by topic: ${topic}`, 'info');}// Update the UI to show active filter@@ -1870,7 +1870,7 @@ function clearTopicFilter() {activeTopicFilter = null;updateActiveTopicUI();renderNewsItems();- showAlert('Filter cleared', 'info');+ showNewsAlert('Filter cleared', 'info');}// Update bulk actions bar@@ -2020,7 +2020,7 @@ function clearAllFilters() {// Re-renderrenderNewsItems();- showAlert('All filters cleared', 'info');+ showNewsAlert('All filters cleared', 'info');}// Render source links@@ -2144,7 +2144,7 @@ async function showSubscriptionHistory(subscriptionId) {} catch (error) {SafeLogger.error('Error loading subscription history:', error);- showAlert('Failed to load subscription history', 'error');+ showNewsAlert('Failed to load subscription history', 'error');}}@@ -2163,16 +2163,16 @@ function useQueryTemplate() {document.getElementById('news-query').value = getNewsTableQuery();hideQueryTemplate();document.getElementById('table-view-toggle').checked = true;- showAlert('Query template loaded. Click Search to execute!', 'info');+ showNewsAlert('Query template loaded. Click Search to execute!', 'info');}async function copyQueryTemplate() {try {await navigator.clipboard.writeText(getNewsTableQuery());- showAlert('Query copied to clipboard!', 'success');+ showNewsAlert('Query copied to clipboard!', 'success');} catch (err) {SafeLogger.error('Failed to copy:', err);- showAlert('Failed to copy query', 'error');+ showNewsAlert('Failed to copy query', 'error');}}@@ -2253,7 +2253,7 @@ async function createSubscription() {const refreshMinutes = document.getElementById('sub-refresh').value;if (!query) {- showAlert('Please enter a query or topic', 'warning');+ showNewsAlert('Please enter a query or topic', 'warning');return;}@@ -2274,18 +2274,18 @@ async function createSubscription() {if (response.ok) {hideSubscriptionModal();await loadSubscriptions();- showAlert('Subscription created successfully!', 'success');+ showNewsAlert('Subscription created successfully!', 'success');} else {- showAlert('Failed to create subscription', 'error');+ showNewsAlert('Failed to create subscription', 'error');}} catch (error) {SafeLogger.error('Error creating subscription:', error);- showAlert('Error creating subscription', 'error');+ showNewsAlert('Error creating subscription', 'error');}}// Utility functions-function showAlert(message, type = 'info') {+function showNewsAlert(message, type = 'info') {const alertContainer = document.getElementById('news-alert');alertContainer.className = `ldr-settings-alert-container alert-${type}`;alertContainer.textContent = message;@@ -2395,7 +2395,7 @@ async function runNewsSemanticSearch(query) {const currentId = ++newsSearchId;if (!newsCollectionId) {- showAlert('Semantic search not available — research history may not be indexed yet.', 'warning');+ showNewsAlert('Semantic search not available — research history may not be indexed yet.', 'warning');return;}@@ -2588,7 +2588,7 @@ function refreshFeed() {} else {loadNewsFeed();}- showAlert('Feed refreshed', 'info');+ showNewsAlert('Feed refreshed', 'info');}// Auto-refresh functions@@ -2611,7 +2611,7 @@ function startAutoRefresh() {}refreshIndicatorInterval = setInterval(updateRefreshIndicator, 1000);- showAlert('Auto-refresh enabled (every 5 minutes)', 'success');+ showNewsAlert('Auto-refresh enabled (every 5 minutes)', 'success');}function stopAutoRefresh() {@@ -2623,7 +2623,7 @@ function stopAutoRefresh() {clearInterval(refreshIndicatorInterval);refreshIndicatorInterval = null;}- showAlert('Auto-refresh disabled', 'info');+ showNewsAlert('Auto-refresh disabled', 'info');}function updateRefreshIndicator() {@@ -2761,7 +2761,7 @@ function endNewsResearchPollWithFeed(poll, message, type = 'error') {stopNewsResearchPoll(poll);clearStoredNewsResearch(poll.researchId);removeNewsResearchCards(poll.researchId);- showAlert(message, type);+ showNewsAlert(message, type);if (!explicitFeedOwnsSurface) loadNewsFeed();}@@ -2775,7 +2775,7 @@ function completeNewsResearchPoll(poll, message) {stopNewsResearchPoll(poll);clearStoredNewsResearch(poll.researchId);removeNewsResearchCards(poll.researchId);- showAlert(message, 'success');+ showNewsAlert(message, 'success');const completedPollId = poll.id;const completedFeedRequestId = newsFeedRequestId;@@ -3028,7 +3028,7 @@ async function checkActiveNewsResearch() {} else if (ResearchStates.isCompleted(status.status)) {// Research completed while user was awayclearStoredNewsResearch(researchId);- showAlert('Your news analysis has completed! Loading results...', 'success');+ showNewsAlert('Your news analysis has completed! Loading results...', 'success');// Reload the feed to show the resultsawait loadNewsFeed();@@ -3291,13 +3291,13 @@ async function clearSearchHistory() {searchHistoryMutationGeneration++;searchHistory = [];displayRecentSearches();- showAlert('Search history cleared', 'success');+ showNewsAlert('Search history cleared', 'success');} else {- showAlert('Failed to clear search history', 'danger');+ showNewsAlert('Failed to clear search history', 'danger');}} catch (e) {SafeLogger.error('Failed to clear search history:', e);- showAlert('Failed to clear search history', 'danger');+ showNewsAlert('Failed to clear search history', 'danger');} finally {releaseWrite();}@@ -3400,7 +3400,7 @@ function markAllAsRead() {});saveReadStatus();renderNewsItems();- showAlert('All items marked as read', 'success');+ showNewsAlert('All items marked as read', 'success');}// Expand all items@@ -3414,7 +3414,7 @@ function expandAll() {if (icon) icon.style.transform = 'rotate(180deg)';}});- showAlert('All items expanded', 'info');+ showNewsAlert('All items expanded', 'info');}// Collapse all items@@ -3425,7 +3425,7 @@ function collapseAll() {const icon = item.querySelector('.ldr-expand-icon');if (icon) icon.style.transform = 'rotate(0)';});- showAlert('All items collapsed', 'info');+ showNewsAlert('All items collapsed', 'info');}// Share and export functions@@ -3461,7 +3461,7 @@ function shareNews(newsId) {text: item.summary || item.findings?.substring(0, 200) + '...',url: shareUrl}).then(() => {- showAlert('Shared successfully', 'success');+ showNewsAlert('Shared successfully', 'success');}).catch(err => {if (err.name !== 'AbortError') {copyToClipboard(shareText);@@ -3514,7 +3514,7 @@ function exportToMarkdown(newsId) {a.download = `${item.headline.replace(/[^a-z0-9]/gi, '_').toLowerCase()}.md`;a.click();- showAlert('Exported to Markdown', 'success');+ showNewsAlert('Exported to Markdown', 'success');}function hideNewsItem(newsId) {@@ -3530,14 +3530,14 @@ function hideNewsItem(newsId) {updateBulkActionsBar();}, 300);}- showAlert('Item hidden', 'info');+ showNewsAlert('Item hidden', 'info');}function copyToClipboard(text) {if (navigator.clipboard) {navigator.clipboard.writeText(text).then(() => {- showAlert('Copied to clipboard', 'success');+ showNewsAlert('Copied to clipboard', 'success');}).catch(_err => {// Fallbackconst textarea = document.createElement('textarea');@@ -3548,7 +3548,7 @@ function copyToClipboard(text) {textarea.select();document.execCommand('copy');document.body.removeChild(textarea);- showAlert('Copied to clipboard', 'success');+ showNewsAlert('Copied to clipboard', 'success');});}}@@ -4071,7 +4071,7 @@ function showNewsSubscriptionModal(query = '', templateName = '') {await performAdvancedNewsSearch(currentQuery);} else {SafeLogger.error('No query found in news-subscription-query input');- showAlert('Please enter a query', 'warning');+ showNewsAlert('Please enter a query', 'warning');}});}@@ -4177,7 +4177,7 @@ async function handleNewsSubscriptionSubmit(e) {if (response.ok) {const data = await response.json();- showAlert('Subscription created successfully!', 'success');+ showNewsAlert('Subscription created successfully!', 'success');// Close modalbootstrap.Modal.getInstance(document.getElementById('newsSubscriptionModal')).hide();@@ -4204,7 +4204,7 @@ async function handleNewsSubscriptionSubmit(e) {);if (hasResearchId) {- showAlert('Subscription research started...', 'info');+ showNewsAlert('Subscription research started...', 'info');// Show loading state in news feed with progress visualizationconst container = document.getElementById('news-feed-content');@@ -4238,15 +4238,15 @@ async function handleNewsSubscriptionSubmit(e) {pollForNewsResearchResults(researchId, query);} else {SafeLogger.error('Immediate subscription run response did not include a research ID');- showAlert('Subscription created, but its research run could not be started.', 'warning');+ showNewsAlert('Subscription created, but its research run could not be started.', 'warning');}} else {SafeLogger.error('Failed to run subscription immediately');- showAlert('Subscription created, but its research run could not be started.', 'warning');+ showNewsAlert('Subscription created, but its research run could not be started.', 'warning');}} catch (error) {SafeLogger.error('Error running subscription:', error);- showAlert('Subscription created, but its research run could not be started.', 'warning');+ showNewsAlert('Subscription created, but its research run could not be started.', 'warning');}}@@ -4254,11 +4254,11 @@ async function handleNewsSubscriptionSubmit(e) {loadSubscriptions();} else {const error = await response.json();- showAlert(error.error || 'Failed to create subscription', 'danger');+ showNewsAlert(error.error || 'Failed to create subscription', 'danger');}} catch (error) {SafeLogger.error('Error creating subscription:', error);- showAlert('Failed to create subscription', 'danger');+ showNewsAlert('Failed to create subscription', 'danger');} finally {if (activeNewsSubscriptionSubmit === submitOwnership) {activeNewsSubscriptionSubmit = null;@@ -4349,7 +4349,7 @@ function applyCustomTemplate() {const templateQuery = document.getElementById('template-query').value;if (!templateQuery.trim()) {- showAlert('Please enter a template query', 'warning');+ showNewsAlert('Please enter a template query', 'warning');return;}@@ -4362,7 +4362,7 @@ function applyCustomTemplate() {modal.hide();// Show message- showAlert(`Custom template "${templateName || 'Untitled'}" loaded. Click "Search News" to run.`, 'success');+ showNewsAlert(`Custom template "${templateName || 'Untitled'}" loaded. Click "Search News" to run.`, 'success');}// Expose functions to global scope for onclick handlersdiff --git a/tests/js/collection-upload-migration-contract.test.js b/tests/js/collection-upload-migration-contract.test.jsindex 94afd6954a..385976e954 100644--- a/tests/js/collection-upload-migration-contract.test.js+++ b/tests/js/collection-upload-migration-contract.test.js@@ -115,7 +115,7 @@ function installFakeXmlHttpRequest() {function compileRealUploadRuntime(files) {const calls = {- showError: vi.fn(),+ showCollectionUploadError: vi.fn(),showCleanProgress: vi.fn(),showBatchedProgress: vi.fn(),updateUploadProgress: vi.fn(),@@ -225,12 +225,12 @@ it('routes a small upload to the collection endpoint with current CSRF and mode'});const handleSingleUpload = vi.fn().mockResolvedValue(undefined);const handleBatchedUpload = vi.fn();- const showError = vi.fn();+ const showCollectionUploadError = vi.fn();window.api = { getCsrfToken: vi.fn(() => 'csrf-collection-upload') };const handleUploadFiles = compileUploadHandler([file], {handleSingleUpload,handleBatchedUpload,- showError,+ showCollectionUploadError,});const form = document.getElementById('upload-files-form');const event = {@@ -250,7 +250,7 @@ it('routes a small upload to the collection endpoint with current CSRF and mode'0,);expect(handleBatchedUpload).not.toHaveBeenCalled();- expect(showError).not.toHaveBeenCalled();+ expect(showCollectionUploadError).not.toHaveBeenCalled();const button = form.querySelector('button[type="submit"]');expect(button.disabled).toBe(false);expect(button.textContent).toContain('Upload Files');@@ -306,7 +306,7 @@ it('executes the real XHR upload contract and completes a successful upload', asexpect(button.disabled).toBe(false);expect(button.textContent).toContain('Upload Files');expect(calls.updateProgressComplete).toHaveBeenCalledWith(response);- expect(calls.showError).not.toHaveBeenCalled();+ expect(calls.showCollectionUploadError).not.toHaveBeenCalled();expect(calls.showUploadResults).not.toHaveBeenCalled();await vi.advanceTimersByTimeAsync(500);@@ -327,7 +327,7 @@ it('recovers the button and reports a non-OK XHR response', async () => {requests[0].respond(422, 'invalid file');await upload;- expect(calls.showError).toHaveBeenCalledWith(+ expect(calls.showCollectionUploadError).toHaveBeenCalledWith('Upload failed: Server returned 422: invalid file',);expect(SafeLogger.error).toHaveBeenCalledOnce();@@ -346,7 +346,7 @@ it('recovers the button and reports an XHR network failure', async () => {requests[0].failNetwork();await upload;- expect(calls.showError).toHaveBeenCalledWith(+ expect(calls.showCollectionUploadError).toHaveBeenCalledWith('Upload failed: NetworkError: Upload failed',);expect(calls.showUploadResults).not.toHaveBeenCalled();diff --git a/tests/js/embedding-test-configuration-runtime.test.js b/tests/js/embedding-test-configuration-runtime.test.jsindex 8f7f80a39c..b139cac9ca 100644--- a/tests/js/embedding-test-configuration-runtime.test.js+++ b/tests/js/embedding-test-configuration-runtime.test.js@@ -13,11 +13,11 @@ const SOURCE_PATH = resolve('../../src/local_deep_research/web/static/js/embedding_settings.js',);-function loadTestConfiguration({ safeFetchWithAuth, showError, showSuccess }) {+function loadTestConfiguration({ safeFetchWithAuth, showEmbeddingSettingsError, showSuccess }) {return compileTemplateHarness({templatePath: SOURCE_PATH,functionNames: ['testConfiguration'],- dependencies: { safeFetchWithAuth, showError, showSuccess },+ dependencies: { safeFetchWithAuth, showEmbeddingSettingsError, showSuccess },returnExpression: 'testConfiguration',});}@@ -49,11 +49,11 @@ it('POSTs only the selected model with CSRF for a server-owned text probe', asynresponse_time_ms: 42,}), { status: 200 }),);- const showError = vi.fn();+ const showEmbeddingSettingsError = vi.fn();const showSuccess = vi.fn();const testConfiguration = loadTestConfiguration({safeFetchWithAuth,- showError,+ showEmbeddingSettingsError,showSuccess,});@@ -81,7 +81,7 @@ it('POSTs only the selected model with CSRF for a server-owned text probe', asyn.toContain('Response time: 42ms');expect(document.getElementById('test-config-btn').disabled).toBe(false);expect(showSuccess).toHaveBeenCalledWith('Embedding test passed!');- expect(showError).not.toHaveBeenCalled();+ expect(showEmbeddingSettingsError).not.toHaveBeenCalled();});it('escapes a failed test envelope and restores the test button', async () => {@@ -114,11 +114,11 @@ it('escapes a failed test envelope and restores the test button', async () => {error: payload,}), { status: 422 }),);- const showError = vi.fn();+ const showEmbeddingSettingsError = vi.fn();const showSuccess = vi.fn();const testConfiguration = loadTestConfiguration({safeFetchWithAuth,- showError,+ showEmbeddingSettingsError,showSuccess,});@@ -129,7 +129,7 @@ it('escapes a failed test envelope and restores the test button', async () => {expect(result.querySelector('img')).toBeNull();expect(result.textContent).toContain(payload);expect(window.__embeddingXss).toBeUndefined();- expect(showError).toHaveBeenCalledWith(+ expect(showEmbeddingSettingsError).toHaveBeenCalledWith('Embedding test failed: ' + payload,);expect(showSuccess).not.toHaveBeenCalled();diff --git a/tests/js/pages/news-advanced-search-runtime.test.js b/tests/js/pages/news-advanced-search-runtime.test.jsindex b50212cb38..1ebf996548 100644--- a/tests/js/pages/news-advanced-search-runtime.test.js+++ b/tests/js/pages/news-advanced-search-runtime.test.js@@ -31,7 +31,7 @@ function deferred() {}function compileAdvancedSearchRuntime() {- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();const pollForNewsResearchResults = vi.fn();const createSubscriptionFromSearch = vi.fn().mockResolvedValue(undefined);const safeLogger = {@@ -48,7 +48,7 @@ function compileAdvancedSearchRuntime() {dependencies: {URLS: { API: { START_RESEARCH: '/api/start_research' } },getCSRFToken: () => window.api.getCsrfToken(),- showAlert,+ showNewsAlert,SafeLogger: safeLogger,escapeHtml: window.escapeHtml,pollForNewsResearchResults,@@ -59,7 +59,7 @@ function compileAdvancedSearchRuntime() {});return {performAdvancedNewsSearch,- showAlert,+ showNewsAlert,pollForNewsResearchResults,createSubscriptionFromSearch,safeLogger,@@ -144,7 +144,7 @@ it('starts advanced research with CSRF and hands an inert owned card to polling'.toHaveBeenCalledWith(researchId, query);expect(runtime.createSubscriptionFromSearch).toHaveBeenCalledWith(query, researchId);- expect(runtime.showAlert).toHaveBeenLastCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenLastCalledWith('Analyzing news... Results will appear below when ready.','info',);@@ -159,7 +159,7 @@ it('renders a FastAPI detail error without starting polling or a subscription',await runtime.performAdvancedNewsSearch('migration news');- expect(runtime.showAlert).toHaveBeenLastCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenLastCalledWith('Search strategy is invalid','error',);@@ -179,7 +179,7 @@ it('uses the shared login redirect after an unauthorized advanced search', asyncawait runtime.performAdvancedNewsSearch('private migration news');- expect(runtime.showAlert).toHaveBeenLastCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenLastCalledWith('Authentication required. Please log in to perform research.','error',);@@ -219,7 +219,7 @@ it('keeps duplicate callers on the active request and releases after an unreadaberrorBody.reject(new Error('response body was not JSON'));await Promise.all([firstSearch, duplicateSearch]);- expect(runtime.showAlert).toHaveBeenLastCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenLastCalledWith('Error starting research: Unprocessable Entity','error',);diff --git a/tests/js/pages/news-feed-ownership-runtime.test.js b/tests/js/pages/news-feed-ownership-runtime.test.jsindex f7a0de4dc4..e81c642e22 100644--- a/tests/js/pages/news-feed-ownership-runtime.test.js+++ b/tests/js/pages/news-feed-ownership-runtime.test.js@@ -31,7 +31,7 @@ function compileFeedRuntime() {const extractTrendingTopics = vi.fn();const updateBulkActionsBar = vi.fn();const loadVotesForNewsItems = vi.fn().mockResolvedValue(undefined);- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();const runtime = compileTemplateHarness({templatePath: NEWS_SOURCE_PATH,@@ -49,7 +49,7 @@ function compileFeedRuntime() {],dependencies: {clearSemanticState,- showAlert,+ showNewsAlert,safeRenderHTML: (container, content) => {container.textContent = content;},@@ -93,7 +93,7 @@ function compileFeedRuntime() {extractTrendingTopics,updateBulkActionsBar,loadVotesForNewsItems,- showAlert,+ showNewsAlert,};}@@ -199,7 +199,7 @@ it('does not let a delayed completion reload supersede a newer focused feed', asexpect(runtime.getNewsItems()).toEqual([{ id: 'focused', headline: 'Migration focused result' },]);- expect(runtime.showAlert).toHaveBeenCalledWith('Completed', 'success');+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Completed', 'success');vi.useRealTimers();});diff --git a/tests/js/pages/news-research-monitor-runtime.test.js b/tests/js/pages/news-research-monitor-runtime.test.jsindex e474108087..58777a2d57 100644--- a/tests/js/pages/news-research-monitor-runtime.test.js+++ b/tests/js/pages/news-research-monitor-runtime.test.js@@ -28,7 +28,7 @@ function deferred() {}function compileMonitorRuntime() {- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();const loadNewsFeed = vi.fn().mockResolvedValue(undefined);const ResearchStates = {isInProgress: status => status === 'in_progress',@@ -59,7 +59,7 @@ function compileMonitorRuntime() {'pollForNewsResearchResults',],dependencies: {- showAlert,+ showNewsAlert,loadNewsFeed,ResearchStates,URLBuilder: window.URLBuilder,@@ -91,7 +91,7 @@ function compileMonitorRuntime() {})`,});- return { ...runtime, showAlert, loadNewsFeed };+ return { ...runtime, showNewsAlert, loadNewsFeed };}beforeEach(() => {@@ -146,7 +146,7 @@ it('allows only one monitor status request in flight and settles once', async ()expect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('.ldr-active-research-card')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Test run completed! Loading results...','success',);@@ -176,7 +176,7 @@ it('cleans monitor state and restores the feed after a status network error', asexpect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('.ldr-active-research-card')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Error checking research status. Please try again.','error',);@@ -212,7 +212,7 @@ it('retires an in-flight monitor on page cleanup without repainting after it set}));await monitoring;- expect(runtime.showAlert).not.toHaveBeenCalled();+ expect(runtime.showNewsAlert).not.toHaveBeenCalled();expect(runtime.loadNewsFeed).not.toHaveBeenCalled();expect(document.querySelector('.ldr-active-research-card')).toBeNull();expect(JSON.parse(localStorage.getItem('active_news_research')))@@ -254,7 +254,7 @@ it.each(['completed', 'in_progress'])(.not.toBeNull();expect(document.querySelector('[data-research-id="restore-a"]')).toBeNull();- expect(runtime.showAlert).not.toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).not.toHaveBeenCalledWith('Your news analysis has completed! Loading results...','success',);@@ -321,7 +321,7 @@ it('times out a monitor whose initial status request never settles', async () =>await vi.advanceTimersByTimeAsync(5 * 60 * 1000);expect(localStorage.getItem('active_news_research')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Research monitoring timed out. Please try again.','warning',);@@ -355,7 +355,7 @@ it('bounds a hung page-restore probe without discarding resumable state', asyncexpect(restoreSignal.aborted).toBe(true);expect(JSON.parse(localStorage.getItem('active_news_research'))).toMatchObject({ researchId: 'hung-restore' });- expect(runtime.showAlert).not.toHaveBeenCalled();+ expect(runtime.showNewsAlert).not.toHaveBeenCalled();expect(runtime.loadNewsFeed).not.toHaveBeenCalled();expect(vi.getTimerCount()).toBe(0);});@@ -387,7 +387,7 @@ it('keeps the restore deadline active while the status body is hung', async () =expect(restoreSignal.aborted).toBe(true);expect(JSON.parse(localStorage.getItem('active_news_research'))).toMatchObject({ researchId: 'hung-restore-body' });- expect(runtime.showAlert).not.toHaveBeenCalled();+ expect(runtime.showNewsAlert).not.toHaveBeenCalled();expect(runtime.loadNewsFeed).not.toHaveBeenCalled();expect(vi.getTimerCount()).toBe(0);});@@ -410,7 +410,7 @@ it('hands an active restore to monitoring without blocking page bootstrap', asynexpect(fetchMock).toHaveBeenCalledTimes(2);expect(JSON.parse(localStorage.getItem('active_news_research'))).toMatchObject({ researchId: 'active-restore-handoff' });- expect(runtime.showAlert).not.toHaveBeenCalled();+ expect(runtime.showNewsAlert).not.toHaveBeenCalled();expect(runtime.loadNewsFeed).not.toHaveBeenCalled();});@@ -434,7 +434,7 @@ it('uses a wall-clock timeout while a subscription status request is hung', asynexpect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('[data-research-id="hung-subscription"]')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Research taking too long. Check the progress page.','warning',);@@ -443,5 +443,5 @@ it('uses a wall-clock timeout while a subscription status request is hung', asynpendingStatus.resolve(response({ status: 'completed', progress: 100 }));await Promise.resolve();await Promise.resolve();- expect(runtime.showAlert).toHaveBeenCalledOnce();+ expect(runtime.showNewsAlert).toHaveBeenCalledOnce();});diff --git a/tests/js/pages/news-search-history-mutations.test.js b/tests/js/pages/news-search-history-mutations.test.jsindex 5a8f0c3b7f..de072c87d0 100644--- a/tests/js/pages/news-search-history-mutations.test.js+++ b/tests/js/pages/news-search-history-mutations.test.js@@ -37,7 +37,7 @@ function compileHarness(overrides = {}) {const factory = new Function( // eslint-disable-line no-new-func'getCSRFToken','displayRecentSearches',- 'showAlert',+ 'showNewsAlert','SafeLogger',`let searchHistory = [{ query: 'existing search' }];@@ -57,7 +57,7 @@ function compileHarness(overrides = {}) {return factory(overrides.getCSRFToken || (() => 'history-csrf'),overrides.displayRecentSearches || vi.fn(),- overrides.showAlert || vi.fn(),+ overrides.showNewsAlert || vi.fn(),overrides.SafeLogger || { log: vi.fn(), error: vi.fn() },);}@@ -95,10 +95,10 @@ it('posts the current query, type, and count with same-origin CSRF', async () =>it('deletes all history and clears the rendered list only after success', async () => {const fetchMock = vi.fn().mockResolvedValue({ ok: true });const displayRecentSearches = vi.fn();- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();vi.stubGlobal('fetch', fetchMock);vi.stubGlobal('confirm', vi.fn().mockReturnValue(true));- const harness = compileHarness({ displayRecentSearches, showAlert });+ const harness = compileHarness({ displayRecentSearches, showNewsAlert });await harness.clearSearchHistory();@@ -109,7 +109,7 @@ it('deletes all history and clears the rendered list only after success', async});expect(harness.getSearchHistory()).toEqual([]);expect(displayRecentSearches).toHaveBeenCalledOnce();- expect(showAlert).toHaveBeenCalledWith(+ expect(showNewsAlert).toHaveBeenCalledWith('Search history cleared','success',);@@ -167,11 +167,11 @@ it('releases the history queue after a failed insert or delete', async () => {it('preserves visible history when deletion is declined or rejected', async () => {const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 503 });const displayRecentSearches = vi.fn();- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();const confirmMock = vi.fn().mockReturnValueOnce(false).mockReturnValue(true);vi.stubGlobal('fetch', fetchMock);vi.stubGlobal('confirm', confirmMock);- const harness = compileHarness({ displayRecentSearches, showAlert });+ const harness = compileHarness({ displayRecentSearches, showNewsAlert });await harness.clearSearchHistory();expect(fetchMock).not.toHaveBeenCalled();@@ -182,7 +182,7 @@ it('preserves visible history when deletion is declined or rejected', async () ={ query: 'existing search' },]);expect(displayRecentSearches).not.toHaveBeenCalled();- expect(showAlert).toHaveBeenCalledWith(+ expect(showNewsAlert).toHaveBeenCalledWith('Failed to clear search history','danger',);diff --git a/tests/js/pages/news-semantic-search-runtime.test.js b/tests/js/pages/news-semantic-search-runtime.test.jsindex f65d574207..87aaa9ba8a 100644--- a/tests/js/pages/news-semantic-search-runtime.test.js+++ b/tests/js/pages/news-semantic-search-runtime.test.js@@ -44,7 +44,7 @@ function compileNewsSearchRuntime({collectionId = 'news-collection-3299',csrfToken = 'csrf-news-search',renderNewsItems = vi.fn(),- showAlert = vi.fn(),+ showNewsAlert = vi.fn(),} = {}) {const newsCardConfig = {getId: result => result.research_id || '',@@ -63,7 +63,7 @@ function compileNewsSearchRuntime({initialCollectionId: collectionId,csrfToken,renderNewsItems,- showAlert,+ showNewsAlert,NEWS_CARD_CONFIG: newsCardConfig,URLBuilder: window.URLBuilder,URLS: window.URLS,diff --git a/tests/js/pages/news-subscription-submit-runtime.test.js b/tests/js/pages/news-subscription-submit-runtime.test.jsindex 1f9ef14e53..e0b586e4df 100644--- a/tests/js/pages/news-subscription-submit-runtime.test.js+++ b/tests/js/pages/news-subscription-submit-runtime.test.js@@ -43,7 +43,7 @@ function escapeHtml(value) {}function compileSubscriptionRuntime({- showAlert = vi.fn(),+ showNewsAlert = vi.fn(),loadSubscriptions = vi.fn().mockResolvedValue(undefined),loadNewsFeed = vi.fn().mockResolvedValue(undefined),} = {}) {@@ -77,7 +77,7 @@ function compileSubscriptionRuntime({'handleNewsSubscriptionSubmit',],dependencies: {- showAlert,+ showNewsAlert,loadSubscriptions,loadNewsFeed,escapeHtml,@@ -103,7 +103,7 @@ function compileSubscriptionRuntime({return {...runtime,- showAlert,+ showNewsAlert,loadSubscriptions,loadNewsFeed,hideModal,@@ -240,7 +240,7 @@ it('creates, runs, polls, and completes a subscription using the returned resear);expect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('.ldr-active-research-card')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('News analysis completed! Loading results...','success',);@@ -323,7 +323,7 @@ it.each([await vi.advanceTimersByTimeAsync(15000);expect(fetchMock).toHaveBeenCalledTimes(2);- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Subscription created, but its research run could not be started.','warning',);@@ -360,7 +360,7 @@ it('stops polling and restores the feed when research reaches a failed state', a'/api/research/research-failed/status',);expect(localStorage.getItem('active_news_research')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Research failed: provider unavailable','error',);@@ -390,7 +390,7 @@ it('reports an immediate-run failure without starting a status poll', async () =expect(fetchMock).toHaveBeenCalledTimes(2);expect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('.ldr-active-research-card')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Subscription created, but its research run could not be started.','warning',);@@ -429,7 +429,7 @@ it('retires a superseded status request before it can contradict the newer run',.not.toBeNull();await vi.advanceTimersByTimeAsync(5000);- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('News analysis completed! Loading results...','success',);@@ -445,8 +445,8 @@ it('retires a superseded status request before it can contradict the newer run',await Promise.resolve();await vi.advanceTimersByTimeAsync(1000);- expect(runtime.showAlert).toHaveBeenCalledTimes(1);- expect(runtime.showAlert).not.toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledTimes(1);+ expect(runtime.showNewsAlert).not.toHaveBeenCalledWith('Research failed: stale provider failure','error',);@@ -478,7 +478,7 @@ it('cleans persisted and visible polling state after a status HTTP failure', asyexpect(localStorage.getItem('active_news_research')).toBeNull();expect(document.querySelector('.ldr-active-research-card')).toBeNull();- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Failed to check research status. Please try again.','error',);diff --git a/tests/js/pages/news-votes-runtime.test.js b/tests/js/pages/news-votes-runtime.test.jsindex 76e16c8ab2..9adfaa7344 100644--- a/tests/js/pages/news-votes-runtime.test.js+++ b/tests/js/pages/news-votes-runtime.test.js@@ -29,11 +29,11 @@ function deferred() {}function compileVotesRuntime(items, csrfToken = 'csrf-news-votes') {- const showAlert = vi.fn();+ const showNewsAlert = vi.fn();const runtime = compileTemplateHarness({templatePath: NEWS_SOURCE_PATH,functionNames: ['loadVotesForNewsItems', 'vote'],- dependencies: { items, csrfToken, showAlert },+ dependencies: { items, csrfToken, showNewsAlert },preamble: `let newsItems = items;let voteLoadRequestId = 0;@@ -47,7 +47,7 @@ function compileVotesRuntime(items, csrfToken = 'csrf-news-votes') {setNewsItems: value => { newsItems = value; },})`,});- return { ...runtime, showAlert };+ return { ...runtime, showNewsAlert };}function addNewsCard(id) {@@ -274,7 +274,7 @@ it.each([body: JSON.stringify({ card_ids: ['reconcile-news'] }),},]);- expect(runtime.showAlert).toHaveBeenCalledWith(+ expect(runtime.showNewsAlert).toHaveBeenCalledWith('Failed to save vote. Restoring the latest vote state.','error',);diff --git a/tests/web/test_collection_details_script_contracts.py b/tests/web/test_collection_details_script_contracts.pyindex 6f40b318a5..7e30c2d2ce 100644--- a/tests/web/test_collection_details_script_contracts.py+++ b/tests/web/test_collection_details_script_contracts.py@@ -16,13 +16,14 @@ _COLLECTION_DETAILS_JS = (# ^-anchored, like test_notes_js_global_shadowing.py's _DECL_RE: only a# top-level (column-0) declaration in a classic (non-module) script creates-# or shadows a global, so only those forms matter here. Narrowed to one-# name (formatBytes) and kept as its own check here -- rather than folded-# into that file's full base.html-shared-script sweep -- because that-# sweep is keyed on every top-level name in this file, and today it would-# also have to reconcile this file's unrelated, pre-existing top-level-# `showError` against services/ui.js's own `showError` (a real but-# separate, out-of-scope collision).+# or shadows a global, so only those forms matter here. Kept as its own+# check -- rather than folded into that file's full base.html-shared-script+# sweep -- because the sweep's failure message enumerates every colliding+# name, while this one names the specific declaration (and its SyntaxError+# consequence) that delete_manager.js makes fatal on this page. The+# `showError` collision that used to keep this file out of that sweep is+# fixed (renamed to `showCollectionError`, #6585), so collection_details.js+# is now swept there too._LOCAL_FORMAT_BYTES_DECL = re.compile(r"^(?:async\s+)?function\s+formatBytes\b"r"|^(?:let|var|const)\s+formatBytes\b"diff --git a/tests/web/test_notes_js_global_shadowing.py b/tests/web/test_notes_js_global_shadowing.pyindex 5bd8197a95..264a50a9c8 100644--- a/tests/web/test_notes_js_global_shadowing.py+++ b/tests/web/test_notes_js_global_shadowing.py@@ -16,9 +16,9 @@ so every error toast no-opped.The collision was removed by renaming the page-local functions. This testlocks the invariant so it cannot silently regress: no top-level name in a-notes page script may collide with a top-level name in a script base.html-loads. If you add a page-level helper, give it a name unique from the shared-service scripts (or wrap the page script in an IIFE/module).+page script listed below may collide with a top-level name in a script+base.html loads. If you add a page-level helper, give it a name unique from+the shared service scripts (or wrap the page script in an IIFE/module)."""import re@@ -44,23 +44,55 @@ _DECL_RE = re.compile(re.MULTILINE,)-# The notes page scripts that had the collisions, plus other classic-# (non-module) page scripts that declare a top-level name of their own and-# must not collide with one of the base.html-shared scripts' top-level-# names: delete_manager.js declares a top-level `const formatBytes`-# wrapping the shared window.formatBytes (see the comment there) -- a-# same-named top-level declaration later added to a base.html-shared-# script would crash with SyntaxError, not silently shadow it.-#-# collection_details.js is included so its page-local helpers remain distinct-# from the shared service layer loaded by base.html.-_NOTES_PAGE_SCRIPTS = [+# Classic (non-module) page scripts that declare top-level names of their own+# and must not collide with one of the base.html-shared scripts' top-level+# names. The notes page scripts that had the original collisions, plus+# delete_manager.js (a top-level `const formatBytes` wrapping the shared+# window.formatBytes -- a same-named top-level declaration later added to a+# base.html-shared script would crash with SyntaxError, not silently shadow+# it). Collection, embedding-settings, and news scripts are emitted from+# their templates' content blocks before base.html's shared deferred scripts.+# Their page-local alert helpers must have names distinct from ui.js's+# showError/showAlert declarations (#6585, #7018).+_PAGE_SCRIPTS = ["js/pages/note-detail.js","js/pages/notes.js",+ "js/pages/news.js","js/deletion/delete_manager.js","js/collection_details.js",+ "js/collections_manager.js",+ "js/collection_create.js",+ "js/collection_upload.js",+ "js/embedding_settings.js",]+_CONTENT_BLOCK_PAGES = {+ "collection_details.html": "js/collection_details.js",+ "collections.html": "js/collections_manager.js",+ "collection_create.html": "js/collection_create.js",+ "collection_upload.html": "js/collection_upload.js",+ "embedding_settings.html": "js/embedding_settings.js",+ "news.html": "js/pages/news.js",+ "news_cleaned.html": "js/pages/news.js",+}+++def test_affected_page_scripts_run_before_shared_ui():+ """Keep the ordering assumption behind this collision guard explicit."""+ base = _BASE_HTML.read_text(encoding="utf-8")+ assert base.index("{% block content %}") < base.index(+ "/static/js/services/ui.js"+ )+ for template, script in _CONTENT_BLOCK_PAGES.items():+ html = (_WEB / "templates" / "pages" / template).read_text(+ encoding="utf-8"+ )+ content = html.split("{% block content %}", 1)[1].split(+ "{% endblock %}", 1+ )[0]+ assert f'<script defer src="/static/{script}"></script>' in content+ assert script in _PAGE_SCRIPTS+def _top_level_names(js_path: Path) -> set[str]:text = js_path.read_text(encoding="utf-8")@@ -91,14 +123,14 @@ def test_base_html_shared_scripts_are_discoverable():assert "formatting.js" in shared-def test_notes_page_scripts_do_not_shadow_shared_globals():+def test_page_scripts_do_not_shadow_shared_globals():shared_names: dict[str, str] = {}for sp in _base_html_shared_scripts():for name in _top_level_names(sp):shared_names.setdefault(name, sp.name)collisions = []- for rel in _NOTES_PAGE_SCRIPTS:+ for rel in _PAGE_SCRIPTS:page = _STATIC / relassert page.exists(), f"missing page script: {rel}"for name in _top_level_names(page):