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.

fix(frontend): repair migration regressions with Vitest coverage (#6037)

LearningCircuit8646b7100bb9
diff --git a/.github/workflows/fastapi-migration-quality.yml b/.github/workflows/fastapi-migration-quality.yml
index e08d23665a..bad597cb3b 100644
--- a/.github/workflows/fastapi-migration-quality.yml
+++ b/.github/workflows/fastapi-migration-quality.yml
@@ -12,13 +12,16 @@ on:
- .pre-commit-hooks/check-no-flask.py
- pyproject.toml
- pdm.lock
+ - package.json
+ - package-lock.json
+ - vite.config.js
- .pre-commit-hooks/check-silent-exceptions.py
- src/local_deep_research/web/fastapi_app.py
- src/local_deep_research/web/app.py
- src/local_deep_research/web/server_config.py
- src/local_deep_research/web/template_config.py
- src/local_deep_research/web/templates/**
- - src/local_deep_research/web/static/js/config/urls.js
+ - src/local_deep_research/web/static/js/**
- src/local_deep_research/web/dependencies/**
- src/local_deep_research/web/auth/**
- src/local_deep_research/web/exceptions.py
@@ -30,6 +33,7 @@ on:
- src/local_deep_research/web/services/research_service.py
- src/local_deep_research/web/services/settings_service.py
- src/local_deep_research/web/services/socketio_asgi.py
+ - tests/js/**
- src/local_deep_research/utilities/request_context.py
- src/local_deep_research/utilities/resource_utils.py
- src/local_deep_research/database/backup/backup_service.py
@@ -120,6 +124,33 @@ concurrency:
cancel-in-progress: true
jobs:
+ vitest:
+ name: Vitest JS Unit Tests
+ runs-on: ubuntu-latest
+ timeout-minutes: 10
+
+ steps:
+ - name: Harden the runner
+ uses: step-security/harden-runner@bf7454d06d71f1098171f2acdf0cd4708d7b5920 # v2.20.0
+ with:
+ egress-policy: audit
+
+ - name: Checkout repository
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7.0.0
+ with:
+ persist-credentials: false
+
+ - name: Set up Node.js
+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
+ with:
+ node-version: '24'
+
+ - name: Install frontend dependencies
+ run: npm ci
+
+ - name: Run full Vitest suite (shuffle seed 3299)
+ run: npm test -- --sequence.shuffle --sequence.seed=3299
+
fastapi-migration-quality:
runs-on: ubuntu-latest
timeout-minutes: 20
diff --git a/changelog.d/6037.bugfix.md b/changelog.d/6037.bugfix.md
new file mode 100644
index 0000000000..dce898a69b
--- /dev/null
+++ b/changelog.d/6037.bugfix.md
@@ -0,0 +1,9 @@
+Fix frontend regressions after the FastAPI migration, including stale asynchronous updates, repeated submissions, ordered settings saves, streamed chat answers, and download completion. Add Vitest coverage for browser entry points and run the full shuffled frontend suite in migration CI.
+
+Keep the Background sweep toggle at its last confirmed state when consecutive queued saves fail, while preserving conservative handling of its legacy setting.
+
+Keep Reset All ordered after pending settings saves, avoid duplicate page/socket polling and recursive logging when the log panel is unavailable, preserve newer note ordering during error recovery, serialize news history insertion and clearing, and retain completed research results when cancellation arrives too late.
+
+Preserve the confirmed auto-index setting after failed queued saves, save ordinary and JSON control reversals while earlier writes are pending, and keep benchmark progress updating when status requests exceed the polling interval.
+
+Keep benchmark recent results and search-quality monitoring updating during slow polling, and preserve pending local-only preferences when leaving the Private-only scope.
diff --git a/package-lock.json b/package-lock.json
index d6c0cdec5c..4f76ed3011 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -26,6 +26,7 @@
},
"devDependencies": {
"@vitest/coverage-v8": "^4.1.7",
+ "acorn": "^8.18.0",
"eslint": "^10.9.1",
"eslint-plugin-chai-friendly": "^1.2.1",
"eslint-plugin-no-unsanitized": "^4.1.5",
diff --git a/package.json b/package.json
index a1196c3dcd..be14e5dbc3 100644
--- a/package.json
+++ b/package.json
@@ -38,6 +38,7 @@
},
"devDependencies": {
"@vitest/coverage-v8": "^4.1.7",
+ "acorn": "^8.18.0",
"eslint": "^10.9.1",
"eslint-plugin-chai-friendly": "^1.2.1",
"eslint-plugin-no-unsanitized": "^4.1.5",
diff --git a/src/local_deep_research/web/fastapi_app.py b/src/local_deep_research/web/fastapi_app.py
index b592a746d2..64870aeadc 100644
--- a/src/local_deep_research/web/fastapi_app.py
+++ b/src/local_deep_research/web/fastapi_app.py
@@ -1111,7 +1111,7 @@ def _register_exception_handlers(app: FastAPI) -> None:
# URL) as `next`, so a deep link survived the login bounce; the
# port truncated it to the path, silently dropping the query.
# That is not cosmetic: /chat/?q=... auto-submits the query as a
- # research run (static/js/components/chat.js:282-288), so a
+ # research run (static/js/components/chat.js routed-query bootstrap), so a
# signed-out user following a shared link landed on an empty
# chat box with their question gone. The consumer side already
# handles this -- URLValidator.get_safe_redirect_path()
diff --git a/src/local_deep_research/web/routers/research.py b/src/local_deep_research/web/routers/research.py
index 7879446485..d05591c34e 100644
--- a/src/local_deep_research/web/routers/research.py
+++ b/src/local_deep_research/web/routers/research.py
@@ -1430,6 +1430,7 @@ def terminate_research(
return {
"status": "success",
"message": f"Research already {status}",
+ "research_status": status,
}
# Check if it's in the active_research dict
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index adc4628ce3..21fd7febe9 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -8,6 +8,16 @@ let documentsData = [];
let notesData = [];
let currentFilter = 'all';
let indexingPollInterval = null;
+let activeIndexingPoll = null;
+let progressHideTimer = null;
+let progressUiGeneration = 0;
+let collectionDetailsLoadId = 0;
+const collectionBooleanWriteStates = new WeakMap();
+const confirmedCollectionBooleanState = new Map();
+const collectionBooleanToggleIds = {
+ is_public: 'collection-is-public',
+ agent_enabled: 'collection-agent-enabled'
+};
// safeFetch/safeFetchWithAuth (with URLValidator) are now provided by utils/safe-fetch.js loaded in base.html
@@ -38,74 +48,162 @@ document.addEventListener('DOMContentLoaded', function() {
});
/**
- * Persist the collection's public/private (egress) flag.
+ * Serialize writes for one checkbox while keeping different checkboxes
+ * independent. A later intent owns the visible state and notification, but
+ * every intent still reaches the server in the order the user made it.
*/
-async function updateCollectionIsPublic(isPublic) {
- const toggle = document.getElementById('collection-is-public');
- try {
- const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ is_public: isPublic })
- });
- const data = await response.json();
- if (data.success) {
- if (collectionData) collectionData.is_public = !!data.collection.is_public;
- showSuccess(isPublic ? 'Collection marked public.' : 'Collection marked private (local-only).');
- } else {
- if (toggle) toggle.checked = !isPublic; // revert on failure
- showError('Failed to update collection: ' + (data.error || 'unknown error'));
- }
- } catch (e) {
- if (toggle) toggle.checked = !isPublic; // revert on failure
- showError('Failed to update collection privacy setting.');
+function queueCollectionBooleanUpdate({
+ toggle,
+ field,
+ requestedValue,
+ successMessage,
+ networkErrorMessage
+}) {
+ if (!toggle) return Promise.resolve();
+
+ let state = collectionBooleanWriteStates.get(toggle);
+ if (!state) {
+ const loadedValue = collectionData && typeof collectionData[field] === 'boolean'
+ ? collectionData[field]
+ : !requestedValue;
+ state = {
+ queue: Promise.resolve(),
+ latestIntentId: 0,
+ confirmedValue: !!loadedValue,
+ latestIntentValue: !!requestedValue,
+ latestIntentPending: false
+ };
+ collectionBooleanWriteStates.set(toggle, state);
}
+
+ const intentId = ++state.latestIntentId;
+ state.latestIntentValue = !!requestedValue;
+ state.latestIntentPending = true;
+ const run = async () => {
+ try {
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
+ const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ [field]: requestedValue })
+ });
+ const data = await response.json();
+ if (data.success) {
+ const returnedValue = data.collection && typeof data.collection[field] === 'boolean'
+ ? data.collection[field]
+ : requestedValue;
+ state.confirmedValue = !!returnedValue;
+ const previousConfirmedState = confirmedCollectionBooleanState.get(field);
+ confirmedCollectionBooleanState.set(field, {
+ generation: (previousConfirmedState?.generation || 0) + 1,
+ value: state.confirmedValue
+ });
+ if (collectionData) collectionData[field] = state.confirmedValue;
+
+ if (intentId !== state.latestIntentId) return;
+ state.latestIntentPending = false;
+ toggle.checked = state.confirmedValue;
+ showSuccess(successMessage);
+ } else if (intentId === state.latestIntentId) {
+ state.latestIntentPending = false;
+ toggle.checked = state.confirmedValue;
+ showError('Failed to update collection: ' + (data.error || 'unknown error'));
+ }
+ } catch {
+ if (intentId !== state.latestIntentId) return;
+ state.latestIntentPending = false;
+ toggle.checked = state.confirmedValue;
+ showError(networkErrorMessage);
+ }
+ };
+
+ const queued = state.queue.then(run, run);
+ state.queue = queued;
+ return queued;
+}
+
+/**
+ * Persist the collection's public/private (egress) flag.
+ */
+function updateCollectionIsPublic(isPublic) {
+ return queueCollectionBooleanUpdate({
+ toggle: document.getElementById('collection-is-public'),
+ field: 'is_public',
+ requestedValue: isPublic,
+ successMessage: isPublic
+ ? 'Collection marked public.'
+ : 'Collection marked private (local-only).',
+ networkErrorMessage: 'Failed to update collection privacy setting.'
+ });
}
/**
* Persist the collection's research-agent availability flag (usability, not
* egress): whether the LangGraph agent offers this collection as a tool.
*/
-async function updateCollectionAgentEnabled(agentEnabled) {
- const toggle = document.getElementById('collection-agent-enabled');
- try {
- const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DETAILS, COLLECTION_ID), {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ agent_enabled: agentEnabled })
- });
- const data = await response.json();
- if (data.success) {
- if (collectionData) collectionData.agent_enabled = !!data.collection.agent_enabled;
- showSuccess(agentEnabled ? 'Collection available to the research agent.' : 'Collection hidden from the research agent.');
- } else {
- if (toggle) toggle.checked = !agentEnabled; // revert on failure
- showError('Failed to update collection: ' + (data.error || 'unknown error'));
- }
- } catch (e) {
- if (toggle) toggle.checked = !agentEnabled; // revert on failure
- showError('Failed to update research-agent setting.');
- }
+function updateCollectionAgentEnabled(agentEnabled) {
+ return queueCollectionBooleanUpdate({
+ toggle: document.getElementById('collection-agent-enabled'),
+ field: 'agent_enabled',
+ requestedValue: agentEnabled,
+ successMessage: agentEnabled
+ ? 'Collection available to the research agent.'
+ : 'Collection hidden from the research agent.',
+ networkErrorMessage: 'Failed to update research-agent setting.'
+ });
}
/**
* Load collection details and documents
*/
async function loadCollectionDetails() {
+ const currentLoadId = ++collectionDetailsLoadId;
+ const booleanGenerationsAtRequest = new Map(
+ ['is_public', 'agent_enabled'].map(field => [
+ field,
+ confirmedCollectionBooleanState.get(field)?.generation || 0
+ ])
+ );
+
try {
const response = await safeFetchWithAuth(URLBuilder.build(URLS.LIBRARY_API.COLLECTION_DOCUMENTS, COLLECTION_ID));
+ if (currentLoadId !== collectionDetailsLoadId) return;
const data = await response.json();
+ if (currentLoadId !== collectionDetailsLoadId) return;
if (data.success) {
collectionData = data.collection;
+ // A collection bootstrap/reload can begin before a checkbox PUT
+ // commits and finish after it. Preserve only fields whose newer
+ // server-confirmed mutation superseded this GET; the rest of the
+ // payload (documents, notes, metadata, and untouched flags) still
+ // hydrates normally.
+ for (const field of ['is_public', 'agent_enabled']) {
+ const confirmedState = confirmedCollectionBooleanState.get(field);
+ const loadedValue = field === 'agent_enabled'
+ ? collectionData[field] !== false
+ : !!collectionData[field];
+ let authoritativeValue = loadedValue;
+ if (
+ confirmedState &&
+ confirmedState.generation !== booleanGenerationsAtRequest.get(field)
+ ) {
+ authoritativeValue = confirmedState.value;
+ }
+ collectionData[field] = authoritativeValue;
+
+ const toggle = document.getElementById(collectionBooleanToggleIds[field]);
+ const writeState = toggle && collectionBooleanWriteStates.get(toggle);
+ if (writeState) {
+ // Even while the latest intent owns the visible checkbox,
+ // retain the newest authoritative value as its rollback
+ // target if that pending write fails.
+ writeState.confirmedValue = authoritativeValue;
+ }
+ }
documentsData = data.documents || [];
notesData = data.notes || [];
@@ -116,13 +214,19 @@ async function loadCollectionDetails() {
// Reflect the public/private (egress) flag
const publicToggle = document.getElementById('collection-is-public');
if (publicToggle) {
- publicToggle.checked = !!collectionData.is_public;
+ const writeState = collectionBooleanWriteStates.get(publicToggle);
+ publicToggle.checked = writeState?.latestIntentPending
+ ? writeState.latestIntentValue
+ : !!collectionData.is_public;
}
// Reflect the research-agent availability flag (default available).
const agentToggle = document.getElementById('collection-agent-enabled');
if (agentToggle) {
- agentToggle.checked = collectionData.agent_enabled !== false;
+ const writeState = collectionBooleanWriteStates.get(agentToggle);
+ agentToggle.checked = writeState?.latestIntentPending
+ ? writeState.latestIntentValue
+ : collectionData.agent_enabled !== false;
}
// System collections (Notes, Library, Research History) can't be
@@ -151,6 +255,7 @@ async function loadCollectionDetails() {
showError('Failed to load collection details: ' + data.error);
}
} catch (error) {
+ if (currentLoadId !== collectionDetailsLoadId) return;
SafeLogger.error('Error loading collection details:', error);
showError('Failed to load collection details');
}
@@ -469,9 +574,15 @@ async function indexCollection(forceReindex) {
* Check if there's an active indexing task and resume UI
*/
async function checkAndResumeIndexing() {
+ const resumeUiGeneration = progressUiGeneration;
try {
const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);
+ if (resumeUiGeneration !== progressUiGeneration) return;
+ if (!response.ok) {
+ throw new Error('Indexing status request failed (HTTP ' + response.status + ')');
+ }
const data = await response.json();
+ if (resumeUiGeneration !== progressUiGeneration) return;
if (data.status === 'processing') {
SafeLogger.log('Active indexing task found, resuming UI');
@@ -493,6 +604,12 @@ async function checkAndResumeIndexing() {
* Show the progress UI
*/
function showProgressUI() {
+ progressUiGeneration += 1;
+ if (progressHideTimer !== null) {
+ clearTimeout(progressHideTimer);
+ progressHideTimer = null;
+ }
+
const progressSection = document.getElementById('indexing-progress');
const cancelBtn = document.getElementById('cancel-indexing-btn');
const indexBtn = document.getElementById('index-collection-btn');
@@ -518,10 +635,23 @@ function hideProgressUI({ keepVisible = false } = {}) {
indexBtn.disabled = false;
reindexBtn.disabled = false;
+ if (progressHideTimer !== null) {
+ clearTimeout(progressHideTimer);
+ progressHideTimer = null;
+ }
+
if (!keepVisible) {
- setTimeout(() => {
+ const hideGeneration = progressUiGeneration;
+ const hideTimer = setTimeout(() => {
+ if (
+ progressHideTimer !== hideTimer ||
+ progressUiGeneration !== hideGeneration
+ ) return;
+
+ progressHideTimer = null;
progressSection.style.display = 'none';
}, 5000);
+ progressHideTimer = hideTimer;
}
}
@@ -529,24 +659,56 @@ function hideProgressUI({ keepVisible = false } = {}) {
* Start polling for indexing status
*/
function startPolling() {
- // Clear any existing interval
- if (indexingPollInterval) {
+ // Retire both the timer and any response still awaiting I/O from the
+ // previous poll owner. A restarted poll must not be repainted by that
+ // older response after the new owner reaches a terminal state.
+ if (activeIndexingPoll) {
+ if (activeIndexingPoll.interval !== null) {
+ clearInterval(activeIndexingPoll.interval);
+ }
+ activeIndexingPoll.interval = null;
+ activeIndexingPoll = null;
+ indexingPollInterval = null;
+ } else if (indexingPollInterval) {
clearInterval(indexingPollInterval);
+ indexingPollInterval = null;
}
+ const poll = {
+ interval: null,
+ requestInFlight: false
+ };
+ activeIndexingPoll = poll;
+
// Poll every 2 seconds
- indexingPollInterval = setInterval(async () => {
+ poll.interval = setInterval(async () => {
+ if (activeIndexingPoll !== poll || poll.requestInFlight) return;
+ poll.requestInFlight = true;
+
try {
const response = await safeFetchWithAuth(`/library/api/collections/${COLLECTION_ID}/index/status`);
+ if (activeIndexingPoll !== poll) return;
+ if (!response.ok) {
+ throw new Error('Indexing status request failed (HTTP ' + response.status + ')');
+ }
const data = await response.json();
+ if (activeIndexingPoll !== poll) return;
+
+ const isTerminal = (
+ ResearchStates.isTerminal(data.status) ||
+ data.status === 'idle'
+ );
+ if (isTerminal) {
+ clearInterval(poll.interval);
+ poll.interval = null;
+ activeIndexingPoll = null;
+ indexingPollInterval = null;
+ }
updateProgressFromStatus(data);
// Stop polling if indexing is done
- if (ResearchStates.isTerminal(data.status) || data.status === 'idle') {
- clearInterval(indexingPollInterval);
- indexingPollInterval = null;
-
+ if (isTerminal) {
if (ResearchStates.isCompleted(data.status)) {
addLogEntry(data.progress_message || 'Indexing completed!', 'success');
hideProgressUI();
@@ -570,9 +732,13 @@ function startPolling() {
loadCollectionDetails();
}
} catch (error) {
+ if (activeIndexingPoll !== poll) return;
SafeLogger.error('Error polling status:', error);
+ } finally {
+ poll.requestInFlight = false;
}
}, 2000);
+ indexingPollInterval = poll.interval;
}
function renderIndexingFailure(data) {
@@ -850,6 +1016,11 @@ function initCollectionSearch() {
clearTimeout(searchDebounceTimer);
const query = searchInput.value.trim();
if (!query) {
+ // Clearing the field retires any request that is still
+ // awaiting the server. Otherwise that old response can
+ // repopulate results after the user deliberately
+ // cleared them.
+ collectionSearchId += 1;
const container = document.getElementById('collection-search-results');
if (container) container.innerHTML = '';
return;
@@ -917,16 +1088,29 @@ async function searchCollection(query) {
container.innerHTML = '<div class="ldr-empty-state"><i class="fas fa-exclamation-triangle fa-2x"></i><p>' + escapeHtml(data.error || 'Search failed') + '</p></div>';
}
} catch (error) {
+ // A rejected older request must not replace a newer search result with
+ // its generic error state.
+ if (currentSearchId !== collectionSearchId) return;
SafeLogger.error('Collection search error:', error);
// bearer:disable javascript_lang_dangerous_insert_html
container.innerHTML = '<div class="ldr-empty-state"><i class="fas fa-exclamation-triangle fa-2x"></i><p>Search failed. Please try again.</p></div>';
}
}
-// Exposed on window so vitest can exercise pure UI helpers.
+// Exposed on window so vitest can exercise the checked-in runtime helpers.
window.getProviderLabel = getProviderLabel;
window.renderIndexingFailure = renderIndexingFailure;
+window.checkAndResumeIndexing = checkAndResumeIndexing;
+window.showProgressUI = showProgressUI;
window.hideProgressUI = hideProgressUI;
window.startPolling = startPolling;
window.displayCollectionEmbeddingSettings = displayCollectionEmbeddingSettings;
window.setCollectionDataForTesting = (data) => { collectionData = data; };
+window.updateCollectionIsPublic = updateCollectionIsPublic;
+window.updateCollectionAgentEnabled = updateCollectionAgentEnabled;
+// These handlers are referenced by inline controls rendered by the collection
+// template/document cards. Assign them explicitly so the contract survives if
+// this script is evaluated as a module (as it is in the direct-runtime tests).
+window.filterDocuments = filterDocuments;
+window.removeDocumentFromCollection = removeDocumentFromCollection;
+window.deleteDocumentCompletely = deleteDocumentCompletely;
diff --git a/src/local_deep_research/web/static/js/collection_upload.js b/src/local_deep_research/web/static/js/collection_upload.js
index 596ee0b4b1..d93d295fb6 100644
--- a/src/local_deep_research/web/static/js/collection_upload.js
+++ b/src/local_deep_research/web/static/js/collection_upload.js
@@ -12,6 +12,8 @@
// Store selected files globally to avoid losing them
let selectedFiles = [];
+let fileSelectionGeneration = 0;
+let uploadGeneration = 0;
// Store supported formats (fetched from backend)
let supportedFormats = {
@@ -96,10 +98,17 @@ document.addEventListener('DOMContentLoaded', function() {
const fileInput = document.getElementById('files-input');
if (dropZone && fileInput) {
+ const browseButton = dropZone.querySelector('button[type="button"]');
+ if (browseButton) {
+ browseButton.addEventListener('click', () => fileInput.click());
+ }
+
dropZone.addEventListener('click', (e) => {
- if (e.target.tagName !== 'BUTTON') {
- fileInput.click();
- }
+ // The button owns its activation above. Ignore both its children
+ // and the hidden input's synthetic click as they bubble through
+ // the drop zone, otherwise one gesture can open the picker twice.
+ if (e.target.closest?.('button, input')) return;
+ fileInput.click();
});
dropZone.addEventListener('dragover', handleDragOver);
@@ -234,6 +243,7 @@ function handleFiles(files) {
// Store files globally
selectedFiles = Array.from(files);
+ fileSelectionGeneration++;
SafeLogger.log('📦 Stored files globally:', selectedFiles.length, 'files');
if (files.length === 0) {
@@ -299,9 +309,12 @@ async function handleUploadFiles(e) {
const submitBtn = e.target.querySelector('button[type="submit"]');
const csrfToken = window.api ? window.api.getCsrfToken() : '';
const uploadUrl = URLBuilder.build(URLS.LIBRARY_API.COLLECTION_UPLOAD, COLLECTION_ID);
+ const filesToUpload = selectedFiles.slice();
+ const selectionGeneration = fileSelectionGeneration;
+ const requestGeneration = ++uploadGeneration;
// Decide: batch upload for large sets, single upload for small sets
- const useBatchedUpload = selectedFiles.length > BATCH_SIZE;
+ const useBatchedUpload = filesToUpload.length > BATCH_SIZE;
try {
submitBtn.disabled = true;
@@ -309,10 +322,24 @@ async function handleUploadFiles(e) {
if (useBatchedUpload) {
// Batched upload for large file sets
- await handleBatchedUpload(selectedFiles, pdfStorageMode, csrfToken, uploadUrl);
+ await handleBatchedUpload(
+ filesToUpload,
+ pdfStorageMode,
+ csrfToken,
+ uploadUrl,
+ requestGeneration,
+ selectionGeneration
+ );
} else {
// Single upload for small file sets
- await handleSingleUpload(selectedFiles, pdfStorageMode, csrfToken, uploadUrl);
+ await handleSingleUpload(
+ filesToUpload,
+ pdfStorageMode,
+ csrfToken,
+ uploadUrl,
+ requestGeneration,
+ selectionGeneration
+ );
}
} catch (error) {
SafeLogger.error('Error uploading files:', error);
@@ -323,10 +350,37 @@ async function handleUploadFiles(e) {
}
}
+/**
+ * Show results and clear the picker only while this upload still owns the
+ * selection. The submit button is re-enabled before this delayed callback,
+ * so a user may already have selected or submitted a newer set of files.
+ */
+function scheduleUploadCompletion(data, requestGeneration, selectionGeneration) {
+ setTimeout(() => {
+ if (requestGeneration !== uploadGeneration ||
+ selectionGeneration !== fileSelectionGeneration) {
+ return;
+ }
+
+ showUploadResults(data);
+ document.getElementById('upload-files-form').reset();
+ selectedFiles = [];
+ fileSelectionGeneration++;
+ hideSelectedFiles();
+ }, 500);
+}
+
/**
* Handle batched upload - uploads files in smaller chunks
*/
-async function handleBatchedUpload(files, pdfStorageMode, csrfToken, uploadUrl) {
+async function handleBatchedUpload(
+ files,
+ pdfStorageMode,
+ csrfToken,
+ uploadUrl,
+ requestGeneration = uploadGeneration,
+ selectionGeneration = fileSelectionGeneration
+) {
const totalFiles = files.length;
const totalSize = files.reduce((sum, f) => sum + f.size, 0);
const batches = [];
@@ -386,12 +440,7 @@ async function handleBatchedUpload(files, pdfStorageMode, csrfToken, uploadUrl)
};
updateProgressComplete(combinedResult);
- setTimeout(() => {
- showUploadResults(combinedResult);
- document.getElementById('upload-files-form').reset();
- selectedFiles = [];
- hideSelectedFiles();
- }, 500);
+ scheduleUploadCompletion(combinedResult, requestGeneration, selectionGeneration);
}
/**
@@ -443,7 +492,14 @@ function uploadBatch(files, pdfStorageMode, csrfToken, uploadUrl, onProgress) {
/**
* Handle single upload (original behavior for small file sets)
*/
-async function handleSingleUpload(files, pdfStorageMode, csrfToken, uploadUrl) {
+async function handleSingleUpload(
+ files,
+ pdfStorageMode,
+ csrfToken,
+ uploadUrl,
+ requestGeneration = uploadGeneration,
+ selectionGeneration = fileSelectionGeneration
+) {
const formData = new FormData();
for (const file of files) {
formData.append('files', file);
@@ -487,12 +543,7 @@ async function handleSingleUpload(files, pdfStorageMode, csrfToken, uploadUrl) {
if (data.success) {
updateProgressComplete(data);
- setTimeout(() => {
- showUploadResults(data);
- document.getElementById('upload-files-form').reset();
- selectedFiles = [];
- hideSelectedFiles();
- }, 500);
+ scheduleUploadCompletion(data, requestGeneration, selectionGeneration);
} else {
showError(data.error || 'Upload failed');
}
diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.js
index a8a266644f..cb37524cda 100644
--- a/src/local_deep_research/web/static/js/collections_manager.js
+++ b/src/local_deep_research/web/static/js/collections_manager.js
@@ -6,6 +6,21 @@
// Store collections data
let collections = [];
+// Serialize writes per toggle so the backend cannot commit rapid same-key
+// changes out of order. Separate tails preserve concurrency across controls.
+const autoIndexSaveState = { generation: 0, tail: Promise.resolve(), confirmedValue: null };
+const backgroundSweepSaveState = { generation: 0, tail: Promise.resolve(), pendingCount: 0, confirmedValue: null };
+
+function queueControlSettingSave(state, operation) {
+ const generation = ++state.generation;
+ const queued = state.tail.then(
+ () => operation(generation),
+ () => operation(generation)
+ );
+ state.tail = queued.catch(() => {});
+ return queued;
+}
+
// safeFetch/safeFetchWithAuth are now provided by utils/safe-fetch.js loaded in base.html
// escapeHtml is the canonical window.escapeHtml from security/xss-protection.js
// (loaded first via base.html). Do NOT reintroduce a local fallback — it would
@@ -37,12 +52,17 @@ document.addEventListener('DOMContentLoaded', function() {
* Load the auto-index setting and update the toggle
*/
async function loadAutoIndexSetting() {
+ const hydrationGeneration = autoIndexSaveState.generation;
+ const isCurrent = () => hydrationGeneration === autoIndexSaveState.generation;
try {
const response = await safeFetchWithAuth('/settings/api/research_library.auto_index_enabled');
- if (!response.ok) return;
+ if (!isCurrent() || !response.ok) return;
const data = await response.json();
+ if (!isCurrent()) return;
const toggle = document.getElementById('auto-index-toggle');
toggle.checked = data.value === true || data.value === 'true';
+ // eslint-disable-next-line require-atomic-updates -- Generation checks after both awaits keep this hydration current.
+ autoIndexSaveState.confirmedValue = toggle.checked;
} catch (error) {
SafeLogger.error('Error loading auto-index setting:', error);
}
@@ -53,25 +73,37 @@ async function loadAutoIndexSetting() {
*/
async function saveAutoIndexSetting() {
const toggle = document.getElementById('auto-index-toggle');
- try {
- const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const response = await safeFetchWithAuth('/settings/api/research_library.auto_index_enabled', {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ value: toggle.checked })
- });
- const data = await response.json();
- if (!response.ok || data.error) {
- SafeLogger.error('Failed to save auto-index setting:', data.error);
- toggle.checked = !toggle.checked;
- }
- } catch (error) {
- SafeLogger.error('Error saving auto-index setting:', error);
- toggle.checked = !toggle.checked;
+ const desired = toggle.checked;
+ if (autoIndexSaveState.confirmedValue === null) {
+ autoIndexSaveState.confirmedValue = !desired;
}
+
+ return queueControlSettingSave(autoIndexSaveState, async (generation) => {
+ const isLatest = () => generation === autoIndexSaveState.generation;
+ try {
+ const csrfToken = window.api ? window.api.getCsrfToken() : '';
+ const response = await safeFetchWithAuth('/settings/api/research_library.auto_index_enabled', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ value: desired })
+ });
+ const data = await response.json();
+ if (!response.ok || data.error) {
+ SafeLogger.error('Failed to save auto-index setting:', data.error);
+ if (isLatest()) toggle.checked = autoIndexSaveState.confirmedValue;
+ } else {
+ // A successful earlier write is still the rollback baseline
+ // when a newer intent is queued and its write later fails.
+ autoIndexSaveState.confirmedValue = desired;
+ }
+ } catch (error) {
+ SafeLogger.error('Error saving auto-index setting:', error);
+ if (isLatest()) toggle.checked = autoIndexSaveState.confirmedValue;
+ }
+ });
}
/**
@@ -214,75 +246,94 @@ async function saveBackgroundSweepSetting() {
const toggle = document.getElementById('background-sweep-toggle');
const desired = toggle.checked;
const csrfToken = window.api ? window.api.getCsrfToken() : '';
- const putSetting = (key, value) => safeFetchWithAuth('/settings/api/' + key, {
- method: 'PUT',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({ value })
- });
- try {
- const response = await putSetting('document_scheduler.sweep_library_collections', desired);
- const preserveIndeterminateSuccess = (detail) => {
- // Trust a successful enable. For disable, an unknown body cannot
- // confirm the legacy gate is disarmed, so keep the honest ON state.
- SafeLogger.warn(
- 'Background-sweep setting write succeeded but its response was indeterminate; preserving ON state:',
- detail
- );
- setBackgroundSweepToggleState(true);
- };
- let data;
+
+ // Capture the displayed baseline once per pending burst. A later click
+ // reverses an intent, not necessarily a write the server accepted.
+ if (backgroundSweepSaveState.pendingCount === 0) {
+ backgroundSweepSaveState.confirmedValue = !desired;
+ }
+ backgroundSweepSaveState.pendingCount++;
+
+ return queueControlSettingSave(backgroundSweepSaveState, async (generation) => {
+ const isLatest = () => generation === backgroundSweepSaveState.generation;
+ const putSetting = (key, value) => safeFetchWithAuth('/settings/api/' + key, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({ value })
+ });
try {
- data = await response.json();
- } catch (error) {
- if (response.ok) {
- preserveIndeterminateSuccess(error);
+ const response = await putSetting('document_scheduler.sweep_library_collections', desired);
+ const preserveIndeterminateSuccess = (detail) => {
+ // Trust a successful enable. For disable, an unknown body cannot
+ // confirm the legacy gate is disarmed, so keep the honest ON state.
+ SafeLogger.warn(
+ 'Background-sweep setting write succeeded but its response was indeterminate; preserving ON state:',
+ detail
+ );
+ backgroundSweepSaveState.confirmedValue = true;
+ if (isLatest()) setBackgroundSweepToggleState(true);
+ };
+ let data;
+ try {
+ data = await response.json();
+ } catch (error) {
+ if (response.ok) {
+ preserveIndeterminateSuccess(error);
+ return;
+ }
+ throw error;
+ }
+ if (response.ok && data == null) {
+ preserveIndeterminateSuccess('empty response body');
return;
}
- throw error;
- }
- if (response.ok && data == null) {
- preserveIndeterminateSuccess('empty response body');
- return;
- }
- if (!response.ok || data == null || data.error) {
- SafeLogger.error('Failed to save background-sweep setting:', data?.error);
- toggle.checked = !desired;
- return;
- }
- // The reconciler runs while (sweep_library_collections OR generate_rag)
- // is set, so turning the toggle OFF must also clear the legacy
- // generate_rag arm — otherwise the sweep keeps running for upgraded
- // users and this control would not actually disable the feature it
- // governs. (Turning ON only needs sweep=true; the OR makes the legacy
- // value irrelevant.)
- //
- // Read the legacy arm first so the common default install (generate_rag
- // already false) skips a redundant PUT — avoiding a silent flip of the
- // separately-displayed Settings-page control and a needless second
- // reschedule. Crucially, this is the DISABLE action, so be conservative
- // about "unknown": readBackgroundSweepLegacyArm returns null when it
- // can't read the value (transient failure / unregistered), and we must
- // NOT treat that as "already off" — otherwise a blip would leave the
- // toggle showing OFF while generate_rag keeps the reconciler armed.
- // Skip the clear ONLY when we are certain it is already false.
- if (!desired && legacyArmNeedsClear(await readBackgroundSweepLegacyArm())) {
- const legacy = await putSetting('document_scheduler.generate_rag', false);
- const legacyData = await legacy.json();
- if (!legacy.ok || legacyData.error) {
- // sweep=false already persisted, but the legacy arm may still be
- // set, so the reconciler can stay armed — the honest state is ON.
- // Reflect reality rather than a false OFF.
- SafeLogger.error('Failed to clear legacy generate_rag on OFF:', legacyData.error);
- setBackgroundSweepToggleState(true);
+ if (!response.ok || data == null || data.error) {
+ SafeLogger.error('Failed to save background-sweep setting:', data?.error);
+ if (isLatest()) setBackgroundSweepToggleState(backgroundSweepSaveState.confirmedValue);
+ return;
}
+ // A successful ON is confirmed immediately. A successful primary
+ // OFF remains effectively ON until the legacy arm is disarmed.
+ backgroundSweepSaveState.confirmedValue = true;
+ // The reconciler runs while (sweep_library_collections OR generate_rag)
+ // is set, so turning the toggle OFF must also clear the legacy
+ // generate_rag arm — otherwise the sweep keeps running for upgraded
+ // users and this control would not actually disable the feature it
+ // governs. (Turning ON only needs sweep=true; the OR makes the legacy
+ // value irrelevant.)
+ //
+ // Read the legacy arm first so the common default install (generate_rag
+ // already false) skips a redundant PUT — avoiding a silent flip of the
+ // separately-displayed Settings-page control and a needless second
+ // reschedule. Crucially, this is the DISABLE action, so be conservative
+ // about "unknown": readBackgroundSweepLegacyArm returns null when it
+ // can't read the value (transient failure / unregistered), and we must
+ // NOT treat that as "already off" — otherwise a blip would leave the
+ // toggle showing OFF while generate_rag keeps the reconciler armed.
+ // Skip the clear ONLY when we are certain it is already false.
+ if (!desired && legacyArmNeedsClear(await readBackgroundSweepLegacyArm())) {
+ const legacy = await putSetting('document_scheduler.generate_rag', false);
+ const legacyData = await legacy.json();
+ if (!legacy.ok || legacyData.error) {
+ // sweep=false already persisted, but the legacy arm may still be
+ // set, so the reconciler can stay armed — the honest state is ON.
+ // Reflect reality rather than a false OFF.
+ SafeLogger.error('Failed to clear legacy generate_rag on OFF:', legacyData.error);
+ if (isLatest()) setBackgroundSweepToggleState(true);
+ return;
+ }
+ }
+ backgroundSweepSaveState.confirmedValue = desired;
+ } catch (error) {
+ SafeLogger.error('Error saving background-sweep setting:', error);
+ if (isLatest()) setBackgroundSweepToggleState(backgroundSweepSaveState.confirmedValue);
}
- } catch (error) {
- SafeLogger.error('Error saving background-sweep setting:', error);
- setBackgroundSweepToggleState(!desired);
- }
+ }).finally(() => {
+ backgroundSweepSaveState.pendingCount--;
+ });
}
/**
@@ -594,6 +645,8 @@ if (typeof window !== 'undefined') {
window.bindReindexButtons = bindReindexButtons;
window.triggerReindex = triggerReindex;
window.collectionApiUrl = collectionApiUrl;
+ window.loadAutoIndexSetting = loadAutoIndexSetting;
+ window.saveAutoIndexSetting = saveAutoIndexSetting;
window.loadBackgroundSweepSetting = loadBackgroundSweepSetting;
window.saveBackgroundSweepSetting = saveBackgroundSweepSetting;
}
diff --git a/src/local_deep_research/web/static/js/components/annotation_surface.js b/src/local_deep_research/web/static/js/components/annotation_surface.js
index 9157a24761..4c5cb60549 100644
--- a/src/local_deep_research/web/static/js/components/annotation_surface.js
+++ b/src/local_deep_research/web/static/js/components/annotation_surface.js
@@ -523,7 +523,10 @@
});
const data = await response.json().catch(() => ({}));
if (!response.ok || !data.success) {
- throw new Error(data.error || `Server returned ${response.status}`);
+ throw new Error(
+ data.error || data.detail ||
+ `Server returned ${response.status}`
+ );
}
closePopover();
toast('Comment deleted', 'success');
diff --git a/src/local_deep_research/web/static/js/components/chat.js b/src/local_deep_research/web/static/js/components/chat.js
index 78382e5a09..37795ed54c 100644
--- a/src/local_deep_research/web/static/js/components/chat.js
+++ b/src/local_deep_research/web/static/js/components/chat.js
@@ -45,6 +45,13 @@
let oldestLoadedId = null;
let hasMoreMessages = false;
let isLoadingOlderMessages = false;
+ // Invalidates an async session hydration when a newer load or an explicit
+ // New Chat reset takes ownership of the view while fetches are in flight.
+ let sessionLoadGeneration = 0;
+ // A Send can claim the SAME session while its initial message hydration is
+ // pending, so session id + load generation alone cannot detect that race.
+ // Increment this for every accepted Send to retire the stale DB snapshot.
+ let sessionInteractionGeneration = 0;
// Research step config
const STEP_ICONS = {
@@ -67,6 +74,8 @@
// string and OOM the tab. Past the cap we stop appending and show a
// one-time truncation notice.
const MAX_STREAM_BUFFER_CHARS = 256 * 1024;
+ const STREAM_TRUNCATION_NOTICE =
+ '\n\n_(Response truncated — exceeded display limit.)_';
let streamTruncated = false;
// DOM elements
@@ -145,6 +154,17 @@
if (isLoadingOlderMessages || !sessionId || !oldestLoadedCreatedAt) return;
isLoadingOlderMessages = true;
+ // A session switch can happen while this page is awaiting the API.
+ // Snapshot both pieces of view ownership so the abandoned response
+ // cannot prepend messages (or release the loading lock) in the next
+ // session.
+ const sessionIdAtRequest = sessionId;
+ const loadGenerationAtRequest = sessionLoadGeneration;
+ const ownsPagination = () => (
+ sessionLoadGeneration === loadGenerationAtRequest &&
+ sessionId === sessionIdAtRequest
+ );
+
const btn = document.getElementById('ldr-chat-load-older-btn');
if (btn) {
btn.disabled = true;
@@ -157,12 +177,13 @@
const scrollTopBefore = chatMessages.scrollTop;
try {
- let url = `/api/chat/sessions/${encodeURIComponent(sessionId)}/messages` +
+ let url = `/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}/messages` +
`?before_created_at=${encodeURIComponent(oldestLoadedCreatedAt)}`;
if (oldestLoadedId) {
url += `&before_id=${encodeURIComponent(oldestLoadedId)}`;
}
const data = await apiGet(url);
+ if (!ownsPagination()) return;
if (!data || !Array.isArray(data.messages) || data.messages.length === 0) {
hasMoreMessages = false;
@@ -213,18 +234,21 @@
hasMoreMessages = !!data.has_more;
renderLoadOlderButton();
} catch (e) {
+ if (!ownsPagination()) return;
_log.error('Error loading older messages:', e);
if (btn) {
btn.disabled = false;
btn.textContent = 'Load older messages';
}
} finally {
- // Preserve scroll position so the user's current view is
- // not displaced by the prepended content.
- const scrollHeightAfter = chatMessages.scrollHeight;
- chatMessages.scrollTop = scrollTopBefore + (scrollHeightAfter - scrollHeightBefore);
- // eslint-disable-next-line require-atomic-updates
- isLoadingOlderMessages = false;
+ if (ownsPagination()) {
+ // Preserve scroll position so the user's current view is
+ // not displaced by the prepended content.
+ const scrollHeightAfter = chatMessages.scrollHeight;
+ chatMessages.scrollTop = scrollTopBefore + (scrollHeightAfter - scrollHeightBefore);
+ // eslint-disable-next-line require-atomic-updates
+ isLoadingOlderMessages = false;
+ }
}
}
@@ -260,6 +284,12 @@
setupEventListeners();
setupTextareaAutoResize();
+ // A routed `?q=` is a one-shot bootstrap action. Snapshot user
+ // interaction before hydration so a manual Send during a slow restore
+ // wins even if that request fails (and clears isProcessing) before the
+ // restore settles.
+ const interactionGenerationAtInit = sessionInteractionGeneration;
+
// Check for existing session ID from meta tag
const sessionMeta = document.querySelector('meta[name="chat-session-id"]');
if (sessionMeta && sessionMeta.content) {
@@ -280,12 +310,21 @@
// Auto-send initial query from URL parameter (e.g., from main page chat mode)
const urlParams = new URLSearchParams(window.location.search);
const initialQuery = urlParams.get('q');
- if (initialQuery && sessionId && !isProcessing) {
- // Clean the URL without reloading
+ if (initialQuery) {
+ // Always consume the one-shot query. A manual Send may already own
+ // the composer; leaving `?q=` behind would replay it on a later
+ // reload after that research finishes.
window.history.replaceState({}, '', window.location.pathname);
- // eslint-disable-next-line require-atomic-updates -- one-shot init flow
- chatInput.value = initialQuery;
- handleSend();
+ if (
+ !isProcessing &&
+ sessionInteractionGeneration === interactionGenerationAtInit
+ ) {
+ // handleSend creates a session when a fresh `/chat/?q=...`
+ // bootstrap has no recent conversation to restore.
+ // eslint-disable-next-line require-atomic-updates -- one-shot init flow
+ chatInput.value = initialQuery;
+ handleSend();
+ }
}
// Readiness signal: init is fully settled, including the async
@@ -466,7 +505,11 @@
* research id is removed.
*/
async function handleDeleteAttempt(researchId) {
- if (!researchId || !sessionId) return;
+ // A retry/new research owns the chat until it settles. Allowing Delete
+ // to supersede it can strand isProcessing if the delete then fails.
+ if (!researchId || !sessionId || isProcessing) return;
+ const sessionIdAtRequest = sessionId;
+ const loadGenerationAtRequest = sessionLoadGeneration;
// Default to the "Re-run / replace" wording which is safe for
// both failed and completed attempts — the client doesn't
// always know the prior status cheaply.
@@ -476,13 +519,21 @@
);
if (!ok) return;
+ const interactionGenerationAtRequest = sessionInteractionGeneration;
+ const ownsAttempt = () => (
+ sessionLoadGeneration === loadGenerationAtRequest &&
+ sessionInteractionGeneration === interactionGenerationAtRequest &&
+ sessionId === sessionIdAtRequest
+ );
+
try {
await apiPost(
- `/api/chat/sessions/${encodeURIComponent(sessionId)}/attempts/${encodeURIComponent(researchId)}`,
+ `/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}/attempts/${encodeURIComponent(researchId)}`,
null,
'DELETE',
);
} catch (e) {
+ if (!ownsAttempt()) return;
_log.error('Chat: delete attempt failed', e);
const raw = (e && e.message) ? e.message : '';
const display = raw && !/^Request failed \(\d+\)$/.test(raw)
@@ -495,6 +546,8 @@
return;
}
+ if (!ownsAttempt()) return;
+
// Remove every DOM node tagged with this research id: the user
// message, any assistant response(s), and the step accordion.
// The step accordion is built by ensureLiveAccordion/wrap-
@@ -502,7 +555,7 @@
// full session reload is the simplest correct path. Cheaper
// alternative would be a sibling walk, but the reload also
// fixes any message_count drift in the sidebar.
- await loadSession(sessionId);
+ await loadSession(sessionIdAtRequest);
}
/**
@@ -518,12 +571,21 @@
*/
async function handleRetryAttempt(researchId) {
if (!researchId || !sessionId || isProcessing) return;
+ const sessionIdAtRequest = sessionId;
+ const loadGenerationAtRequest = sessionLoadGeneration;
const ok = window.confirm(
'Re-run this attempt? The previous response will be '
+ 'replaced and the same query will be submitted again.'
);
if (!ok) return;
+ const interactionGenerationAtRequest = ++sessionInteractionGeneration;
+ const ownsAttempt = () => (
+ sessionLoadGeneration === loadGenerationAtRequest &&
+ sessionInteractionGeneration === interactionGenerationAtRequest &&
+ sessionId === sessionIdAtRequest
+ );
+
// If a different research is in-flight (e.g. user started a new
// turn after the failed one), tear down its listeners before
// subscribing to the new id — otherwise step events from the
@@ -546,9 +608,10 @@
try {
const data = await apiPost(
- `/api/chat/sessions/${encodeURIComponent(sessionId)}/attempts/${encodeURIComponent(researchId)}/retry`,
+ `/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}/attempts/${encodeURIComponent(researchId)}/retry`,
{},
);
+ if (!ownsAttempt()) return;
if (!data.research_id) {
throw new Error('Server did not return a new research_id');
}
@@ -569,9 +632,9 @@
// detached thinkingEl — so we deliberately don't. Mirrors
// handleDeleteAttempt. Use the captured sessionId to avoid
// races with a concurrent startNewChat().
- const sidAtCall = sessionId;
- await loadSession(sidAtCall);
+ await loadSession(sessionIdAtRequest);
} catch (e) {
+ if (!ownsAttempt()) return;
_log.error('Chat: retry attempt failed', e);
removeThinking(thinkingEl);
const raw = (e && e.message) ? e.message : '';
@@ -613,7 +676,9 @@
const r = await fetch(url, { headers: { 'X-CSRFToken': getCsrfToken() } });
if (!r.ok) {
const err = await r.json().catch(() => ({}));
- throw new Error(err.error || `Request failed (${r.status})`);
+ throw new Error(
+ err.error || err.detail || `Request failed (${r.status})`
+ );
}
const data = await r.json();
if (!data.success) throw new Error(data.error || 'Request failed');
@@ -634,7 +699,9 @@
const r = await fetch(url, options);
if (!r.ok) {
const err = await r.json().catch(() => ({}));
- throw new Error(err.error || `Request failed (${r.status})`);
+ throw new Error(
+ err.error || err.detail || `Request failed (${r.status})`
+ );
}
const data = await r.json();
if (!data.success) throw new Error(data.error || 'Request failed');
@@ -647,6 +714,17 @@
async function handleSend() {
const content = chatInput.value.trim();
if (!content || isProcessing) return;
+ sessionInteractionGeneration++;
+
+ // Typing the first message is an explicit claim on the blank chat
+ // surface. Retire any still-pending "most recent session" bootstrap
+ // before it can hydrate an older conversation over this new one.
+ const loadGenerationAtRequest = sessionId
+ ? sessionLoadGeneration
+ : ++sessionLoadGeneration;
+ const ownsSend = () => (
+ sessionLoadGeneration === loadGenerationAtRequest
+ );
isProcessing = true;
sendBtn.disabled = true;
@@ -677,7 +755,11 @@
// module-level sessionId before our POST URL is built.
let targetSessionId = sessionId;
if (!targetSessionId) {
- targetSessionId = await createSession(content);
+ targetSessionId = await createSession(
+ content,
+ loadGenerationAtRequest,
+ );
+ if (!ownsSend()) return;
}
// Send message
@@ -685,6 +767,7 @@
content,
trigger_research: true,
});
+ if (!ownsSend() || sessionId !== targetSessionId) return;
// If research was triggered, subscribe to updates
if (data.research_id) {
@@ -710,6 +793,7 @@
}
} catch (error) {
+ if (!ownsSend()) return;
_log.error('Error sending message:', error);
removeThinking(thinkingEl);
// Surface the server-provided error so the user can tell
@@ -734,12 +818,24 @@
/**
* Create a new chat session.
*/
- async function createSession(initialQuery) {
+ async function createSession(
+ initialQuery,
+ expectedLoadGeneration = sessionLoadGeneration,
+ ) {
const data = await apiPost('/api/chat/sessions', {
initial_query: initialQuery,
});
- sessionId = data.session_id;
+ // Creating the session is a server-side side effect that cannot be
+ // cancelled, but a New Chat/session switch can retire this caller
+ // before the response arrives. Do not let that abandoned response
+ // reclaim the URL, title, or module-level session ownership.
+ const _createdId = data.session_id;
+ if (expectedLoadGeneration !== sessionLoadGeneration) {
+ return _createdId;
+ }
+
+ sessionId = _createdId;
// Update URL without reload
window.history.pushState({}, '', `/chat/${sessionId}`);
@@ -748,8 +844,6 @@
// startNewChat()+createSession() pair could overwrite before
// the caller's POST URL is built (race manifests as messages
// landing in the wrong session).
- const _createdId = data.session_id;
-
// Update title with the immediate fallback title from the server.
if (data.session && data.session.title) {
updateTitle(data.session.title);
@@ -773,6 +867,7 @@
resp &&
resp.success &&
resp.title &&
+ sessionLoadGeneration === expectedLoadGeneration &&
sessionId === createdSessionId &&
chatTitle?.textContent === titleAtRequest
) {
@@ -796,11 +891,31 @@
* Load the most recent session if available.
*/
async function loadMostRecentSession() {
+ const loadGenerationAtRequest = sessionLoadGeneration;
+ const sessionIdAtRequest = sessionId;
+ const ownsBootstrap = () => (
+ sessionLoadGeneration === loadGenerationAtRequest &&
+ sessionId === sessionIdAtRequest
+ );
+
+ let data;
try {
- const data = await apiGet('/api/chat/sessions?limit=1');
+ data = await apiGet('/api/chat/sessions?limit=1');
+ } catch (error) {
+ if (!ownsBootstrap()) return;
+ _log.error('Error loading recent session:', error);
+ showWelcomeScreen();
+ return;
+ }
+ if (!ownsBootstrap()) return;
+
+ try {
if (data.sessions && data.sessions.length > 0) {
const recentSession = data.sessions[0];
+ // ownsBootstrap() above validates both the generation and
+ // blank-session identity after the awaited list request.
+ // eslint-disable-next-line require-atomic-updates
sessionId = recentSession.id;
// Update URL without reload
@@ -811,6 +926,9 @@
showWelcomeScreen();
}
} catch (error) {
+ // A user action or replacement session that took ownership while
+ // the bootstrap was settling also owns the welcome state.
+ if (!ownsBootstrap() && sessionId !== data.sessions?.[0]?.id) return;
_log.error('Error loading recent session:', error);
showWelcomeScreen();
}
@@ -820,12 +938,19 @@
* Load an existing session.
*/
async function loadSession(id) {
+ const ownLoadGeneration = ++sessionLoadGeneration;
+ const interactionGenerationAtLoad = sessionInteractionGeneration;
+ const ownsLoad = () => (
+ ownLoadGeneration === sessionLoadGeneration &&
+ interactionGenerationAtLoad === sessionInteractionGeneration
+ );
try {
completionHandled = true;
resetActiveResearchState();
// Load session info
const sessionData = await apiGet(`/api/chat/sessions/${id}`);
+ if (!ownsLoad()) return;
// Update title
if (sessionData.session && sessionData.session.title) {
@@ -834,6 +959,7 @@
// Load messages
const messagesData = await apiGet(`/api/chat/sessions/${id}/messages`);
+ if (!ownsLoad()) return;
if (messagesData.messages.length > 0) {
hideWelcomeScreen();
@@ -915,6 +1041,7 @@
}
} catch (error) {
+ if (!ownsLoad()) return;
_log.error('Error loading session:', error);
sessionId = null;
showWelcomeScreen();
@@ -966,6 +1093,9 @@
oldestLoadedCreatedAt = null;
oldestLoadedId = null;
hasMoreMessages = false;
+ // Any pagination request retired by the session generation guard must
+ // not keep the replacement session locked in a loading state.
+ isLoadingOlderMessages = false;
lastStepPhase = null;
hideProgress();
}
@@ -1003,7 +1133,7 @@
// bearer:disable javascript_lang_dangerous_insert_html
// eslint-disable-next-line no-unsanitized/property -- audited: renderMarkdown() sanitizes via DOMPurify (app.js bundle), with textContent fallback on error
textEl.innerHTML = window.ui.renderMarkdown(content);
- } catch (e) {
+ } catch (_e) {
textEl.textContent = content;
}
} else {
@@ -1061,6 +1191,7 @@
* Start a new chat.
*/
function startNewChat() {
+ sessionLoadGeneration++;
completionHandled = true;
resetActiveResearchState();
@@ -1546,20 +1677,32 @@
// N reconnects.
if (_stableProgressCb === null) {
_stableProgressCb = (data) => {
- // Always read current research/element from closure state —
- // a stale `thinkingEl` captured at subscribe time would be
- // wrong after session switches.
+ // Resolve the current thinking bubble from the live DOM. Once
+ // streaming starts, `streamingMessageEl` is the partial answer,
+ // not a thinking indicator; passing it as `thinkingEl` made the
+ // suspended path remove the answer it was meant to preserve.
+ // A stale element captured at subscribe time is also wrong
+ // after a session switch.
if (data && data.research_id && data.research_id !== currentResearchId) {
return; // Late event for an old research; ignore.
}
+ const currentThinkingEl = chatMessages?.querySelector(
+ '.ldr-chat-message-thinking'
+ );
try {
- handleProgressUpdate(data, streamingMessageEl);
+ handleProgressUpdate(data, currentThinkingEl);
} catch (err) {
_log.error('Chat: progress handler threw', err);
- handleResearchError(streamingMessageEl, err && err.message ? err.message : 'Internal error');
+ handleResearchError(
+ currentThinkingEl,
+ err && err.message ? err.message : 'Internal error'
+ );
}
};
}
+ // Chat already owns its one-second completion poll, even while the
+ // socket is connected. Do not add a second generic service poll.
+ window.socket.setPollingFallback?.(() => {});
window.socket.subscribeToResearch(researchId, _stableProgressCb);
// Subscribe to streaming response chunks. Same try/catch wrapper —
@@ -1570,6 +1713,13 @@
// Remove any existing listener to prevent duplicates on retry/reconnect
socket.off(`response_chunk_${researchId}`);
socket.on(`response_chunk_${researchId}`, (data) => {
+ // socket.off() prevents future delivery, but a callback that was
+ // already queued before a session switch can still run. Keep an
+ // old research's chunk out of the new research's shared stream
+ // buffer and DOM.
+ if (currentResearchId !== researchId) {
+ return;
+ }
try {
handleResponseChunk(data, thinkingEl);
} catch (err) {
@@ -1775,15 +1925,20 @@
}
// Accumulate content (bounded — see MAX_STREAM_BUFFER_CHARS).
- if (chunk) {
- if (streamedContent.length < MAX_STREAM_BUFFER_CHARS) {
+ // Final events carry a full snapshot (or an empty sentinel), not a
+ // delta. Appending that snapshot here would count the answer twice
+ // and falsely truncate otherwise valid responses near the cap.
+ if (chunk && !is_final && !streamTruncated) {
+ const remaining = MAX_STREAM_BUFFER_CHARS - streamedContent.length;
+ if (chunk.length <= remaining) {
streamedContent += chunk;
- } else if (!streamTruncated) {
- // Cross the cap exactly once: append a visible notice and
- // stop accumulating so a runaway stream can't OOM the tab.
+ } else {
+ // Bound the chunk itself as well as later accumulation. A
+ // provider can deliver one very large callback, so checking
+ // only the pre-append buffer length does not enforce the cap.
+ streamedContent += chunk.slice(0, Math.max(remaining, 0));
streamTruncated = true;
- streamedContent +=
- '\n\n_(Response truncated — exceeded display limit.)_';
+ streamedContent += STREAM_TRUNCATION_NOTICE;
}
// Debounced render: update the DOM at most every 100ms during streaming
@@ -1815,7 +1970,16 @@
// shorter than half of what's already been streamed, treat it
// as a partial-delivery anomaly and keep the accumulated buffer.
let finalContent;
- if (chunk && chunk.length >= streamedContent.length * 0.5) {
+ if (streamTruncated) {
+ // Never let a full final payload bypass the client-side
+ // display bound after incremental delivery crossed it.
+ finalContent = streamedContent;
+ } else if (chunk && chunk.length > MAX_STREAM_BUFFER_CHARS) {
+ streamTruncated = true;
+ streamedContent = chunk.slice(0, MAX_STREAM_BUFFER_CHARS)
+ + STREAM_TRUNCATION_NOTICE;
+ finalContent = streamedContent;
+ } else if (chunk && chunk.length >= streamedContent.length * 0.5) {
finalContent = chunk;
streamedContent = chunk;
} else if (chunk && streamedContent) {
@@ -1865,21 +2029,31 @@
const ownResearchId = researchId;
const poll = async () => {
- if (
- pollCount >= maxPolls
- || !currentResearchId
- || currentResearchId !== ownResearchId
- ) {
+ if (pollCount >= maxPolls) {
pollTimerId = null;
return;
}
+ if (!currentResearchId || currentResearchId !== ownResearchId) {
+ // A newer research may already own pollTimerId. Do not clear
+ // that shared handle while retiring this stale closure.
+ return;
+ }
try {
const response = await fetch(`/api/research/${researchId}/status`, {
headers: { 'X-CSRFToken': getCsrfToken() }
});
+ if (currentResearchId !== ownResearchId) {
+ return;
+ }
if (!response.ok) throw new Error(`Status check failed (${response.status})`);
const data = await response.json();
+ // Ownership can also change while response.json() is pending.
+ // Applying A's terminal snapshot to B would complete/error the
+ // wrong chat and release B's listeners.
+ if (currentResearchId !== ownResearchId) {
+ return;
+ }
if (data.status === 'completed') {
pollTimerId = null;
@@ -1915,6 +2089,9 @@
pollTimerId = setTimeout(poll, pollInterval);
} catch (error) {
+ if (currentResearchId !== ownResearchId) {
+ return;
+ }
_log.error('Polling error:', error);
pollCount++;
pollTimerId = setTimeout(poll, pollInterval * 2);
@@ -1950,6 +2127,8 @@
// loadSession both reassign module-level sessionId). Without this
// snapshot, post-await DOM writes land in the wrong session's view.
const sessionIdAtComplete = sessionId;
+ const sessionLoadGenerationAtComplete = sessionLoadGeneration;
+ const sessionInteractionGenerationAtComplete = sessionInteractionGeneration;
try {
// Remove thinking indicator
@@ -2031,7 +2210,7 @@
if (textEl) renderToElement(textEl, 'Research completed — the chat copy of the answer could not be loaded. Open the full report below.');
_appendResearchLink(streamingMessageEl, researchIdToFetch);
}
- } catch (e) {
+ } catch (_e) {
if (sessionId === sessionIdAtComplete) {
const textEl = streamingMessageEl.querySelector('.ldr-chat-message-text');
if (textEl) renderToElement(textEl, 'Research completed — the chat copy of the answer could not be loaded. Open the full report below.');
@@ -2054,7 +2233,7 @@
} else {
addMessageToUI('assistant', 'Research completed — the chat copy of the answer could not be loaded. Open the full report below.', null, researchIdToFetch);
}
- } catch (e) {
+ } catch (_e) {
if (sessionId === sessionIdAtComplete) {
addMessageToUI('assistant', 'Research completed — the chat copy of the answer could not be loaded. Open the full report below.', null, researchIdToFetch);
}
@@ -2069,35 +2248,45 @@
// when the live-chunk path didn't end up with a visible
// response (transient socket drop, race on session switch,
// missed is_final, etc.).
- await refreshSessionMessages(researchIdToFetch);
+ await refreshSessionMessages(
+ researchIdToFetch,
+ sessionIdAtComplete,
+ sessionLoadGenerationAtComplete,
+ sessionInteractionGenerationAtComplete,
+ );
} catch (error) {
_log.error('Error fetching research result:', error);
- if (!streamingComplete) {
+ if (sessionId === sessionIdAtComplete && !streamingComplete) {
addMessageToUI('assistant', 'Research completed but there was an error loading the results.');
}
} finally {
- cancelPendingTimers();
- hideProgress();
- isProcessing = false;
- sendBtn.disabled = !chatInput.value.trim();
+ // Always release the completed research's listener, but do not let
+ // an older async completion mutate controls/timers that now belong
+ // to a newly selected session.
+ cleanupSocketListeners(researchIdToFetch);
+ if (sessionId === sessionIdAtComplete) {
+ cancelPendingTimers();
+ hideProgress();
+ isProcessing = false;
+ sendBtn.disabled = !chatInput.value.trim();
+
+ // Collapse live accordion and clean up live classes
+ if (liveAccordion) {
+ liveAccordion.classList.add('ldr-chat-steps-collapsed');
+ const header = liveAccordion.querySelector('.ldr-chat-steps-header');
+ if (header) header.setAttribute('aria-expanded', 'false');
+ liveAccordion.querySelectorAll('.ldr-chat-step-live').forEach(el => {
+ el.classList.remove('ldr-chat-step-live');
+ });
+ delete liveAccordion.dataset.live;
+ liveAccordion = null;
+ }
+ lastStepPhase = null;
- // Collapse live accordion and clean up live classes
- if (liveAccordion) {
- liveAccordion.classList.add('ldr-chat-steps-collapsed');
- const header = liveAccordion.querySelector('.ldr-chat-steps-header');
- if (header) header.setAttribute('aria-expanded', 'false');
- liveAccordion.querySelectorAll('.ldr-chat-step-live').forEach(el => {
- el.classList.remove('ldr-chat-step-live');
- });
- delete liveAccordion.dataset.live;
- liveAccordion = null;
+ resetStreamingVars();
+ showSessionButtons();
}
- lastStepPhase = null;
-
- cleanupSocketListeners(researchIdToFetch);
- resetStreamingVars();
- showSessionButtons();
}
}
@@ -2172,6 +2361,12 @@
throw new Error('Terminate API not available');
}
await window.api.terminateResearch(rid);
+ // A New Chat/session switch can happen while termination is in
+ // flight. Its result belongs to the captured research only; do
+ // not hide or relabel controls now owned by a newer research.
+ if (currentResearchId !== rid) {
+ return;
+ }
// The terminate API just sets a flag and returns. The worker
// thread can take 0-30s to actually exit if it's blocked
// inside an LLM HTTP call (thinking-mode <think> blocks don't
@@ -2198,6 +2393,9 @@
}
_setBtnLabel('fa-stop', 'Stop');
} catch (error) {
+ if (currentResearchId !== rid) {
+ return;
+ }
_clearStopElapsedTimer();
_log.error('Failed to stop research:', error);
if (stopResearchBtn) {
@@ -2238,6 +2436,12 @@
return;
}
suspendedHandled = true;
+ // A chunk may have arrived inside the 100ms render debounce window
+ // immediately before Stop. Flush that owned buffer before cancelling
+ // timers so the partial answer is not silently discarded.
+ if (streamingMessageEl && streamedContent) {
+ renderStreamedContent();
+ }
cancelPendingTimers();
if (currentResearchId) {
cleanupSocketListeners(currentResearchId);
@@ -2277,16 +2481,29 @@
/**
* Refresh session messages from server.
*/
- async function refreshSessionMessages(expectedResearchId) {
- if (!sessionId) return;
+ async function refreshSessionMessages(
+ expectedResearchId,
+ expectedSessionId = sessionId,
+ expectedLoadGeneration = sessionLoadGeneration,
+ expectedInteractionGeneration = sessionInteractionGeneration,
+ ) {
+ if (!expectedSessionId) return;
+ const ownsRefresh = () => (
+ sessionId === expectedSessionId &&
+ sessionLoadGeneration === expectedLoadGeneration &&
+ sessionInteractionGeneration === expectedInteractionGeneration
+ );
+ if (!ownsRefresh()) return;
try {
// Refresh session title (may have been auto-generated from first message)
- const sessionResponse = await fetch(`/api/chat/sessions/${sessionId}`, {
+ const sessionResponse = await fetch(`/api/chat/sessions/${expectedSessionId}`, {
headers: { 'X-CSRFToken': getCsrfToken() },
});
+ if (!ownsRefresh()) return;
if (sessionResponse.ok) {
const sessionData = await sessionResponse.json();
+ if (!ownsRefresh()) return;
if (sessionData.success && sessionData.session && sessionData.session.title) {
updateTitle(sessionData.session.title);
}
@@ -2302,12 +2519,12 @@
// finished and (b) no assistant message with that research_id
// is currently in the DOM. The happy path is a cheap DOM
// query and a no-op.
- if (expectedResearchId && chatMessages) {
+ if (expectedResearchId && chatMessages && ownsRefresh()) {
const ridSelector = `.ldr-chat-message-assistant:not(.ldr-chat-message-step)[data-research-id="${CSS.escape(expectedResearchId)}"]`;
const haveResponse = !!chatMessages.querySelector(ridSelector);
if (!haveResponse) {
_log.warn('Chat: response bubble missing after completion; re-rendering from DB', { researchId: expectedResearchId });
- await loadSession(sessionId);
+ await loadSession(expectedSessionId);
}
}
} catch (error) {
@@ -2404,8 +2621,14 @@
const newTitle = prompt('Enter new title:', currentTitle);
if (newTitle && newTitle !== currentTitle && sessionId) {
+ const sessionIdAtRequest = sessionId;
+ const loadGenerationAtRequest = sessionLoadGeneration;
+ const ownsTitleEdit = () => (
+ sessionId === sessionIdAtRequest &&
+ sessionLoadGeneration === loadGenerationAtRequest
+ );
try {
- const response = await fetch(`/api/chat/sessions/${sessionId}`, {
+ const response = await fetch(`/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
@@ -2414,15 +2637,17 @@
body: JSON.stringify({ title: newTitle }),
});
+ if (!ownsTitleEdit()) return;
if (!response.ok) {
_log.error(`Failed to update title (${response.status})`);
return;
}
const data = await response.json();
- if (data.success) {
+ if (ownsTitleEdit() && data.success) {
updateTitle(newTitle);
}
} catch (error) {
+ if (!ownsTitleEdit()) return;
_log.error('Error updating title:', error);
}
}
@@ -2437,6 +2662,13 @@
return;
}
+ // Export the session the user selected when they clicked, even if
+ // they start or load another chat while cursor pages are in flight.
+ // Re-reading the module globals between pages can mix conversations
+ // and can also give the archive the replacement chat's title.
+ const sessionIdAtRequest = sessionId;
+ const titleAtRequest = chatTitle?.textContent || 'Chat Session';
+
try {
// Fetch ALL messages by paging the cursor backwards. A bare
// /messages call returns at most 50 (server default) or 100
@@ -2452,7 +2684,7 @@
// true). At 100 per page this caps export at 50k messages.
const MAX_PAGES = 500;
for (let i = 0; i < MAX_PAGES; i++) {
- let pageUrl = `/api/chat/sessions/${sessionId}/messages?limit=${PAGE_SIZE}`;
+ let pageUrl = `/api/chat/sessions/${encodeURIComponent(sessionIdAtRequest)}/messages?limit=${PAGE_SIZE}`;
if (cursorCreatedAt) {
pageUrl += `&before_created_at=${encodeURIComponent(cursorCreatedAt)}`;
}
@@ -2474,7 +2706,7 @@
}
// Build markdown content
- const title = chatTitle?.textContent || 'Chat Session';
+ const title = titleAtRequest;
const exportDate = new Date().toLocaleString();
// Escape title for Markdown-heading context. The user-controlled
@@ -2535,7 +2767,7 @@
} else {
link.href = url; // blob: URL is safe to assign directly
}
- link.download = `${title.replace(/[^a-z0-9]/gi, '_')}_${sessionId.slice(0, 8)}.md`;
+ link.download = `${title.replace(/[^a-z0-9]/gi, '_')}_${sessionIdAtRequest.slice(0, 8)}.md`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
diff --git a/src/local_deep_research/web/static/js/components/context-overflow.js b/src/local_deep_research/web/static/js/components/context-overflow.js
index 0046624a5b..e3b4026451 100644
--- a/src/local_deep_research/web/static/js/components/context-overflow.js
+++ b/src/local_deep_research/web/static/js/components/context-overflow.js
@@ -46,7 +46,11 @@
if (text == null) return '';
const div = document.createElement('div');
div.textContent = String(text);
- return div.innerHTML;
+ // innerHTML escapes text-node delimiters such as < and &, but leaves
+ // quotes untouched. This helper is also used inside quoted title
+ // attributes below, so escape both quote styles as well to prevent a
+ // research query from breaking out into an event-handler attribute.
+ return div.innerHTML.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
}
// Helper function to format model names for better display
@@ -151,7 +155,18 @@
if (!token_summary || token_summary.total_requests === 0) {
document.getElementById('empty-no-data').style.display = 'block';
document.getElementById('warning-banner').style.display = 'none';
+ document.getElementById('empty-no-context-data').style.display = 'none';
+ document.getElementById('empty-no-truncation').style.display = 'none';
document.getElementById('context-overflow-section').innerHTML = '';
+
+ // A period change can transition from populated data to no data.
+ // Clear the prior period's client-side rows and pagination rather
+ // than leaving stale requests visible below the empty-state card.
+ currentPageData = [];
+ currentPage = pagination?.page || 1;
+ totalPages = pagination?.total_pages || 1;
+ renderRequestsTable();
+ updatePaginationControls();
return;
}
document.getElementById('empty-no-data').style.display = 'none';
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 5debfdd87a..98ed0e9f9c 100644
--- a/src/local_deep_research/web/static/js/components/details.js
+++ b/src/local_deep_research/web/static/js/components/details.js
@@ -112,13 +112,13 @@
// Use DOMPurify for secure HTML rendering
const domainHtml = data.domains.map(domain => `
<div style="display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; border-bottom: 1px solid var(--border-color);">
- <span style="font-weight: 500;">${window.escapeHtml(domain.domain)}</span>
+ <span style="font-weight: 500;">${escapeHtml(domain.domain)}</span>
<div style="display: flex; gap: 1rem; align-items: center;">
<span style="background: var(--primary-color); color: white; padding: 0.25rem 0.5rem; border-radius: 0.25rem; font-size: 0.875rem;">
- ${window.escapeHtml(domain.count)} links
+ ${escapeHtml(domain.count)} links
</span>
<span style="color: var(--text-secondary); font-size: 0.875rem;">
- ${window.escapeHtml(domain.percentage)}%
+ ${escapeHtml(domain.percentage)}%
</span>
</div>
</div>
@@ -126,12 +126,10 @@
if (window.sanitizeHtml) {
// bearer:disable javascript_lang_dangerous_insert_html
domainList.innerHTML = window.sanitizeHtml(domainHtml);
- } else if (window.escapeHtml) {
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
- domainList.innerHTML = domainHtml; // Already escaped individual fields above
} else {
- domainList.textContent = 'Domain data unavailable (security module not loaded)';
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- all dynamic fields use the always-available local escapeHtml helper
+ domainList.innerHTML = domainHtml;
}
} else if (window.safeSetInnerHTML) {
window.safeSetInnerHTML(domainList, '<div style="text-align: center; color: var(--text-secondary); padding: 1rem;">No domain data available</div>', true);
diff --git a/src/local_deep_research/web/static/js/components/history.js b/src/local_deep_research/web/static/js/components/history.js
index e8eedc7137..0f96f2d571 100644
--- a/src/local_deep_research/web/static/js/components/history.js
+++ b/src/local_deep_research/web/static/js/components/history.js
@@ -191,8 +191,15 @@
// Debounced search input
if (searchInput) {
searchInput.addEventListener('input', () => {
+ // Ownership changes at the browser event boundary, not when
+ // the outer debounce eventually renders the new query. A
+ // request for the previous value may settle during that gap.
+ invalidatePendingSearch();
clearTimeout(inputDebounceTimer);
- inputDebounceTimer = setTimeout(handleSearchInput, 250);
+ inputDebounceTimer = setTimeout(
+ () => handleSearchInput(true),
+ 250
+ );
});
}
@@ -307,7 +314,7 @@
}
}
- async function fetchChatSessions({ all = false } = {}) {
+ async function fetchChatSessions({ all = false, throwOnError = false } = {}) {
// Paginate through ALL chat sessions when `all=true` (used by the
// Clear-All path so it actually deletes every session, not just
// the first page). Without pagination, users with >50 sessions
@@ -330,9 +337,19 @@
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
}
});
- if (!response.ok) break;
+ if (!response.ok) {
+ if (throwOnError) {
+ throw new Error(`Chat sessions API error: ${response.status} ${response.statusText}`);
+ }
+ break;
+ }
const data = await response.json();
- if (!data.success || !Array.isArray(data.sessions)) break;
+ if (!data.success || !Array.isArray(data.sessions)) {
+ if (throwOnError) {
+ throw new Error(data.error || data.detail || 'Invalid chat sessions response');
+ }
+ break;
+ }
for (const s of data.sessions) {
collected.push({
id: s.id,
@@ -351,6 +368,7 @@
}
return collected;
} catch (e) {
+ if (throwOnError) throw e;
SafeLogger.warn('Could not fetch chat sessions:', e);
return [];
}
@@ -937,14 +955,33 @@
return result;
}
+ function invalidatePendingSearch() {
+ semanticSearchId++;
+ hybridSearchId++;
+ clearTimeout(inputDebounceTimer);
+ inputDebounceTimer = null;
+ clearTimeout(semanticDebounceTimer);
+ semanticDebounceTimer = null;
+
+ const staleIndicator = document.getElementById('hybrid-loading-indicator');
+ if (staleIndicator) staleIndicator.remove();
+ }
+
/**
* Handle search input — text, semantic, or hybrid depending on mode
+ * @param {boolean} ownershipAlreadyInvalidated - Whether the synchronous
+ * input listener already invalidated older async work.
*/
- function handleSearchInput() {
+ function handleSearchInput(ownershipAlreadyInvalidated = false) {
if (!searchInput) return;
- // Clean up stale hybrid loading indicator on any mode change/re-entry
- const staleIndicator = document.getElementById('hybrid-loading-indicator');
- if (staleIndicator) staleIndicator.remove();
+ // Every accepted input state owns the result surface, including an
+ // empty query and text-only mode. Without invalidating both async
+ // search channels here, a semantic response that was already in
+ // flight could repaint its old query after the user cleared the
+ // search box and restored the full history list.
+ // This remains here for programmatic callers such as mode changes and
+ // post-delete re-renders; input events also invalidate synchronously.
+ if (!ownershipAlreadyInvalidated) invalidatePendingSearch();
const searchTerm = searchInput.value.trim();
if (!searchTerm) {
@@ -958,8 +995,7 @@
renderHistoryItems();
} else if (searchMode === SM.SEMANTIC) {
- clearTimeout(semanticDebounceTimer);
- const currentSemanticId = ++semanticSearchId;
+ const currentSemanticId = semanticSearchId;
semanticDebounceTimer = setTimeout(async () => {
if (!window.HistorySearch ||
typeof window.HistorySearch.semanticSearchHistory !== 'function' ||
@@ -995,6 +1031,11 @@
}
window.HistorySearch.renderSemanticResults(results, searchTerm);
} catch (error) {
+ // A response owned by an older query (or by a mode the
+ // user has already left) must not replace the current
+ // results with a generic failure state.
+ if (currentSemanticId !== semanticSearchId) return;
+ if (searchMode !== SM.SEMANTIC) return;
SafeLogger.error('Semantic search failed:', error);
if (historyContainer) {
historyContainer.innerHTML = `
@@ -1033,10 +1074,9 @@
if (historyContainer) historyContainer.appendChild(loadingDiv);
// 4. Race-condition guard
- const currentSearchId = ++hybridSearchId;
+ const currentSearchId = hybridSearchId;
// 5. Debounced semantic call (separate timer from input debounce)
- clearTimeout(semanticDebounceTimer);
semanticDebounceTimer = setTimeout(async () => {
try {
const results = await window.HistorySearch.semanticSearchHistory(searchTerm);
@@ -1058,6 +1098,10 @@
const tiered = buildTieredResults(textResults, semanticResults, { textIdKey: 'id', semanticIdKey: 'research_id' });
renderMergedResults(tiered);
} catch (error) {
+ // Do not let an older rejected request remove the loading
+ // indicator that belongs to the current hybrid query.
+ if (currentSearchId !== hybridSearchId) return;
+ if (searchMode !== SM.HYBRID) return;
SafeLogger.error('Hybrid semantic search failed:', error);
const indicator = document.getElementById('hybrid-loading-indicator');
if (indicator) indicator.remove();
@@ -1160,19 +1204,39 @@
// we only fetched the first 50, so the user could click "Clear
// All", see success, then reload and find older sessions still
// there because they were never enumerated for deletion.
+ let chatClearFailed = false;
try {
- const chatSessions = await fetchChatSessions({ all: true });
+ const chatSessions = await fetchChatSessions({
+ all: true,
+ throwOnError: true
+ });
const csrfToken = window.api ? window.api.getCsrfToken() : '';
for (const session of chatSessions) {
- await fetch(`/api/chat/sessions/${encodeURIComponent(session.id)}`, {
+ const response = await fetch(`/api/chat/sessions/${encodeURIComponent(session.id)}`, {
method: 'DELETE',
headers: {
...(csrfToken ? { 'X-CSRFToken': csrfToken } : {})
}
});
+ if (!response.ok) {
+ throw new Error(`Chat delete API error: ${response.status} ${response.statusText}`);
+ }
}
} catch (chatErr) {
SafeLogger.warn('Could not clear chat sessions:', chatErr);
+ chatClearFailed = true;
+ }
+
+ if (chatClearFailed) {
+ uiUtils.showError(
+ 'Research history was cleared, but chat sessions could not all be cleared. Please try again.'
+ );
+ // Research history was already cleared and chat deletion may
+ // have succeeded only in part. Re-read both feeds so the page
+ // reflects the durable state instead of claiming everything
+ // disappeared locally.
+ await loadHistoryData();
+ return;
}
// Clear arrays
diff --git a/src/local_deep_research/web/static/js/components/notes_shared.js b/src/local_deep_research/web/static/js/components/notes_shared.js
index 1a97a9c809..70442a2284 100644
--- a/src/local_deep_research/web/static/js/components/notes_shared.js
+++ b/src/local_deep_research/web/static/js/components/notes_shared.js
@@ -53,7 +53,9 @@
});
const data = await response.json().catch(() => ({}));
if (!response.ok || !data.success) {
- throw new Error(data.error || `Server returned ${response.status}`);
+ throw new Error(
+ data.error || data.detail || `Server returned ${response.status}`
+ );
}
return data;
}
diff --git a/src/local_deep_research/web/static/js/components/progress.js b/src/local_deep_research/web/static/js/components/progress.js
index 567b7a395c..4e1a03c048 100644
--- a/src/local_deep_research/web/static/js/components/progress.js
+++ b/src/local_deep_research/web/static/js/components/progress.js
@@ -8,6 +8,8 @@
let pollInterval = null;
let isCompleted = false;
let socketErrorShown = false;
+ let nextProgressUpdateGeneration = 0;
+ let latestAppliedProgressUpdateGeneration = 0;
// Keeps track of whether we've set a specific progress message or just
// a generic one based on the status.
let specificProgressMessage = false;
@@ -227,10 +229,12 @@
}
// Subscribe to research events
+ window.socket.setPollingFallback?.(fallbackToPolling);
window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);
// Handle socket reconnection
window.socket.onReconnect(() => {
+ if (isCompleted || researchCompleted) return;
SafeLogger.log('Socket reconnected, resubscribing to research events');
window.socket.subscribeToResearch(currentResearchId, handleProgressUpdate);
});
@@ -264,6 +268,7 @@
* Fall back to polling for updates
*/
function fallbackToPolling() {
+ if (isCompleted || researchCompleted) return;
SafeLogger.log('Setting up polling fallback for research updates');
if (!pollInterval) {
@@ -276,6 +281,44 @@
}
}
+ /**
+ * Claim an HTTP status snapshot for the progress UI.
+ *
+ * Non-terminal snapshots use latest-applied ownership so a delayed poll
+ * cannot regress a newer socket frame. Terminal state is monotonic for a
+ * research ID, however, so a completed/failed/cancelled HTTP snapshot must
+ * still win when transports deliver it after a newer non-terminal frame.
+ * @param {number} requestGeneration - Generation captured by the request
+ * @param {Object} snapshot - Research status returned by the API
+ * @returns {boolean} Whether the caller owns the progress UI
+ */
+ function claimProgressSnapshot(requestGeneration, snapshot) {
+ if (isCompleted || researchCompleted) return false;
+
+ const hasStatus = (
+ typeof snapshot?.status === 'string' && snapshot.status.trim() !== ''
+ );
+ const hasProgress = (
+ typeof snapshot?.progress === 'number' &&
+ Number.isFinite(snapshot.progress)
+ );
+ if (!hasStatus && !hasProgress) return false;
+
+ const isTerminalSnapshot = ResearchStates.isTerminal(snapshot.status);
+ if (
+ !isTerminalSnapshot &&
+ requestGeneration < latestAppliedProgressUpdateGeneration
+ ) {
+ return false;
+ }
+
+ latestAppliedProgressUpdateGeneration = Math.max(
+ latestAppliedProgressUpdateGeneration,
+ requestGeneration
+ );
+ return true;
+ }
+
/**
* Handle progress update from socket
* @param {Object} data - The progress data
@@ -294,6 +337,21 @@
if (!data) return;
+ // A socket status snapshot is a newer owner than any status request
+ // already in flight. Logger events are also delivered on this channel
+ // as `{log_entry}` only; those must not suppress bootstrap hydration
+ // because they carry no progress/status state of their own.
+ const ownsProgressState = (
+ (typeof data.status === 'string' && data.status.trim() !== '') ||
+ (typeof data.progress === 'number' && Number.isFinite(data.progress))
+ );
+ if (ownsProgressState) {
+ latestAppliedProgressUpdateGeneration = ++nextProgressUpdateGeneration;
+ }
+
+ // Once a terminal state has rendered, ignore late socket frames.
+ if (isCompleted || researchCompleted) return;
+
// Handle agent thinking updates for MCP/ReAct strategy
if (data.phase && (data.phase === 'thought' || data.phase === 'tool_call' ||
data.phase === 'observation' || data.phase === 'error' || data.phase === 'react' ||
@@ -364,6 +422,9 @@
* Check research progress via API
*/
async function checkProgress() {
+ if (isCompleted || researchCompleted) return;
+
+ const requestGeneration = ++nextProgressUpdateGeneration;
try {
if (!window.api || !window.api.getResearchStatus) {
SafeLogger.error('API service not available');
@@ -373,6 +434,22 @@
SafeLogger.log('Checking research progress for ID:', currentResearchId);
const data = await window.api.getResearchStatus(currentResearchId);
+ if (!claimProgressSnapshot(requestGeneration, data)) {
+ if (
+ requestGeneration >= latestAppliedProgressUpdateGeneration &&
+ !isCompleted &&
+ !researchCompleted &&
+ data &&
+ typeof data === 'object'
+ ) {
+ SafeLogger.warn('Invalid research status received from API');
+ if (statusText) {
+ statusText.textContent = 'Error checking research status';
+ }
+ }
+ return;
+ }
+
if (data) {
SafeLogger.log('Got research status update:', data);
@@ -399,6 +476,13 @@
SafeLogger.warn('No data received from API');
}
} catch (error) {
+ if (
+ requestGeneration < latestAppliedProgressUpdateGeneration ||
+ isCompleted ||
+ researchCompleted
+ ) {
+ return;
+ }
SafeLogger.error('Error checking research progress:', error);
if (statusText) {
statusText.textContent = 'Error checking research status';
@@ -619,7 +703,7 @@
if (ResearchStates.isCompleted(data.status)) {
// Show view results button
if (viewResultsButton) {
- viewResultsButton.style.display = 'inline-block';
+ showResultsButton();
URLValidator.safeAssign(viewResultsButton, 'href', URLBuilder.resultsPage(currentResearchId));
}
@@ -700,6 +784,7 @@
* Handle research cancellation
*/
async function handleCancelResearch() {
+ if (isCompleted || researchCompleted) return;
if (!confirm('Are you sure you want to cancel this research?')) {
return;
}
@@ -715,7 +800,45 @@
throw new Error('API service not available');
}
- await window.api.terminateResearch(currentResearchId);
+ const result = await window.api.terminateResearch(currentResearchId);
+
+ // Completion may win while terminate is in flight. A successful
+ // terminate response can also mean the server was already done,
+ // even if its final socket frame never reached this page.
+ if (isCompleted || researchCompleted) return;
+ if (
+ result?.research_status &&
+ ResearchStates.isTerminal(result.research_status) &&
+ !ResearchStates.isCancelled(result.research_status)
+ ) {
+ handleProgressUpdate({
+ research_id: currentResearchId,
+ status: result.research_status,
+ progress: 100,
+ });
+ return;
+ }
+
+ // Cancellation is terminal for this page. Retire every status
+ // request already in flight before updating the DOM so a late
+ // poll or socket frame cannot repaint the cancelled state.
+ isCompleted = true;
+ researchCompleted = true;
+ latestAppliedProgressUpdateGeneration = ++nextProgressUpdateGeneration;
+ if (pollInterval) {
+ clearInterval(pollInterval);
+ pollInterval = null;
+ }
+ if (typeof window.socket?.unsubscribeFromResearch === 'function') {
+ try {
+ window.socket.unsubscribeFromResearch(currentResearchId);
+ } catch (unsubscribeError) {
+ SafeLogger.warn(
+ 'Research was cancelled, but socket cleanup failed:',
+ unsubscribeError
+ );
+ }
+ }
// Update status manually (in case socket fails)
if (statusText) {
@@ -743,6 +866,7 @@
}
} catch (error) {
+ if (isCompleted || researchCompleted) return;
SafeLogger.error('Error cancelling research:', error);
// Re-enable cancel button
@@ -878,7 +1002,9 @@
setTimeout(() => {
notificationEl.classList.remove('show');
setTimeout(() => {
- notificationContainer.removeChild(notificationEl);
+ if (notificationContainer.contains(notificationEl)) {
+ notificationContainer.removeChild(notificationEl);
+ }
}, 300); // Wait for fade animation
}, duration);
}
@@ -907,9 +1033,22 @@
* Get initial research status from API
*/
async function getInitialStatus() {
+ const requestGeneration = ++nextProgressUpdateGeneration;
try {
const status = await window.api.getResearchStatus(currentResearchId);
+ if (!claimProgressSnapshot(requestGeneration, status)) {
+ if (
+ requestGeneration >= latestAppliedProgressUpdateGeneration &&
+ !isCompleted &&
+ !researchCompleted
+ ) {
+ SafeLogger.warn('Invalid initial research status received from API');
+ setErrorState('Error loading research status. Please refresh the page to try again.');
+ }
+ return;
+ }
+
// Process status
if (status) {
// If complete, show complete UI
@@ -920,9 +1059,22 @@
else if (ResearchStates.isFailed(status.status)) {
handleResearchError({
research_id: currentResearchId,
- error: status.message || 'Unknown error'
+ // The FastAPI status route exposes persisted failure
+ // details under metadata.error_info; socket frames may
+ // still supply a top-level message/error.
+ error: status.metadata?.error_info?.message
+ || status.message
+ || status.error
+ || 'Unknown error'
});
}
+ // FastAPI persists user-terminated research as "suspended"
+ // (and older callers may still report "cancelled"). Render
+ // the final snapshot before retiring every later transport.
+ else if (ResearchStates.isCancelled(status.status)) {
+ updateProgressUI(status);
+ handleResearchCompletion(status);
+ }
// If queued, show queue status and set up polling
else if (status.status === window.RESEARCH_STATUS.QUEUED) {
updateProgressUI(status);
@@ -936,6 +1088,13 @@
}
}
} catch (error) {
+ if (
+ requestGeneration < latestAppliedProgressUpdateGeneration ||
+ isCompleted ||
+ researchCompleted
+ ) {
+ return;
+ }
SafeLogger.error('Error getting initial status:', error);
setErrorState('Error loading research status. Please refresh the page to try again.');
}
@@ -953,26 +1112,26 @@
return;
}
- // Update UI
- setProgressValue(100);
- setStatus(window.RESEARCH_STATUS.COMPLETED);
- setCurrentTask('Research completed successfully');
-
- // Hide cancel button
- if (cancelButton) {
- cancelButton.style.display = 'none';
- }
-
- // Show results button
- showResultsButton();
-
- // Show notification if enabled
- showNotification('Research Complete', 'Your research has been completed successfully.');
+ // Hydrating a page whose research already completed must take the
+ // same terminal path as a live HTTP/socket completion. The former
+ // bespoke UI updates exposed the result button without assigning its
+ // href (the template anchor has none), skipped context-overflow
+ // recovery, and left the document title in its in-progress state.
+ const completionData = {
+ ...data,
+ status: window.RESEARCH_STATUS.COMPLETED,
+ progress: 100,
+ current_task: data.current_task || 'Research completed successfully'
+ };
+ updateProgressUI(completionData);
+ handleResearchCompletion(completionData);
// Update favicon
updateFavicon(100);
- // Set flag
+ // Keep the secondary terminal flag in sync with the shared completion
+ // path. `handleResearchCompletion` already owns isCompleted and poll
+ // cleanup.
researchCompleted = true;
}
@@ -988,6 +1147,12 @@
return;
}
+ isCompleted = true;
+ if (pollInterval) {
+ clearInterval(pollInterval);
+ pollInterval = null;
+ }
+
// Update UI to error state
setProgressValue(100);
setStatus(window.RESEARCH_STATUS.ERROR);
diff --git a/src/local_deep_research/web/static/js/components/research.js b/src/local_deep_research/web/static/js/components/research.js
index a36530d776..fd3605c8ee 100644
--- a/src/local_deep_research/web/static/js/components/research.js
+++ b/src/local_deep_research/web/static/js/components/research.js
@@ -21,6 +21,31 @@
// Form validator instance
let researchValidator = null;
+ // The active submit owns the button and overlay until its request settles.
+ // Keyboard shortcuts call the handler directly (and textarea key events
+ // also bubble to the document shortcut), so disabling the button alone
+ // cannot prevent duplicate requests.
+ let activeResearchSubmit = null;
+
+ // Preserve user-event order for writes to the same setting. Different
+ // settings keep independent promise tails, so they can still save in
+ // parallel. The tracked tail always settles so one failed request cannot
+ // prevent the next value from being written.
+ const pendingResearchSettingSaves = new Map();
+
+ function enqueueResearchSettingSave(settingKey, startSave) {
+ const priorSave = pendingResearchSettingSaves.get(settingKey)
+ || Promise.resolve();
+ const request = priorSave.then(startSave, startSave);
+ const trackedRequest = request.catch(() => undefined).finally(() => {
+ if (pendingResearchSettingSaves.get(settingKey) === trackedRequest) {
+ pendingResearchSettingSaves.delete(settingKey);
+ }
+ });
+
+ pendingResearchSettingSaves.set(settingKey, trackedRequest);
+ return request;
+ }
// DOM Elements
let form = null;
@@ -387,8 +412,13 @@
searchEngineInput.value = value;
}
- // Only save if not initializing
- if (!isInitializing) {
+ // custom_dropdown dispatches the hidden input's
+ // change event immediately after this callback;
+ // that listener below is the single owner of the
+ // settings write. Only fall back to a direct save
+ // for an incomplete embedding without the hidden
+ // form control.
+ if (!isInitializing && !document.getElementById('search_engine_hidden')) {
saveSearchEngineSettings(value);
}
},
@@ -564,8 +594,10 @@
seHidden.value = value;
}
- // Save search engine selection to settings - only if not initializing
- if (!isInitializing) {
+ // The dropdown dispatches change on the hidden input after
+ // this callback; let that listener own the write so a
+ // single selection cannot race duplicate PUTs.
+ if (!isInitializing && !seHidden) {
saveSearchEngineSettings(value);
}
},
@@ -1720,6 +1752,9 @@
if (openrouterApiKeyContainer) {
openrouterApiKeyContainer.style.display = activeProvider === 'OPENROUTER' ? 'block' : 'none';
}
+ if (orcarouterApiKeyContainer) {
+ orcarouterApiKeyContainer.style.display = activeProvider === 'ORCAROUTER' ? 'block' : 'none';
+ }
if (atlascloudApiKeyContainer) {
atlascloudApiKeyContainer.style.display = activeProvider === 'ATLASCLOUD' ? 'block' : 'none';
}
@@ -1784,70 +1819,80 @@
contextWindowInput.disabled = !contextWindowSetting.editable;
}
- // Update API key inputs from settings
+ // The FastAPI settings endpoint deliberately returns
+ // "[REDACTED]" for stored secrets. Keep password controls
+ // blank instead of rendering that transport sentinel (or any
+ // accidentally unredacted value); the editable flag still
+ // tells the user whether a replacement may be submitted.
const openaiApiKeySetting = data.settings['llm.openai.api_key'];
if (openaiApiKeySetting && openaiApiKeyInput) {
- openaiApiKeyInput.value = openaiApiKeySetting.value || '';
+ openaiApiKeyInput.value = '';
openaiApiKeyInput.disabled = !openaiApiKeySetting.editable;
}
const anthropicApiKeySetting = data.settings['llm.anthropic.api_key'];
if (anthropicApiKeySetting && anthropicApiKeyInput) {
- anthropicApiKeyInput.value = anthropicApiKeySetting.value || '';
+ anthropicApiKeyInput.value = '';
anthropicApiKeyInput.disabled = !anthropicApiKeySetting.editable;
}
const googleApiKeySetting = data.settings['llm.google.api_key'];
if (googleApiKeySetting && googleApiKeyInput) {
- googleApiKeyInput.value = googleApiKeySetting.value || '';
+ googleApiKeyInput.value = '';
googleApiKeyInput.disabled = !googleApiKeySetting.editable;
}
const openrouterApiKeySetting = data.settings['llm.openrouter.api_key'];
if (openrouterApiKeySetting && openrouterApiKeyInput) {
- openrouterApiKeyInput.value = openrouterApiKeySetting.value || '';
+ openrouterApiKeyInput.value = '';
openrouterApiKeyInput.disabled = !openrouterApiKeySetting.editable;
}
+ const orcarouterApiKeySetting = data.settings['llm.orcarouter.api_key'];
+ if (orcarouterApiKeySetting && orcarouterApiKeyInput) {
+ orcarouterApiKeyInput.value = '';
+ orcarouterApiKeyInput.disabled = !orcarouterApiKeySetting.editable;
+ }
+
const atlascloudApiKeySetting = data.settings['llm.atlascloud.api_key'];
if (atlascloudApiKeySetting && atlascloudApiKeyInput) {
- atlascloudApiKeyInput.value = atlascloudApiKeySetting.value || '';
+ atlascloudApiKeyInput.value = '';
atlascloudApiKeyInput.disabled = !atlascloudApiKeySetting.editable;
}
const xaiApiKeySetting = data.settings['llm.xai.api_key'];
if (xaiApiKeySetting && xaiApiKeyInput) {
- xaiApiKeyInput.value = xaiApiKeySetting.value || '';
+ xaiApiKeyInput.value = '';
xaiApiKeyInput.disabled = !xaiApiKeySetting.editable;
}
const ionosApiKeySetting = data.settings['llm.ionos.api_key'];
if (ionosApiKeySetting && ionosApiKeyInput) {
- ionosApiKeyInput.value = ionosApiKeySetting.value || '';
+ ionosApiKeyInput.value = '';
ionosApiKeyInput.disabled = !ionosApiKeySetting.editable;
}
const openaiEndpointApiKeySetting = data.settings['llm.openai_endpoint.api_key'];
if (openaiEndpointApiKeySetting && openaiEndpointApiKeyInput) {
- openaiEndpointApiKeyInput.value = openaiEndpointApiKeySetting.value || '';
+ openaiEndpointApiKeyInput.value = '';
openaiEndpointApiKeyInput.disabled = !openaiEndpointApiKeySetting.editable;
}
const anthropicEndpointApiKeySetting = data.settings['llm.anthropic_endpoint.api_key'];
if (anthropicEndpointApiKeySetting && anthropicEndpointApiKeyInput) {
- anthropicEndpointApiKeyInput.value = anthropicEndpointApiKeySetting.value || '';
+ anthropicEndpointApiKeyInput.value = '';
anthropicEndpointApiKeyInput.disabled = !anthropicEndpointApiKeySetting.editable;
}
const ollamaApiKeySetting = data.settings['llm.ollama.api_key'];
if (ollamaApiKeySetting && ollamaApiKeyInput) {
- ollamaApiKeyInput.value = ollamaApiKeySetting.value || '';
+ ollamaApiKeyInput.value = '';
ollamaApiKeyInput.disabled = !ollamaApiKeySetting.editable;
}
const lmstudioApiKeySetting = data.settings['llm.lmstudio.api_key'];
if (lmstudioApiKeySetting && lmstudioApiKeyInput) {
- lmstudioApiKeyInput.value = lmstudioApiKeySetting.value || '';
+ lmstudioApiKeyInput.value = '';
lmstudioApiKeyInput.disabled = !lmstudioApiKeySetting.editable;
}
@@ -2276,14 +2321,14 @@
return (sel.value || '').toLowerCase().trim();
}
- // The user's currently-selected primary engine. Prefer the in-memory
- // selection (the most recent value the form has); fall back to
- // the hidden input for the initial-load case.
+ // The user's currently-selected primary engine. The hidden input is the
+ // value that form submission actually sends, so it is authoritative if a
+ // hydration/reconciliation path ever leaves it out of sync with the
+ // in-memory dropdown selection.
function getCurrentPrimaryForDropdown() {
- if (selectedSearchEngineValue) return selectedSearchEngineValue;
const hidden = document.getElementById('search_engine_hidden');
if (hidden && hidden.value) return hidden.value;
- return '';
+ return selectedSearchEngineValue || '';
}
// Build the egress-aware URL for GET /api/available-search-engines.
@@ -2855,7 +2900,7 @@
});
// Save to the database using the settings API
- fetch(URLBuilder.updateSetting('llm.model'), {
+ return enqueueResearchSettingSave('llm.model', () => fetch(URLBuilder.updateSetting('llm.model'), {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -2866,7 +2911,9 @@
.then(async response => {
const data = await response.json();
if (!response.ok) {
- throw new Error(data.error || data.message || `HTTP ${response.status}`);
+ throw new Error(
+ data.error || data.detail || data.message || `HTTP ${response.status}`
+ );
}
return data;
})
@@ -2877,7 +2924,7 @@
if (window.ui && window.ui.showMessage) {
window.ui.showMessage(`Model updated to: ${modelValue}`, 'success', 2000);
}
- })
+ }))
.catch(error => {
SafeLogger.error('Error saving model setting to database:', error);
@@ -2899,7 +2946,7 @@
});
// Save to the database using the settings API
- fetch(URLS.SETTINGS_API.SEARCH_TOOL, {
+ return enqueueResearchSettingSave('search.tool', () => fetch(URLS.SETTINGS_API.SEARCH_TOOL, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -2907,7 +2954,15 @@
},
body: JSON.stringify({ value: engineValue })
})
- .then(response => response.json())
+ .then(async response => {
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ data.error || data.detail || data.message || `HTTP ${response.status}`
+ );
+ }
+ return data;
+ })
.then(data => {
SafeLogger.log('Search engine setting saved to database:', data);
@@ -2915,7 +2970,7 @@
if (window.ui && window.ui.showMessage) {
window.ui.showMessage(`Search engine updated to: ${engineValue}`, 'success', 2000);
}
- })
+ }))
.catch(error => {
SafeLogger.error('Error saving search engine setting to database:', error);
@@ -2939,7 +2994,15 @@
},
body: JSON.stringify({ engine_id: engineId })
})
- .then(response => response.json())
+ .then(async response => {
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ data.error || data.detail || data.message || `HTTP ${response.status}`
+ );
+ }
+ return data;
+ })
.then(data => {
SafeLogger.log('Favorite toggled:', data);
@@ -3005,7 +3068,7 @@
});
// Save to the database using the settings API
- fetch(URLS.SETTINGS_API.LLM_PROVIDER, {
+ return enqueueResearchSettingSave('llm.provider', () => fetch(URLS.SETTINGS_API.LLM_PROVIDER, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -3013,7 +3076,15 @@
},
body: JSON.stringify({ value: providerValue.toLowerCase() })
})
- .then(response => response.json())
+ .then(async response => {
+ const data = await response.json();
+ if (!response.ok) {
+ throw new Error(
+ data.error || data.detail || data.message || `HTTP ${response.status}`
+ );
+ }
+ return data;
+ })
.then(data => {
SafeLogger.log('Provider setting saved to database:', data);
@@ -3029,7 +3100,7 @@
if (window.ui && window.ui.showMessage) {
window.ui.showMessage(`Provider updated to: ${providerValue}`, 'success', 2000);
}
- })
+ }))
.catch(error => {
SafeLogger.error('Error saving provider setting to database:', error);
@@ -3138,7 +3209,7 @@
}
function saveSearchSetting(settingKey, value, onFailure = null, onSuccess = null) {
- return fetch(`/settings/api/${settingKey}`, {
+ return enqueueResearchSettingSave(settingKey, () => fetch(`/settings/api/${settingKey}`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
@@ -3149,7 +3220,10 @@
.then(async response => {
const data = await response.json();
if (!response.ok) {
- throw new Error(data.error || `Request failed (${response.status})`);
+ throw new Error(
+ data.error || data.detail || data.message ||
+ `Request failed (${response.status})`
+ );
}
return data;
})
@@ -3162,7 +3236,7 @@
if (window.ui && window.ui.showMessage) {
window.ui.showMessage(`${settingKey.split(".").pop()} updated to: ${value}`, "success", 2000);
}
- })
+ }))
.catch(error => {
SafeLogger.error(`Error saving search setting ${settingKey} to database:`, error);
if (typeof onFailure === "function") onFailure(error);
@@ -3175,6 +3249,11 @@
// Research form submission handler
function handleResearchSubmit(event) {
event.preventDefault();
+
+ if (activeResearchSubmit !== null) {
+ return;
+ }
+
SafeLogger.log('Research form submitted');
// Clear any alerts this submit handler previously produced — both
@@ -3232,6 +3311,9 @@
researchValidator.clearErrors();
}
+ const submitOwnership = {};
+ activeResearchSubmit = submitOwnership;
+
// Disable the submit button to prevent multiple submissions
startBtn.disabled = true;
@@ -3258,15 +3340,23 @@
`;
document.body.appendChild(loadingOverlay);
+ const finishResearchSubmit = () => {
+ if (activeResearchSubmit !== submitOwnership) {
+ return;
+ }
+
+ activeResearchSubmit = null;
+ startBtn.disabled = false;
+ window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
+ loadingOverlay.remove();
+ };
+
// Handle Chat Mode - create session and redirect
// (mode was resolved up front, before the validation guards.)
if (mode === 'chat') {
if (!query) {
showAlert('Please enter a research query.', 'error');
- startBtn.disabled = false;
- window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
- const overlay = document.querySelector('.ldr-loading-overlay');
- if (overlay) overlay.remove();
+ finishResearchSubmit();
return;
}
@@ -3279,27 +3369,35 @@
},
body: JSON.stringify({ initial_query: query })
})
- .then(response => {
+ .then(async response => {
+ const data = await response.json();
if (!response.ok) {
- throw new Error('Failed to create chat session');
+ const message = nonBlankString(data && data.detail)
+ ? data.detail
+ : nonBlankString(data && data.error)
+ ? data.error
+ : nonBlankString(data && data.message)
+ ? data.message
+ : 'Failed to create chat session';
+ throw new Error(message);
}
- return response.json();
+ return data;
})
.then(data => {
if (data.success && data.session_id) {
window.location.href = `/chat/${data.session_id}?q=${encodeURIComponent(query)}`;
} else {
- throw new Error(data.error || 'Failed to create chat session');
+ throw new Error(
+ data.error || data.detail || data.message ||
+ 'Failed to create chat session'
+ );
}
})
.catch(error => {
SafeLogger.error('Error creating chat session:', error);
showAlert('Failed to start chat: ' + error.message, 'error');
- startBtn.disabled = false;
- window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
- const overlay = document.querySelector('.ldr-loading-overlay');
- if (overlay) overlay.remove();
- });
+ })
+ .finally(finishResearchSubmit);
return;
}
@@ -3374,10 +3472,23 @@
},
body: JSON.stringify(formData)
})
- .then(response => response.json())
- .then(data => {
+ .then(async response => ({
+ response,
+ data: await response.json()
+ }))
+ .then(({ response, data }) => {
try {
- if (data && (data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED)) {
+ const researchId = nonBlankString(data && data.research_id)
+ ? data.research_id.trim()
+ : null;
+ const hasSuccessEnvelope = (
+ response.ok &&
+ data &&
+ (data.status === 'success' || data.status === window.RESEARCH_STATUS.QUEUED) &&
+ researchId !== null
+ );
+
+ if (hasSuccessEnvelope) {
SafeLogger.log('Research started:', data);
if (data.status === window.RESEARCH_STATUS.QUEUED) {
@@ -3390,7 +3501,7 @@
// Redirect to the progress page
// URLBuilder produces /progress/{uuid}
// bearer:disable javascript_lang_open_redirect
- window.location.href = URLBuilder.progressPage(data.research_id);
+ window.location.href = URLBuilder.progressPage(researchId);
} else {
// Show error message — anchor near submit + flag the
// offending field (if the server told us which one).
@@ -3408,7 +3519,9 @@
// happens" symptom).
const message = nonBlankString(data && data.message)
? data.message
- : 'Failed to start research.';
+ : nonBlankString(data && data.detail)
+ ? data.detail
+ : 'Failed to start research.';
showAlert(message, 'error');
if (typeof showFormError === 'function') {
showFormError(message, nonBlankString(data && data.field)
@@ -3421,10 +3534,7 @@
// missing status, etc.) would otherwise throw partway
// through. The user must never be left with a permanently
// disabled submit button and a stuck overlay.
- startBtn.disabled = false;
- window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
- const overlay = document.querySelector('.ldr-loading-overlay');
- if (overlay) overlay.remove();
+ finishResearchSubmit();
}
})
.catch(error => {
@@ -3438,14 +3548,7 @@
showFormError(message, null);
}
- // Re-enable the button
- startBtn.disabled = false;
- // Use centralized security utilities for button reset
- window.safeUpdateButton(startBtn, 'fa-rocket', ' Start Research');
-
- // Remove loading overlay
- const overlay = document.querySelector('.ldr-loading-overlay');
- if (overlay) overlay.remove();
+ finishResearchSubmit();
});
}
diff --git a/src/local_deep_research/web/static/js/components/research_notes.js b/src/local_deep_research/web/static/js/components/research_notes.js
index 7ef841a7f2..5f3edcbe02 100644
--- a/src/local_deep_research/web/static/js/components/research_notes.js
+++ b/src/local_deep_research/web/static/js/components/research_notes.js
@@ -205,8 +205,17 @@
if (window.__VITEST_TEST__) {
window.__researchNotesTest = {
+ initResearchNotes,
loadResearchNotes,
- setResearchId: (value) => { researchId = value; }
+ addNoteForResearch,
+ saveReportAsNote,
+ clipSelectionToNote,
+ setResearchId: (value) => { researchId = value; },
+ reset: () => {
+ researchId = null;
+ loadGeneration = 0;
+ saveAsNoteInProgress = false;
+ }
};
}
})();
diff --git a/src/local_deep_research/web/static/js/components/results.js b/src/local_deep_research/web/static/js/components/results.js
index 8263aef1a4..66d5b8ffe3 100644
--- a/src/local_deep_research/web/static/js/components/results.js
+++ b/src/local_deep_research/web/static/js/components/results.js
@@ -175,7 +175,7 @@
}
// Render the content
- if (responseData.content && typeof responseData.content === 'string') {
+ if (typeof responseData.content === 'string') {
SafeLogger.log('Rendering content from API response');
renderResults(responseData.content);
} else {
@@ -283,7 +283,10 @@
}
// Format mode using available formatter
- if (window.formatting && typeof window.formatting.formatMode === 'function') {
+ if (
+ mode && window.formatting &&
+ typeof window.formatting.formatMode === 'function'
+ ) {
mode = window.formatting.formatMode(mode);
SafeLogger.log('Formatted mode:', mode);
}
@@ -298,23 +301,27 @@
* @param {Object} data - Research data to extract content from
*/
function findAndRenderContent(data) {
- if (data.content && typeof data.content === 'string') {
+ if (typeof data.content === 'string') {
// Direct content property (newer format)
SafeLogger.log('Rendering from data.content');
renderResults(data.content);
- } else if (data.research && data.research.content) {
+ } else if (
+ data.research && typeof data.research.content === 'string'
+ ) {
// Nested content in research object (older format)
SafeLogger.log('Rendering from data.research.content');
renderResults(data.research.content);
- } else if (data.report && typeof data.report === 'string') {
+ } else if (typeof data.report === 'string') {
// Report format
SafeLogger.log('Rendering from data.report');
renderResults(data.report);
- } else if (data.results && data.results.content) {
+ } else if (
+ data.results && typeof data.results.content === 'string'
+ ) {
// Results with content field
SafeLogger.log('Rendering from data.results.content');
renderResults(data.results.content);
- } else if (data.results && typeof data.results === 'string') {
+ } else if (typeof data.results === 'string') {
// Results as direct string
SafeLogger.log('Rendering from data.results string');
renderResults(data.results);
@@ -328,7 +335,7 @@
let foundContent = false;
for (const prop of contentProps) {
- if (data[prop] && typeof data[prop] === 'string') {
+ if (typeof data[prop] === 'string') {
SafeLogger.log(`Rendering from data.${prop}`);
renderResults(data[prop]);
foundContent = true;
@@ -355,7 +362,7 @@
SafeLogger.log('Available top-level keys:', Object.keys(data));
// Direct extraction from content
- if (data.content && typeof data.content === 'string') {
+ if (typeof data.content === 'string') {
SafeLogger.log('Attempting to extract metadata from content');
// Extract the query from content first line or header
@@ -719,7 +726,7 @@
// First check direct properties
for (const prop of contentProps) {
- if (researchData[prop] && typeof researchData[prop] === 'string') {
+ if (typeof researchData[prop] === 'string') {
markdownContent = researchData[prop];
SafeLogger.log(`Using ${prop} for markdown content`);
found = true;
@@ -730,7 +737,7 @@
// Then check nested properties
if (!found && researchData.research) {
for (const prop of contentProps) {
- if (researchData.research[prop] && typeof researchData.research[prop] === 'string') {
+ if (typeof researchData.research[prop] === 'string') {
markdownContent = researchData.research[prop];
SafeLogger.log(`Using research.${prop} for markdown content`);
found = true;
@@ -744,9 +751,10 @@
if (typeof researchData.results === 'string') {
markdownContent = researchData.results;
SafeLogger.log('Using results string for markdown content');
+ found = true;
} else {
for (const prop of contentProps) {
- if (researchData.results[prop] && typeof researchData.results[prop] === 'string') {
+ if (typeof researchData.results[prop] === 'string') {
markdownContent = researchData.results[prop];
SafeLogger.log(`Using results.${prop} for markdown content`);
found = true;
@@ -757,7 +765,7 @@
}
// Last resort
- if (!markdownContent) {
+ if (!found) {
SafeLogger.warn('Could not extract markdown content, using JSON');
markdownContent = "```json\n" + JSON.stringify(researchData, null, 2) + "\n```";
}
@@ -769,13 +777,18 @@
// Create blob and trigger download
const blob = new Blob([fullMarkdown], { type: 'text/markdown' });
const link = document.createElement('a');
- URLValidator.safeAssign(link, 'href', URL.createObjectURL(blob));
+ const objectUrl = URL.createObjectURL(blob);
+ URLValidator.safeAssign(link, 'href', objectUrl);
link.download = `research_${researchId}.md`;
// Trigger download
document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
+ try {
+ link.click();
+ } finally {
+ document.body.removeChild(link);
+ URL.revokeObjectURL(objectUrl);
+ }
} catch (error) {
SafeLogger.error('Error exporting markdown:', error);
@@ -811,7 +824,10 @@
if (!response.ok) {
const error = await response.json();
- throw new Error(error.error || `Failed to export to ${formatName}`);
+ throw new Error(
+ error.error || error.detail ||
+ `Failed to export to ${formatName}`
+ );
}
// Get the blob from response
@@ -824,13 +840,18 @@
// Create download link
const link = document.createElement('a');
- URLValidator.safeAssign(link, 'href', URL.createObjectURL(blob));
+ const objectUrl = URL.createObjectURL(blob);
+ URLValidator.safeAssign(link, 'href', objectUrl);
link.download = `research_${researchId}.${extension}`;
// Trigger download
document.body.appendChild(link);
- link.click();
- document.body.removeChild(link);
+ try {
+ link.click();
+ } finally {
+ document.body.removeChild(link);
+ URL.revokeObjectURL(objectUrl);
+ }
SafeLogger.log(`Successfully exported to ${formatName}`);
@@ -992,9 +1013,11 @@
const toggleBtn = document.getElementById('ldr-detailed-rating-toggle');
const detailPanel = document.getElementById('ldr-detailed-rating');
let currentRating = 0;
+ let ratingSelectionGeneration = 0;
+ let ratingSaveTail = null;
// Load existing rating
- loadExistingRating();
+ loadExistingRating(ratingSelectionGeneration);
// Add hover effects
stars.forEach((star, index) => {
@@ -1004,6 +1027,7 @@
star.addEventListener('click', () => {
const rating = index + 1;
+ ratingSelectionGeneration += 1;
setRating(rating);
saveRating(rating);
@@ -1061,12 +1085,15 @@
});
}
- async function loadExistingRating() {
+ async function loadExistingRating(loadGeneration) {
try {
const response = await fetch(`/metrics/api/ratings/${researchId}`);
if (response.ok) {
const data = await response.json();
- if (data.rating) {
+ if (
+ data.rating &&
+ loadGeneration === ratingSelectionGeneration
+ ) {
setRating(data.rating);
if (toggleBtn) toggleBtn.style.display = 'inline';
}
@@ -1076,7 +1103,34 @@
}
}
- async function saveRating(rating) {
+ function saveRating(rating) {
+ const payload = { rating };
+
+ // Snapshot optional detail fields at click time; a later click may
+ // change them while this save is waiting behind an older request.
+ if (detailPanel && detailPanel.style.display !== 'none') {
+ document.querySelectorAll('.ldr-dimension-slider').forEach(slider => {
+ if (slider.dataset.touched === 'true') {
+ payload[slider.dataset.dimension] = parseInt(slider.value, 10);
+ }
+ });
+ const feedback = document.getElementById('ldr-rating-feedback');
+ if (feedback && feedback.value.trim()) {
+ payload.feedback = feedback.value.trim();
+ }
+ }
+
+ const runSave = () => persistRating(payload);
+ const queuedSave = ratingSaveTail
+ ? ratingSaveTail.then(runSave, runSave)
+ : runSave();
+ ratingSaveTail = queuedSave;
+ queuedSave.finally(() => {
+ if (ratingSaveTail === queuedSave) ratingSaveTail = null;
+ });
+ }
+
+ async function persistRating(payload) {
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
@@ -1088,23 +1142,6 @@
headers['X-CSRFToken'] = csrfToken;
}
- const payload = { rating };
-
- // Include sub-dimensions only if the panel is open AND the user
- // moved the slider (default is 3; untouched sliders are skipped so
- // they don't fabricate dimension data).
- if (detailPanel && detailPanel.style.display !== 'none') {
- document.querySelectorAll('.ldr-dimension-slider').forEach(slider => {
- if (slider.dataset.touched === 'true') {
- payload[slider.dataset.dimension] = parseInt(slider.value, 10);
- }
- });
- const feedback = document.getElementById('ldr-rating-feedback');
- if (feedback && feedback.value.trim()) {
- payload.feedback = feedback.value.trim();
- }
- }
-
const response = await fetch(`/metrics/api/ratings/${researchId}`, {
method: 'POST',
headers,
diff --git a/src/local_deep_research/web/static/js/components/save_to_collection.js b/src/local_deep_research/web/static/js/components/save_to_collection.js
index 7bf1ef62c5..a4986cbb80 100644
--- a/src/local_deep_research/web/static/js/components/save_to_collection.js
+++ b/src/local_deep_research/web/static/js/components/save_to_collection.js
@@ -71,13 +71,15 @@
async function loadCollections() {
try {
const response = await fetch(URLS.LIBRARY_API.COLLECTIONS);
+ const data = await response.json().catch(() => ({}));
if (!response.ok) {
- throw new Error(`Server returned ${response.status}`);
+ throw new Error(
+ data.detail || data.error || `Server returned ${response.status}`
+ );
}
- const data = await response.json();
if (!data.success) {
- throw new Error(data.error || 'Failed to load collections');
+ throw new Error(data.error || data.detail || 'Failed to load collections');
}
renderCollections(data.collections);
@@ -201,13 +203,15 @@
body: JSON.stringify({ collection_id: collectionId })
});
+ const data = await response.json().catch(() => ({}));
if (!response.ok) {
- throw new Error(`Server returned ${response.status}`);
+ throw new Error(
+ data.detail || data.error || `Server returned ${response.status}`
+ );
}
- const data = await response.json();
if (!data.success) {
- throw new Error(data.error || 'Failed to save to collection');
+ throw new Error(data.error || data.detail || 'Failed to save to collection');
}
// Show success message
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 6f6bfb6bef..24b48e19c0 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -69,6 +69,10 @@
// Model and search engine dropdown variables
let modelOptions = [];
let searchEngineOptions = [];
+ let nextModelProvidersRequestGeneration = 0;
+ let latestModelProvidersRequest = null;
+ let nextSearchEnginesRequestGeneration = 0;
+ let latestSearchEnginesRequest = null;
// Provider options surfaced by the backend auto-discovery endpoint
// (/settings/api/available-models). Preferred over the static fallback
// lists below so the provider dropdown stays in sync with the registry and
@@ -78,7 +82,17 @@
// Store save timers for each setting key
let saveTimers = {};
let pendingSaveData = {};
- let lastSettingsUpdateTimestamp = 0;
+ let nextSettingsSaveGeneration = 0;
+ let latestUnscopedSettingsSaveGeneration = 0;
+ const latestSettingsSaveGenerationByKey = new Map();
+ const latestSettingsSaveBySource = new WeakMap();
+ // Each entry owns the write slot for one or more setting keys until its
+ // request has fully settled. Response generations protect browser state,
+ // but they cannot stop two server transactions from committing in the
+ // opposite order. Queue only requests whose key sets overlap; unrelated
+ // settings can still save concurrently.
+ const pendingSettingsSaveByKey = new Map();
+ let settingsResetInProgress = false;
/**
* Fallback HTML escape function (used if xss-protection.js fails to load).
@@ -302,6 +316,11 @@
// Skip if this is a button or submit input
if (input.type === 'button' || input.type === 'submit') return;
+ // Expanded JSON controls have parent-aware handlers below. Wiring
+ // the generic handler too would submit a synthetic child key such
+ // as report.options_limit in addition to report.options.
+ if (input.classList.contains('ldr-json-property-control')) return;
+
// Skip if this input already has auto-save handlers attached
// (prevents duplicate listeners when initAutoSaveHandlers is called multiple times)
if (input.hasAttribute('data-autosave-initialized')) return;
@@ -401,15 +420,22 @@
}
});
- // If the raw JSON editor is visible, set up its event handlers
- if (rawConfigEditor) {
- rawConfigEditor.addEventListener('input', handleRawJsonInput);
- rawConfigEditor.addEventListener('blur', function(e) {
- if (rawConfigEditor.getAttribute('data-modified') === 'true') {
- handleRawJsonInput(e, true); // Force save on blur
- }
- });
- }
+ initRawConfigHandlers();
+ }
+
+ function initRawConfigHandlers() {
+ if (
+ !rawConfigEditor ||
+ rawConfigEditor.hasAttribute('data-raw-config-initialized')
+ ) return;
+
+ rawConfigEditor.setAttribute('data-raw-config-initialized', 'true');
+ rawConfigEditor.addEventListener('input', handleRawJsonInput);
+ rawConfigEditor.addEventListener('blur', function(e) {
+ if (rawConfigEditor.getAttribute('data-modified') === 'true') {
+ handleRawJsonInput(e, true); // Force save on blur
+ }
+ });
}
/**
@@ -519,7 +545,9 @@
e.key === 'Enter' &&
!e.shiftKey &&
value === '';
- const hasChanged = !areValuesEqual(value, originalValue) || isExplicitClear;
+ // A reversal still needs saving if an earlier value can commit later.
+ const hasChanged = pendingSettingsSaveByKey.has(key) ||
+ !areValuesEqual(value, originalValue) || isExplicitClear;
if (hasChanged) {
// Mark parent item as modified
@@ -551,6 +579,10 @@
function handleRawJsonInput(e) {
const input = e.target;
+ if (e.type === 'input') {
+ input.setAttribute('data-modified', 'true');
+ }
+
try {
// Try to parse the JSON
JSON.parse(input.value);
@@ -672,7 +704,12 @@
function initExpandedJsonControls() {
// Find all JSON property controls
document.querySelectorAll('.ldr-json-property-control').forEach(control => {
- if (control.hasAttribute('data-json-expanded-initialized')) return;
+ // initAutoSaveHandlers owns dashboard controls and supplies the
+ // blur/Enter force-save behavior. Do not add a second listener set.
+ if (
+ control.hasAttribute('data-json-control-initialized')
+ || control.hasAttribute('data-json-expanded-initialized')
+ ) return;
control.setAttribute('data-json-expanded-initialized', 'true');
// When the control changes, update the hidden JSON field
control.addEventListener('change', function() {
@@ -686,6 +723,8 @@
});
}
});
+
+ initCheckboxWrappers();
}
/**
@@ -743,8 +782,24 @@
}
}
- // Check if there's actually a change before saving
- const hasChanged = !areObjectsEqual(jsonData, originalJson);
+ // Compare against the last server-owned value, not the hidden field we
+ // update live below. Otherwise an input event makes a later blur look
+ // unchanged and number/text edits never persist their parent object.
+ let savedJson = originalJson;
+ if (Object.hasOwn(originalSettings, parentKey)) {
+ savedJson = originalSettings[parentKey];
+ if (typeof savedJson === 'string') {
+ try {
+ savedJson = JSON.parse(savedJson);
+ } catch {
+ savedJson = originalJson;
+ }
+ }
+ }
+ // Returning to the acknowledged value is still a write when another
+ // value is queued: that older save may commit before this reversal.
+ const hasChanged = pendingSettingsSaveByKey.has(parentKey) ||
+ !areObjectsEqual(jsonData, savedJson);
// Mark the parent container as modified if there's a change
const settingItem = changedControl.closest('.ldr-settings-item');
@@ -1237,6 +1292,7 @@
const parts = setting.key.split('.');
const prefix = parts[0]; // app, llm, search, etc.
const subKey = parts[1]; // The actual key name without prefix
+ const effectivePrefix = prefixToTab[prefix] || prefix;
// Filter out nested settings like app.llm, app.search, app.general, app.web, etc.
if (prefix === 'app' && (subKey === 'llm' || subKey === 'search' || subKey === 'general' || subKey === 'web')) {
@@ -1257,7 +1313,6 @@
if (tab !== 'all') {
// Treat aliased prefixes (e.g. policy.* shown under
// search tab) as if they belonged to the target tab.
- const effectivePrefix = prefixToTab[prefix] || prefix;
// Only show settings in tab-specific lists for that tab
if (tab === effectivePrefix) {
// For tab-specific settings, make sure they're in the list
@@ -1278,7 +1333,10 @@
// For "all" tab, filter out duplicates and specialized settings
// Check if this setting belongs exclusively to a specific tab
for (const tabName in tabSpecificSettings) {
- if (tabSpecificSettings[tabName].includes(subKey) && prefix !== tabName) {
+ if (
+ tabSpecificSettings[tabName].includes(subKey)
+ && effectivePrefix !== tabName
+ ) {
// Don't show this setting if it belongs to a different tab
return false;
}
@@ -1975,15 +2033,11 @@
window.modelDropdownsInitialized = false;
window.searchEngineDropdownInitialized = false;
- // Filter settings by tab
- let filteredSettings = allSettings;
-
- if (tab !== 'all') {
- filteredSettings = allSettings.filter(setting => setting.key.startsWith(tab + '.'));
- }
-
- // Organize settings to avoid duplicate groups
- const groupedSettings = organizeSettings(filteredSettings, tab);
+ // Let organizeSettings perform the tab filtering. It also maps
+ // auxiliary policy/embeddings prefixes onto the Search tab; eagerly
+ // filtering by `${tab}.` here would discard those settings before
+ // that mapping can run.
+ const groupedSettings = organizeSettings(allSettings, tab);
// Build HTML
let html = '';
@@ -2020,8 +2074,6 @@
// For each type (app, llm, search, etc.)
for (const type of prefixTypes) {
- if (tab !== 'all' && type !== tab) continue;
-
// For each category in this type
for (const category in groupedSettings[type]) {
const sectionId = `section-${type}-${category.replace(/\s+/g, '-').toLowerCase()}`;
@@ -2099,11 +2151,11 @@
* restored from originalSettings when they pick a non-private scope.
*/
function applyEgressScopeLock() {
- const scopeSelect = document.getElementById('setting-policy-egress-scope');
+ const scopeSelect = document.getElementById('setting-policy-egress_scope');
if (!scopeSelect) return;
const boxes = [
- { id: 'setting-llm-require-local-endpoint', key: 'llm.require_local_endpoint' },
- { id: 'setting-embeddings-require-local', key: 'embeddings.require_local' },
+ { id: 'setting-llm-require_local_endpoint', key: 'llm.require_local_endpoint' },
+ { id: 'setting-embeddings-require_local', key: 'embeddings.require_local' },
];
const LOCK_TITLE = 'Forced on by the Private-only egress scope — local inference is required so data stays on this machine.';
const apply = () => {
@@ -2124,8 +2176,13 @@
} else {
cb.disabled = false;
cb.title = '';
- // Restore the user's stored preference (visual lock only).
- const stored = originalSettings[key];
+ // Restore the latest intent if a save is still pending.
+ // Its acknowledgement may not have reached originalSettings
+ // yet, even though this is the value the user just chose.
+ const pendingSave = pendingSettingsSaveByKey.get(key);
+ const stored = pendingSave
+ ? pendingSave.values[key]
+ : originalSettings[key];
cb.checked = stored === true || stored === 'true';
if (fallback) fallback.disabled = cb.checked;
}
@@ -2509,7 +2566,7 @@
if (typeof value === 'boolean') {
const hiddenFallbackId = `${controlId}_hidden_fallback`;
controlHtml = `
- <div class="ldr-json-property-item ldr-boolean-property" onclick="directToggleCheckbox('${controlId}')" data-checkboxid="${controlId}">
+ <div class="ldr-json-property-item ldr-boolean-property" data-checkboxid="${controlId}">
<div class="ldr-checkbox-wrapper">
<label class="ldr-checkbox-label" for="${controlId}">
<!-- Hidden input ensures unchecked state is submitted -->
@@ -2803,6 +2860,7 @@
* @param {HTMLElement} sourceElement - The input element that triggered the save
*/
function submitSettingsData(formData, sourceElement) {
+ if (settingsResetInProgress) return;
// Show loading indicator
let loadingContainer = sourceElement;
@@ -2842,71 +2900,122 @@
originalValues[key] = Object.hasOwn(originalSettings, key) ? originalSettings[key] : null;
});
- // Capture timestamp before fetch so stale responses can be discarded
- const requestTimestamp = Date.now();
- lastSettingsUpdateTimestamp = requestTimestamp;
+ // Track the latest request per setting key. Date.now() is not a
+ // safe request token: rapid submits can share a millisecond and let an
+ // older response overwrite newer state. Key ownership also covers a
+ // field auto-save that crosses a later full-form save (or vice versa).
+ // Source ownership is kept separately so an obsolete request cannot
+ // clear a newer spinner attached to the same form/input.
+ const requestGeneration = ++nextSettingsSaveGeneration;
+ savingKeys.forEach(key => {
+ latestSettingsSaveGenerationByKey.set(key, requestGeneration);
+ });
+ if (sourceElement) {
+ latestSettingsSaveBySource.set(sourceElement, requestGeneration);
+ } else {
+ latestUnscopedSettingsSaveGeneration = requestGeneration;
+ }
+ const isLatestSourceRequest = () => (
+ sourceElement
+ ? latestSettingsSaveBySource.get(sourceElement) === requestGeneration
+ : latestUnscopedSettingsSaveGeneration === requestGeneration
+ );
+ const getCurrentSavingKeys = () => savingKeys.filter(
+ key => latestSettingsSaveGenerationByKey.get(key) === requestGeneration
+ );
+ const clearOwnedLoadingState = () => {
+ if (isLatestSourceRequest() && loadingContainer) {
+ loadingContainer.classList.remove('ldr-saving');
+ }
+ };
+
+ const blockingSaves = new Set();
+ savingKeys.forEach(key => {
+ const pendingSave = pendingSettingsSaveByKey.get(key);
+ if (pendingSave) blockingSaves.add(pendingSave.finished);
+ });
+
+ let resolveSaveFinished;
+ const saveOwnership = {
+ // Scope locks temporarily override the visible checkbox. Keep the
+ // queued intent available so unlocking does not restore stale data.
+ values: { ...formData },
+ finished: new Promise(resolve => {
+ resolveSaveFinished = resolve;
+ }),
+ };
+ savingKeys.forEach(key => {
+ pendingSettingsSaveByKey.set(key, saveOwnership);
+ });
+ const releaseSettingsSave = () => {
+ savingKeys.forEach(key => {
+ if (pendingSettingsSaveByKey.get(key) === saveOwnership) {
+ pendingSettingsSaveByKey.delete(key);
+ }
+ });
+ resolveSaveFinished();
+ };
- window.api.fetchWithErrorHandling(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
+ const runSaveRequest = () => window.api.fetchWithErrorHandling(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
method: 'POST',
body: JSON.stringify(formData),
})
.then(data => {
- if (data.status === 'success') {
- // Show success indicator on the source element
- if (sourceElement) {
- showSaveSuccess(sourceElement);
- }
-
- // Remove loading state
- if (loadingContainer) {
- loadingContainer.classList.remove('ldr-saving');
- }
+ // Overlapping writes are serialized, so every successful write is
+ // the newest confirmed server value for its submitted keys, even
+ // if a later intent is queued. Keep this rollback baseline when
+ // that later write fails; only visible feedback is intent-owned.
+ if (data.status === 'success' && data.settings) {
+ savingKeys.forEach(key => {
+ const updatedSetting = data.settings[key];
+ if (!updatedSetting) return;
- // Update all settings data if it's a global change
- if (!sourceElement || savingKeys.length > 1) {
- // Update global state
- if (data.settings) {
- // Only apply if no newer request has been dispatched since this one
- if (requestTimestamp >= lastSettingsUpdateTimestamp) {
- allSettings = processSettings(data.settings);
- }
- }
- } else if (savingKeys.length === 1) {
- // Update just the changed setting in our allSettings array
- const key = savingKeys[0];
+ const settingMap = { [key]: { ...updatedSetting } };
+ const processedSetting = processSettings(settingMap)[0];
const settingIndex = allSettings.findIndex(s => s.key === key);
+ if (settingIndex === -1) {
+ allSettings.push(processedSetting);
+ } else {
+ allSettings[settingIndex] = processedSetting;
+ }
+ originalSettings[key] = processedSetting.value;
+ });
+ }
- if (settingIndex !== -1 && data.settings) {
- // Find the updated setting in the response
- const updatedSetting = data.settings[key];
+ const currentSavingKeys = getCurrentSavingKeys();
+ if (savingKeys.length > 0 && currentSavingKeys.length === 0) {
+ clearOwnedLoadingState();
+ return;
+ }
- if (updatedSetting) {
- // Update the setting in our array
- const settingMap = {};
- settingMap[key] = updatedSetting;
- allSettings[settingIndex] = processSettings(settingMap)[0];
- }
- }
+ if (data.status === 'success') {
+ // Show success indicator on the source element
+ if (sourceElement && isLatestSourceRequest()) {
+ showSaveSuccess(sourceElement);
}
- // Update originalSettings cache for the saved keys
- savingKeys.forEach(key => {
- const settingIndex = allSettings.findIndex(s => s.key === key);
- if (settingIndex !== -1) {
- originalSettings[key] = allSettings[settingIndex].value;
- }
- });
-
- // Update the raw JSON editor if it's visible
- if (rawConfigSection && rawConfigSection.style.display === 'block') {
- prepareRawJsonEditor();
+ // Remove loading state
+ clearOwnedLoadingState();
+
+ // Keep the raw editor synchronized without erasing dirty keys
+ // that were not part of this response. A hidden dirty editor
+ // represents a raw-config save that is still settling, so it
+ // must be reconciled too before the user opens it again.
+ if (
+ rawConfigEditor &&
+ (
+ rawConfigSection?.style.display === 'block' ||
+ rawConfigEditor.getAttribute('data-modified') === 'true'
+ )
+ ) {
+ prepareRawJsonEditor(currentSavingKeys);
}
// Format a more informative message showing what changed
let successMessage;
try {
- if (savingKeys.length >= 1) {
- const key = savingKeys[0];
+ if (currentSavingKeys.length >= 1) {
+ const key = currentSavingKeys[0];
const oldValue = originalValues[key];
// Get new value from formData (what we sent) since allSettings might not be updated yet
const newValue = formData[key];
@@ -2929,7 +3038,7 @@
const oldDisplay = isSensitive ? '[hidden]' : formatValueForDisplay(oldValue);
const newDisplay = isSensitive ? '[hidden]' : formatValueForDisplay(newValue);
- if (savingKeys.length === 1) {
+ if (currentSavingKeys.length === 1) {
if (isSensitive) {
// For sensitive fields, just confirm the update without showing values
successMessage = `${capitalizedName} updated`;
@@ -2937,7 +3046,7 @@
successMessage = `${capitalizedName}: ${oldDisplay} → ${newDisplay}`;
}
} else {
- successMessage = `${savingKeys.length} settings saved`;
+ successMessage = `${currentSavingKeys.length} settings saved`;
}
} else {
successMessage = 'Settings saved';
@@ -2966,12 +3075,16 @@
}
// Remove loading state
- if (loadingContainer) {
- loadingContainer.classList.remove('ldr-saving');
- }
+ clearOwnedLoadingState();
}
})
.catch(error => {
+ const currentSavingKeys = getCurrentSavingKeys();
+ if (savingKeys.length > 0 && currentSavingKeys.length === 0) {
+ clearOwnedLoadingState();
+ return;
+ }
+
SafeLogger.error('[submitSettingsData] AJAX Error:', error);
SafeLogger.error('[submitSettingsData] Error details:', error.message);
@@ -2984,10 +3097,15 @@
}
// Remove loading state
- if (loadingContainer) {
- loadingContainer.classList.remove('ldr-saving');
- }
- });
+ clearOwnedLoadingState();
+ })
+ .finally(releaseSettingsSave);
+
+ if (blockingSaves.size > 0) {
+ Promise.allSettled([...blockingSaves]).then(runSaveRequest);
+ } else {
+ runSaveRequest();
+ }
}
/**
@@ -3196,12 +3314,38 @@
* Handle the reset to defaults button click
*/
function handleResetToDefaults() {
+ if (settingsResetInProgress) return Promise.resolve();
// Show confirmation dialog
if (confirm('Are you sure you want to reset ALL settings to their default values? This cannot be undone.')) {
+ // Flush edits still in the debounce window, then drain every key's
+ // queued writes before resetting. Otherwise an older queued save
+ // can reach the server after a successful reset.
+ const unsentSettings = { ...pendingSaveData };
+ Object.values(saveTimers).forEach(clearTimeout);
+ saveTimers = {};
+ pendingSaveData = {};
+ if (Object.keys(unsentSettings).length) {
+ submitSettingsData(unsentSettings, null);
+ }
+ settingsResetInProgress = true;
+ const formWasInert = settingsForm?.inert;
+ if (settingsForm) settingsForm.inert = true;
+ const resetControls = Array.from(document.querySelectorAll(
+ '#settings-form input, #settings-form textarea, #settings-form select, #settings-form button, #reset-to-defaults-button'
+ )).filter(control => !control.disabled);
+ resetControls.forEach(control => { control.disabled = true; });
+ const restoreControls = () => {
+ settingsResetInProgress = false;
+ if (settingsForm) settingsForm.inert = formWasInert;
+ resetControls.forEach(control => { control.disabled = false; });
+ };
+ const pendingSaves = Array.from(new Set(
+ Array.from(pendingSettingsSaveByKey.values(), save => save.finished)
+ ));
// Call the reset to defaults API
- window.api.fetchWithErrorHandling(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {
+ return Promise.allSettled(pendingSaves).then(() => window.api.fetchWithErrorHandling(URLS.SETTINGS_API.RESET_TO_DEFAULTS, {
method: 'POST'
- })
+ }))
.then(data => {
if (data.status === 'success') {
showAlert('Settings have been reset to defaults. Reloading page...', 'success');
@@ -3211,13 +3355,16 @@
window.location.reload();
}, 1500);
} else {
+ restoreControls();
showAlert('Error resetting settings: ' + data.message, 'error');
}
})
.catch(error => {
+ restoreControls();
showAlert('Error resetting settings: ' + error, 'error');
});
}
+ return Promise.resolve();
}
/**
@@ -3277,8 +3424,11 @@
/**
* Prepare the raw JSON editor with all settings
*/
- function prepareRawJsonEditor() {
+ function prepareRawJsonEditor(updatedKeys = []) {
if (rawConfigEditor && allSettings.length > 0) {
+ const updatedKeySet = new Set(updatedKeys);
+ const preserveDirtyValues =
+ rawConfigEditor.getAttribute('data-modified') === 'true';
// Try to parse existing JSON from editor if it exists
let existingConfig = {};
try {
@@ -3286,6 +3436,9 @@
existingConfig = JSON.parse(rawConfigEditor.value);
}
} catch {
+ // A background save must never erase a user's in-progress
+ // invalid buffer. Leave it untouched until they repair it.
+ if (preserveDirtyValues) return;
SafeLogger.warn('Could not parse existing JSON config, starting fresh');
existingConfig = {};
}
@@ -3318,7 +3471,12 @@
settingsObj[prefix][key.substring(prefix.length + 1)] = value;
});
- // Merge with existing config to preserve unknown parameters
+ // Merge with existing config to preserve unknown parameters. If
+ // the user is actively editing raw JSON, preserve known keys too
+ // unless this response saved that exact key. This lets an
+ // unrelated field auto-save refresh its own value without
+ // destroying the raw editor's unsaved work.
+ let preservedDirtyValue = false;
Object.keys(existingConfig).forEach(prefix => {
if (!settingsObj[prefix]) {
settingsObj[prefix] = {};
@@ -3329,14 +3487,23 @@
const fullKey = `${prefix}.${key}`;
const exists = allSettings.some(s => s.key === fullKey);
- if (!exists) {
+ if (
+ !exists ||
+ (preserveDirtyValues && !updatedKeySet.has(fullKey))
+ ) {
settingsObj[prefix][key] = existingConfig[prefix][key];
+ if (preserveDirtyValues && !updatedKeySet.has(fullKey)) {
+ preservedDirtyValue = true;
+ }
}
});
});
// Format as pretty JSON
rawConfigEditor.value = JSON.stringify(settingsObj, null, 2);
+ if (!preservedDirtyValue) {
+ rawConfigEditor.removeAttribute('data-modified');
+ }
}
}
@@ -3374,27 +3541,19 @@
* Initialize click handlers for checkbox wrappers
*/
function initCheckboxWrappers() {
- // No longer needed - using direct onclick attribute instead
- }
+ document.querySelectorAll('.ldr-boolean-property[data-checkboxid]').forEach(wrapper => {
+ if (wrapper.hasAttribute('data-checkbox-wrapper-initialized')) return;
+ wrapper.setAttribute('data-checkbox-wrapper-initialized', 'true');
- /**
- * Toggle checkbox directly from onclick event
- * Simple, direct function to toggle checkboxes
- * @param {string} checkboxId - The ID of the checkbox to toggle
- */
- function directToggleCheckbox(checkboxId) {
- const checkbox = document.getElementById(checkboxId);
- if (checkbox && !checkbox.disabled) {
- // Toggle the checkbox state
- checkbox.checked = !checkbox.checked;
-
- // Trigger change event for listeners
- const changeEvent = new Event('change', { bubbles: true });
- checkbox.dispatchEvent(changeEvent);
-
- // Stop event propagation
- event.stopPropagation();
- }
+ wrapper.addEventListener('click', (event) => {
+ // Inputs and labels already have native checkbox behavior. Only
+ // fill the otherwise inert space in the surrounding row.
+ if (event.target.closest('input, label, button, a')) return;
+
+ const checkbox = document.getElementById(wrapper.dataset.checkboxid);
+ if (checkbox && !checkbox.disabled) checkbox.click();
+ });
+ });
}
/**
@@ -3478,7 +3637,8 @@
? `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`
: URLS.SETTINGS_API.AVAILABLE_MODELS;
- window.modelProvidersRequestInProgress = fetch(url)
+ const requestGeneration = ++nextModelProvidersRequestGeneration;
+ const request = fetch(url)
.then(response => {
if (!response.ok) {
throw new Error(`API returned status: ${response.status}`);
@@ -3486,22 +3646,36 @@
return response.json();
})
.then(data => {
+ // A forced refresh may replace an in-flight request. Let the
+ // newest request own both the dropdown data and every caller's
+ // completion instead of allowing a late, stale response to
+ // overwrite it.
+ if (requestGeneration !== nextModelProvidersRequestGeneration) {
+ return latestModelProvidersRequest;
+ }
+
SafeLogger.log('Got model data from API:', data);
// Process the data
- const processedData = processModelData(data);
- // Clear the request flag
- window.modelProvidersRequestInProgress = null;
- return processedData;
+ return processModelData(data);
})
.catch(error => {
+ if (requestGeneration !== nextModelProvidersRequestGeneration) {
+ return latestModelProvidersRequest;
+ }
+
SafeLogger.error('Error fetching model providers:', error);
- // Clear the request flag on error
- window.modelProvidersRequestInProgress = null;
throw error;
+ })
+ .finally(() => {
+ if (window.modelProvidersRequestInProgress === request) {
+ window.modelProvidersRequestInProgress = null;
+ }
});
- return window.modelProvidersRequestInProgress;
+ latestModelProvidersRequest = request;
+ window.modelProvidersRequestInProgress = request;
+ return request;
}
/**
@@ -3519,7 +3693,8 @@
SafeLogger.log('Fetching search engines from API');
// Create a promise and store it
- window.searchEnginesRequestInProgress = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)
+ const requestGeneration = ++nextSearchEnginesRequestGeneration;
+ const request = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)
.then(response => {
if (!response.ok) {
throw new Error(`API returned status: ${response.status}`);
@@ -3527,22 +3702,32 @@
return response.json();
})
.then(data => {
+ if (requestGeneration !== nextSearchEnginesRequestGeneration) {
+ return latestSearchEnginesRequest;
+ }
+
SafeLogger.log('Received search engine data:', data);
// Process the data
- const processedData = processSearchEngineData(data);
- // Clear the request flag
- window.searchEnginesRequestInProgress = null;
- return processedData;
+ return processSearchEngineData(data);
})
.catch(error => {
+ if (requestGeneration !== nextSearchEnginesRequestGeneration) {
+ return latestSearchEnginesRequest;
+ }
+
SafeLogger.error('Error fetching search engines:', error);
- // Clear the request flag on error
- window.searchEnginesRequestInProgress = null;
throw error;
+ })
+ .finally(() => {
+ if (window.searchEnginesRequestInProgress === request) {
+ window.searchEnginesRequestInProgress = null;
+ }
});
- return window.searchEnginesRequestInProgress;
+ latestSearchEnginesRequest = request;
+ window.searchEnginesRequestInProgress = request;
+ return request;
}
/**
@@ -4070,6 +4255,7 @@
rawConfigToggle = document.getElementById('toggle-raw-config');
rawConfigSection = document.getElementById('raw-config');
rawConfigEditor = document.getElementById('raw_config_editor');
+ initRawConfigHandlers();
// Add dynamic styles immediately
diff --git a/src/local_deep_research/web/static/js/components/settings_sync.js b/src/local_deep_research/web/static/js/components/settings_sync.js
index 9ee46384b0..83dd8be78c 100644
--- a/src/local_deep_research/web/static/js/components/settings_sync.js
+++ b/src/local_deep_research/web/static/js/components/settings_sync.js
@@ -1,13 +1,19 @@
// Note: URLValidator is available globally via /static/js/security/url-validator.js
-// Function to save settings using the individual settings manager API
-function saveMenuSettings(settingKey, settingValue) {
+// Keep writes to the same setting in user-event order. The FastAPI handler
+// runs each request in an independent worker and has no client sequence token,
+// so overlapping PUTs could otherwise commit in the opposite order. Different
+// setting keys remain independent and can still save concurrently.
+const pendingMenuSettingSaves = new Map();
+
+// Perform one save using the individual settings manager API.
+function performMenuSettingSave(settingKey, settingValue) {
SafeLogger.log('Saving setting:', settingKey, '=', settingValue);
// Get CSRF token
const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Use the individual settings API endpoint that uses the settings manager
- fetch(`/settings/api/${settingKey}`, {
+ return fetch(`/settings/api/${settingKey}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
@@ -15,15 +21,21 @@ function saveMenuSettings(settingKey, settingValue) {
},
body: JSON.stringify({ value: settingValue })
})
- .then(response => {
+ .then(async response => {
SafeLogger.log('Response status:', response.status, response.statusText);
+ let data;
+ try {
+ data = await response.json();
+ } catch {
+ data = {};
+ }
if (!response.ok) {
- return response.text().then(text => {
- SafeLogger.error('Error response body:', text);
- throw new Error(`HTTP ${response.status}: ${text}`);
- });
+ const message = data.detail || data.error || data.message
+ || `HTTP ${response.status}`;
+ SafeLogger.error('Error response body:', message);
+ throw new Error(message);
}
- return response.json();
+ return data;
})
.then(data => {
SafeLogger.log(`Setting ${settingKey} saved via settings manager:`, data);
@@ -46,12 +58,50 @@ function saveMenuSettings(settingKey, settingValue) {
} else {
SafeLogger.log('Setting saved successfully:', data);
}
+
+ return true;
})
.catch(error => {
SafeLogger.error(`Error saving setting ${settingKey}:`, error);
if (window.ui && window.ui.showMessage) {
window.ui.showMessage(`Error updating ${settingKey}: ${error.message}`, 'error');
}
+ return false;
+ });
+}
+
+function saveMenuSettings(settingKey, settingValue) {
+ const priorSave = pendingMenuSettingSaves.get(settingKey)
+ || Promise.resolve();
+ const startSave = () => performMenuSettingSave(settingKey, settingValue);
+ const request = priorSave.then(startSave, startSave);
+ const trackedRequest = request.finally(() => {
+ if (pendingMenuSettingSaves.get(settingKey) === trackedRequest) {
+ pendingMenuSettingSaves.delete(settingKey);
+ }
+ });
+
+ pendingMenuSettingSaves.set(settingKey, trackedRequest);
+ return trackedRequest;
+}
+
+/**
+ * Save a URL input once for the browser's change -> blur event sequence.
+ *
+ * Text controls fire `change` immediately before `blur` when an edited value
+ * loses focus. Mark the value synchronously so the blur handler cannot issue
+ * an identical PUT while the change request is still awaiting the server.
+ * A rejected write releases the marker so a later blur can retry it.
+ */
+function saveUrlInputSetting(input, settingKey) {
+ const value = input.value;
+ input.setAttribute('data-last-saved', value);
+
+ return saveMenuSettings(settingKey, value).then(saved => {
+ if (!saved && input.getAttribute('data-last-saved') === value) {
+ input.removeAttribute('data-last-saved');
+ }
+ return saved;
});
}
@@ -60,12 +110,16 @@ function saveMenuSettings(settingKey, settingValue) {
*/
function connectMenuSettings() {
SafeLogger.log('Initializing menu settings handler');
+ // research.js owns these controls on the research page, including their
+ // optimistic UI and error handling. Binding the generic base-page bridge
+ // as well made one dropdown selection issue duplicate (and, for search,
+ // sometimes triple) PUTs to the same FastAPI setting route.
+ const researchOwnsCoreSettings = !!document.getElementById('research-form');
// Handle model dropdown changes
- const modelInput = document.getElementById('model');
const modelHidden = document.getElementById('model_hidden');
- if (modelHidden) {
+ if (modelHidden && !researchOwnsCoreSettings) {
modelHidden.addEventListener('change', function() {
SafeLogger.log('Model changed to:', this.value);
saveMenuSettings('llm.model', this.value);
@@ -74,7 +128,7 @@ function connectMenuSettings() {
// Handle provider dropdown changes
const providerSelect = document.getElementById('model_provider');
- if (providerSelect) {
+ if (providerSelect && !researchOwnsCoreSettings) {
providerSelect.addEventListener('change', function() {
SafeLogger.log('Provider changed to:', this.value);
saveMenuSettings('llm.provider', this.value);
@@ -83,7 +137,7 @@ function connectMenuSettings() {
// Handle search engine dropdown changes
const searchEngineHidden = document.getElementById('search_engine_hidden');
- if (searchEngineHidden) {
+ if (searchEngineHidden && !researchOwnsCoreSettings) {
searchEngineHidden.addEventListener('change', function() {
SafeLogger.log('Search engine changed to:', this.value);
saveMenuSettings('search.tool', this.value);
@@ -92,7 +146,7 @@ function connectMenuSettings() {
// Handle iterations and questions per iteration
const iterationsInput = document.getElementById('iterations');
- if (iterationsInput) {
+ if (iterationsInput && !researchOwnsCoreSettings) {
iterationsInput.addEventListener('change', function() {
SafeLogger.log('Iterations changed to:', this.value);
saveMenuSettings('search.iterations', this.value);
@@ -100,7 +154,7 @@ function connectMenuSettings() {
}
const questionsInput = document.getElementById('questions_per_iteration');
- if (questionsInput) {
+ if (questionsInput && !researchOwnsCoreSettings) {
questionsInput.addEventListener('change', function() {
SafeLogger.log('Questions per iteration changed to:', this.value);
saveMenuSettings('search.questions_per_iteration', this.value);
@@ -118,17 +172,16 @@ function connectMenuSettings() {
// Handle Ollama URL input changes
const ollamaUrlInput = document.getElementById('ollama_url');
- if (ollamaUrlInput) {
+ if (ollamaUrlInput && !researchOwnsCoreSettings) {
ollamaUrlInput.addEventListener('change', function() {
SafeLogger.log('Ollama URL changed to:', this.value);
- saveMenuSettings('llm.ollama.url', this.value);
+ saveUrlInputSetting(this, 'llm.ollama.url');
});
// Also save on blur (when user clicks away)
ollamaUrlInput.addEventListener('blur', function() {
if (this.value && this.value !== this.getAttribute('data-last-saved')) {
SafeLogger.log('Ollama URL changed (on blur) to:', this.value);
- saveMenuSettings('llm.ollama.url', this.value);
- this.setAttribute('data-last-saved', this.value);
+ saveUrlInputSetting(this, 'llm.ollama.url');
}
});
}
@@ -138,14 +191,13 @@ function connectMenuSettings() {
if (customEndpointInput) {
customEndpointInput.addEventListener('change', function() {
SafeLogger.log('Custom endpoint URL changed to:', this.value);
- saveMenuSettings('llm.openai_endpoint.url', this.value);
+ saveUrlInputSetting(this, 'llm.openai_endpoint.url');
});
// Also save on blur
customEndpointInput.addEventListener('blur', function() {
if (this.value && this.value !== this.getAttribute('data-last-saved')) {
SafeLogger.log('Custom endpoint URL changed (on blur) to:', this.value);
- saveMenuSettings('llm.openai_endpoint.url', this.value);
- this.setAttribute('data-last-saved', this.value);
+ saveUrlInputSetting(this, 'llm.openai_endpoint.url');
}
});
}
diff --git a/src/local_deep_research/web/static/js/components/subscription-manager.js b/src/local_deep_research/web/static/js/components/subscription-manager.js
index 0a0ec50287..48e552ffbb 100644
--- a/src/local_deep_research/web/static/js/components/subscription-manager.js
+++ b/src/local_deep_research/web/static/js/components/subscription-manager.js
@@ -10,6 +10,8 @@ class SubscriptionManager {
this.folders = [];
this.currentFolder = 'all';
this.initialized = false;
+ this.loadRequestId = 0;
+ this.editModalRequestId = 0;
}
async initialize() {
@@ -46,44 +48,69 @@ class SubscriptionManager {
// Subscription actions via delegation
document.addEventListener('click', (e) => {
- if (e.target.matches('.edit-subscription-btn')) {
- this.editSubscription(e.target.dataset.subscriptionId);
- } else if (e.target.matches('.delete-subscription-btn')) {
- this.deleteSubscription(e.target.dataset.subscriptionId);
- } else if (e.target.matches('.pause-subscription-btn')) {
- this.toggleSubscriptionStatus(e.target.dataset.subscriptionId);
+ const actionButton = e.target.closest?.(
+ '.edit-subscription-btn, .delete-subscription-btn, .pause-subscription-btn'
+ );
+ if (!actionButton) return;
+
+ if (actionButton.matches('.edit-subscription-btn')) {
+ this.editSubscription(actionButton.dataset.subscriptionId);
+ } else if (actionButton.matches('.delete-subscription-btn')) {
+ this.deleteSubscription(actionButton.dataset.subscriptionId);
+ } else if (actionButton.matches('.pause-subscription-btn')) {
+ this.toggleSubscriptionStatus(actionButton.dataset.subscriptionId);
}
});
}
async loadSubscriptionData() {
+ const requestId = ++this.loadRequestId;
+
try {
// Show loading state
this.showLoading();
// Load stats
const statsResponse = await fetch('/news/api/subscription/stats');
+ if (requestId !== this.loadRequestId) return;
if (statsResponse.ok) {
const stats = await statsResponse.json();
+ if (requestId !== this.loadRequestId) return;
this.updateStats(stats);
}
// Load folders
const foldersResponse = await fetch('/news/api/subscription/folders');
+ if (requestId !== this.loadRequestId) return;
if (foldersResponse.ok) {
- this.folders = await foldersResponse.json();
+ const folders = await foldersResponse.json();
+ if (requestId !== this.loadRequestId) return;
+ this.folders = folders;
this.renderFolderTabs();
}
// Load organized subscriptions
const subsResponse = await fetch('/news/api/subscription/subscriptions/organized');
- if (subsResponse.ok) {
- this.subscriptions = await subsResponse.json();
- this.renderSubscriptions();
+ if (requestId !== this.loadRequestId) return;
+ if (!subsResponse.ok) {
+ throw new Error(`HTTP error! status: ${subsResponse.status}`);
}
+ const subscriptions = await subsResponse.json();
+ if (requestId !== this.loadRequestId) return;
+ this.subscriptions = subscriptions;
+ this.renderSubscriptions();
} catch (error) {
+ if (requestId !== this.loadRequestId) return;
SafeLogger.error('Error loading subscription data:', error);
+ const container = document.getElementById('subscriptions-list');
+ if (container) {
+ const errorMessage = document.createElement('div');
+ errorMessage.className = 'alert alert-danger text-center';
+ errorMessage.setAttribute('role', 'alert');
+ errorMessage.textContent = 'Failed to load subscriptions. Please try again.';
+ container.replaceChildren(errorMessage);
+ }
this.showError('Failed to load subscriptions');
}
}
@@ -273,20 +300,35 @@ class SubscriptionManager {
// bearer:disable javascript_lang_dangerous_insert_html
// eslint-disable-next-line no-unsanitized/method -- audited 2026-03-28: variable built from escaped/numeric values above
document.body.insertAdjacentHTML('beforeend', modalHtml);
+ const modalElement = document.getElementById('editSubscriptionModal');
+ const modalRequestId = ++this.editModalRequestId;
// Set textarea value via DOM property (not innerHTML) to avoid entity encoding issues
document.getElementById('edit-notes').value = subscription.notes || '';
- const modal = new bootstrap.Modal(document.getElementById('editSubscriptionModal'));
+ const modal = new bootstrap.Modal(modalElement);
+ const saveButton = document.getElementById('save-subscription-edit');
// Handle save
- document.getElementById('save-subscription-edit').addEventListener('click', async () => {
+ saveButton.addEventListener('click', async () => {
+ if (saveButton.disabled) return;
+ saveButton.disabled = true;
+
const updates = {
refresh_interval_minutes: parseInt(document.getElementById('edit-frequency').value, 10),
folder: document.getElementById('edit-folder').value,
notes: document.getElementById('edit-notes').value
};
- await this.updateSubscription(subscriptionId, updates);
- modal.hide();
+ const updated = await this.updateSubscription(subscriptionId, updates);
+ const ownsCurrentModal = modalRequestId === this.editModalRequestId &&
+ document.getElementById('editSubscriptionModal') === modalElement;
+ if (!ownsCurrentModal) return;
+
+ if (updated) {
+ modal.hide();
+ } else {
+ // eslint-disable-next-line require-atomic-updates -- modal generation check above proves this button still owns the save
+ saveButton.disabled = false;
+ }
});
modal.show();
@@ -306,12 +348,15 @@ class SubscriptionManager {
if (response.ok) {
this.showSuccess('Subscription updated');
await this.loadSubscriptionData();
- } else {
- this.showError('Failed to update subscription');
+ return true;
}
+
+ this.showError('Failed to update subscription');
+ return false;
} catch (error) {
SafeLogger.error('Error updating subscription:', error);
this.showError('Error updating subscription');
+ return false;
}
}
@@ -379,7 +424,9 @@ class SubscriptionManager {
await this.loadSubscriptionData();
} else {
const error = await response.json();
- this.showError(error.error || 'Failed to create folder');
+ this.showError(
+ error.error || error.detail || 'Failed to create folder'
+ );
}
} catch (error) {
SafeLogger.error('Error creating folder:', error);
diff --git a/src/local_deep_research/web/static/js/deletion/delete_manager.js b/src/local_deep_research/web/static/js/deletion/delete_manager.js
index c781ad33f4..c74c5c1e3d 100644
--- a/src/local_deep_research/web/static/js/deletion/delete_manager.js
+++ b/src/local_deep_research/web/static/js/deletion/delete_manager.js
@@ -108,7 +108,7 @@ async function deleteDocument(documentId, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
// Get preview for better confirmation message
try {
@@ -173,7 +173,7 @@ async function deleteDocumentBlob(documentId, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
}
@@ -222,7 +222,7 @@ async function removeFromCollection(documentId, collectionId, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
}
@@ -268,7 +268,7 @@ async function deleteCollection(collectionId, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
// Get preview for better confirmation message
try {
@@ -337,7 +337,7 @@ async function deleteCollectionIndex(collectionId, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
}
@@ -387,7 +387,7 @@ async function bulkDeleteDocuments(documentIds, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
// Get preview for better confirmation message
try {
@@ -452,7 +452,7 @@ async function bulkDeleteBlobs(documentIds, options = {}) {
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
// Get preview
try {
@@ -517,7 +517,7 @@ async function bulkRemoveFromCollection(documentIds, collectionId, options = {})
};
if (options.skipConfirm) {
- confirmOptions.onConfirm();
+ await confirmOptions.onConfirm();
} else {
await window.DeleteConfirmation.confirmAndRun(confirmOptions, confirmOptions.onConfirm);
}
diff --git a/src/local_deep_research/web/static/js/embedding_settings.js b/src/local_deep_research/web/static/js/embedding_settings.js
index 25d0b3204f..6afcc5bf32 100644
--- a/src/local_deep_research/web/static/js/embedding_settings.js
+++ b/src/local_deep_research/web/static/js/embedding_settings.js
@@ -8,6 +8,11 @@ let providerOptions = [];
let availableModels = {};
let originalValues = {};
let autoSaveListenersAttached = false;
+let nextSettingSaveGeneration = 0;
+let availableModelsLoadId = 0;
+const latestSettingSaveGenerationByKey = new Map();
+const pendingSettingSaveByKey = new Map();
+const latestRequestedSettingValueByKey = new Map();
const openAIEmbeddingBatchSizeSavesInFlight = new WeakSet();
const openAIEmbeddingBatchSizePendingValues = new WeakMap();
let openAIEmbeddingBatchSizeHydrationVersion = 0;
@@ -67,9 +72,12 @@ document.addEventListener('DOMContentLoaded', function() {
* Load available embedding providers and models
*/
async function loadAvailableModels() {
+ const currentLoadId = ++availableModelsLoadId;
try {
const response = await safeFetchWithAuth('/library/api/rag/models');
+ if (currentLoadId !== availableModelsLoadId) return;
const data = await response.json();
+ if (currentLoadId !== availableModelsLoadId) return;
if (data.success) {
providerOptions = data.provider_options || [];
@@ -87,6 +95,7 @@ async function loadAvailableModels() {
showError('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');
}
@@ -397,12 +406,24 @@ function formatValueForDisplay(value) {
* @param {*} oldValue - Previous value for old → new display
*/
async function saveSetting(key, value, displayName, oldValue) {
+ const pendingSave = pendingSettingSaveByKey.get(key);
// Skip no-ops
- if (oldValue !== undefined && areValuesEqual(value, oldValue)) {
+ if (
+ !pendingSave &&
+ oldValue !== undefined &&
+ areValuesEqual(value, oldValue)
+ ) {
return;
}
- try {
+ const previousValue = pendingSave
+ ? latestRequestedSettingValueByKey.get(key)
+ : oldValue;
+ latestRequestedSettingValueByKey.set(key, value);
+ const saveGeneration = ++nextSettingSaveGeneration;
+ latestSettingSaveGenerationByKey.set(key, saveGeneration);
+
+ const runSave = async () => {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
const response = await safeFetchWithAuth('/settings/api/' + key, {
method: 'PUT',
@@ -415,17 +436,29 @@ async function saveSetting(key, value, displayName, oldValue) {
const data = await response.json();
if (!response.ok || data.error) {
- const errorMessage = data.error || 'Request failed (HTTP ' + response.status + ')';
- if (window.ui && window.ui.showMessage) {
- window.ui.showMessage('Failed to save ' + displayName + ': ' + errorMessage, 'error');
- } else {
- showError('Failed to save ' + displayName + ': ' + errorMessage);
- }
- return;
+ throw new Error(
+ data.error || 'Request failed (HTTP ' + response.status + ')'
+ );
}
+ return data;
+ };
+ const saveRequest = (pendingSave || Promise.resolve())
+ .catch(() => {})
+ .then(runSave);
+ pendingSettingSaveByKey.set(key, saveRequest);
+
+ try {
+ await saveRequest;
+
+ // This PUT has committed even when a newer intent now owns the form.
+ // Advance the server baseline before suppressing stale UI so a failed
+ // queued rollback can still be retried against the real saved value.
+ originalValues[key] = value;
+
+ if (latestSettingSaveGenerationByKey.get(key) !== saveGeneration) return;
// Show success notification with old → new
- const oldDisplay = formatValueForDisplay(oldValue);
+ const oldDisplay = formatValueForDisplay(previousValue);
const newDisplay = formatValueForDisplay(value);
const message = displayName + ': ' + oldDisplay + ' \u2192 ' + newDisplay;
@@ -435,17 +468,23 @@ async function saveSetting(key, value, displayName, oldValue) {
showSuccess(message);
}
- // Update tracked original value
- originalValues[key] = value;
-
// Refresh the saved defaults panel
refreshSavedDefaults();
} catch (error) {
+ if (latestSettingSaveGenerationByKey.get(key) !== saveGeneration) return;
SafeLogger.error('Error saving setting ' + key + ':', error);
if (window.ui && window.ui.showMessage) {
- window.ui.showMessage('Failed to save ' + displayName, 'error');
+ window.ui.showMessage(
+ 'Failed to save ' + displayName + ': ' + error.message,
+ 'error'
+ );
} else {
- showError('Failed to save ' + displayName);
+ showError('Failed to save ' + displayName + ': ' + error.message);
+ }
+ } finally {
+ if (pendingSettingSaveByKey.get(key) === saveRequest) {
+ pendingSettingSaveByKey.delete(key);
+ latestRequestedSettingValueByKey.delete(key);
}
}
}
diff --git a/src/local_deep_research/web/static/js/followup.js b/src/local_deep_research/web/static/js/followup.js
index 224b8d58be..cd179fab5c 100644
--- a/src/local_deep_research/web/static/js/followup.js
+++ b/src/local_deep_research/web/static/js/followup.js
@@ -9,6 +9,8 @@ class FollowUpResearch {
constructor() {
this.parentResearchId = null;
this.modalElement = null;
+ this.modalLoadPromise = null;
+ this.submitInProgress = false;
}
/**
@@ -74,10 +76,32 @@ class FollowUpResearch {
*/
async createModal() {
// Check if modal already exists
- if (document.getElementById('followUpModal')) {
+ const existingModal = document.getElementById('followUpModal');
+ if (existingModal) {
+ this.modalElement = existingModal;
return;
}
+ // init() starts loading eagerly. If the user clicks before that fetch
+ // settles, showFollowUpModal() comes through here too; both callers
+ // must own the same request and the same eventual DOM node.
+ if (this.modalLoadPromise) {
+ await this.modalLoadPromise;
+ return;
+ }
+
+ const loadPromise = this.loadModalTemplate();
+ this.modalLoadPromise = loadPromise;
+ try {
+ await loadPromise;
+ } finally {
+ if (this.modalLoadPromise === loadPromise) {
+ this.modalLoadPromise = null;
+ }
+ }
+ }
+
+ async loadModalTemplate() {
// Load modal template from server
try {
const response = await fetch('/static/templates/followup_modal.html');
@@ -103,8 +127,10 @@ class FollowUpResearch {
* Attach event handlers to modal elements
*/
attachModalEventHandlers() {
- const startBtn = document.getElementById('startFollowUpBtn');
- if (startBtn) {
+ const startBtn = this.getStartButton();
+ // The checked-in modal currently has an inline compatibility handler;
+ // don't register a second click callback when that handler is present.
+ if (startBtn && !startBtn.hasAttribute('onclick')) {
startBtn.addEventListener('click', () => this.submitFollowUp());
}
@@ -116,6 +142,11 @@ class FollowUpResearch {
}
}
+ getStartButton() {
+ return document.getElementById('startFollowUpBtn') ||
+ this.modalElement?.querySelector('.modal-footer .btn-primary');
+ }
+
/**
* Add modal styles if needed
*/
@@ -287,6 +318,16 @@ class FollowUpResearch {
return;
}
+ // A slow /start response used to leave the button active, allowing a
+ // rapid double-click to create two independent child researches.
+ // Keep ownership on this instance until the request either fails (and
+ // can be retried) or succeeds and navigates away.
+ if (this.submitInProgress) return;
+ this.submitInProgress = true;
+ const startBtn = this.getStartButton();
+ if (startBtn) startBtn.disabled = true;
+ let started = false;
+
SafeLogger.log('Submitting follow-up research:', {
parent_research_id: this.parentResearchId,
question
@@ -312,30 +353,54 @@ class FollowUpResearch {
if (!response.ok) {
SafeLogger.error('Follow-up API error:', response.status, response.statusText);
- const text = await response.text();
- SafeLogger.error('Response body:', text);
- throw new Error(`HTTP error! status: ${response.status}`);
+ const errorData = await response.json().catch(() => ({}));
+ const errorMessage = errorData?.error || errorData?.detail ||
+ errorData?.message || `HTTP error! status: ${response.status}`;
+ SafeLogger.error('Response body:', errorMessage);
+ throw new Error(errorMessage);
}
const data = await response.json();
SafeLogger.log('Follow-up API response:', data);
- if (data.success) {
+ const researchId = data && data.research_id;
+ const hasResearchId = (
+ (typeof researchId === 'string' && researchId.trim() !== '') ||
+ (typeof researchId === 'number' && Number.isFinite(researchId))
+ );
+
+ if (data?.success && hasResearchId) {
// Close modal
bootstrap.Modal.getInstance(this.modalElement).hide();
// Redirect to progress page to show the research is running.
// Single navigation site; no concurrent writers to window.location.
- // server-generated UUID in hardcoded /progress/ path
+ // Keep the server-generated ID inside one hardcoded /progress/
+ // path segment even if a future backend changes its ID format.
// bearer:disable javascript_lang_open_redirect
// eslint-disable-next-line require-atomic-updates
- window.location.href = `/progress/${data.research_id}`;
+ window.location.href = `/progress/${encodeURIComponent(
+ String(researchId).trim()
+ )}`;
+ started = true;
} else {
- window.ui.showInlineError('followup-error-container', 'Error starting follow-up research: ' + (data.error || 'Unknown error'));
+ const message = data?.error || data?.detail || data?.message ||
+ (data?.success
+ ? 'Response did not include a valid research ID'
+ : 'Unknown error');
+ window.ui.showInlineError(
+ 'followup-error-container',
+ 'Error starting follow-up research: ' + message
+ );
}
} catch (error) {
SafeLogger.error('Error submitting follow-up:', error);
window.ui.showInlineError('followup-error-container', 'Failed to start follow-up research: ' + error.message);
+ } finally {
+ if (!started) {
+ this.submitInProgress = false;
+ if (startBtn) startBtn.disabled = false;
+ }
}
}
}
diff --git a/src/local_deep_research/web/static/js/pages/link_analytics_render.js b/src/local_deep_research/web/static/js/pages/link_analytics_render.js
index 9234b24be0..223b49cd5b 100644
--- a/src/local_deep_research/web/static/js/pages/link_analytics_render.js
+++ b/src/local_deep_research/web/static/js/pages/link_analytics_render.js
@@ -8,7 +8,7 @@
*
* Security note: every untrusted string interpolation in this function is
* either wrapped in Number()/Math.round() (numeric coercion) or passed
- * through window.escapeHtml / encodeURIComponent / encodeURI. External
+ * through escapeHtml / encodeURIComponent / encodeURI. External
* hrefs are additionally screened by URLValidator.isSafeUrl to reject
* javascript:/data: schemes, with a console.warn on rejection for
* debuggability. Tests at tests/js/pages/link-analytics-xss.test.js
@@ -17,6 +17,21 @@
(function() {
'use strict';
+ // This file and link_analytics.html execute in the page content before
+ // base.html's deferred xss-protection.js. Keep a scoped fallback so a
+ // fast initial response cannot race the canonical global escaper.
+ const escapeHtml = window.escapeHtml || (value => String(value ?? '').replace(
+ /[&<>"'/]/g,
+ character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ '/': '&#x2F;',
+ })[character],
+ ));
+
/**
* Build a safe `https://<domain>` href, rejecting anything URLValidator
* flags as an unsafe scheme. Domains here come from the link_analytics
@@ -58,8 +73,8 @@
<div class="ldr-research-links">
<div class="ldr-research-links-title">Recent Researches (${Number(researchDiversity) || 0} total)</div>
${domain.recent_researches.map(r => `
- <a href="/results/${encodeURIComponent(r.id)}" class="ldr-research-link" title="${window.escapeHtml(r.query)}">
- ${window.escapeHtml(r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query)}
+ <a href="/results/${encodeURIComponent(r.id)}" class="ldr-research-link" title="${escapeHtml(r.query)}">
+ ${escapeHtml(r.query.length > 30 ? r.query.substring(0, 30) + '...' : r.query)}
</a>
`).join('')}
</div>
@@ -70,8 +85,8 @@
let classificationHtml = '';
if (domain.classification) {
classificationHtml = `
- <span class="ldr-classified-badge" title="${window.escapeHtml(domain.classification.subcategory)} (${Math.round(Number(domain.classification.confidence) * 100)}% confidence)">
- ${window.escapeHtml(domain.classification.category)}
+ <span class="ldr-classified-badge" title="${escapeHtml(domain.classification.subcategory)} (${Math.round(Number(domain.classification.confidence) * 100)}% confidence)">
+ ${escapeHtml(domain.classification.category)}
</span>
`;
}
@@ -81,7 +96,7 @@
item.innerHTML = `
<div class="ldr-domain-header">
<span class="ldr-domain-name" style="font-size: 1rem; font-weight: 600;">
- ${rank ? `#${rank}` : ''} <a href="${safeExternalHref(domain.domain)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none; border-bottom: 1px dotted var(--accent-primary); transition: all 0.2s ease;" onmouseover="this.style.borderBottom='2px solid var(--accent-primary)'" onmouseout="this.style.borderBottom='1px dotted var(--accent-primary)'">${window.escapeHtml(domain.domain)}</a>
+ ${rank ? `#${rank}` : ''} <a href="${safeExternalHref(domain.domain)}" target="_blank" rel="noopener noreferrer" style="color: var(--accent-primary); text-decoration: none; border-bottom: 1px dotted var(--accent-primary); transition: all 0.2s ease;" onmouseover="this.style.borderBottom='2px solid var(--accent-primary)'" onmouseout="this.style.borderBottom='1px dotted var(--accent-primary)'">${escapeHtml(domain.domain)}</a>
${classificationHtml}
</span>
<div class="ldr-domain-stats">
diff --git a/src/local_deep_research/web/static/js/pages/news.js b/src/local_deep_research/web/static/js/pages/news.js
index 30ec5aa2d8..2e44effe79 100644
--- a/src/local_deep_research/web/static/js/pages/news.js
+++ b/src/local_deep_research/web/static/js/pages/news.js
@@ -33,31 +33,41 @@ function safeRenderHTML(container, htmlString) {
container.appendChild(fragment);
}
-// Sanitize a URL for safe use in href attributes (blocks javascript:, data:, etc.)
+// Sanitize a URL for safe use in report href attributes.
function safeHref(url) {
- if (!url || typeof url !== 'string') return '#';
+ if (typeof url !== 'string') return '#';
const trimmed = url.trim();
- // Allow relative URLs (starting with /)
- if (trimmed.startsWith('/')) return escapeHtml(trimmed);
- // Use URLValidator if available to check for unsafe schemes
- if (typeof URLValidator !== 'undefined' && URLValidator.isSafeUrl) {
- return URLValidator.isSafeUrl(trimmed) ? escapeHtml(trimmed) : '#';
+ if (!trimmed) return '#';
+
+ // Use the same policy as page navigation. A plain object deliberately
+ // avoids the blob/data exceptions reserved for owned DOM render targets.
+ const validator = window.URLValidator;
+ if (validator?.safeAssign) {
+ const navigationProbe = {};
+ if (!validator.safeAssign(
+ navigationProbe,
+ 'href',
+ trimmed,
+ )) return '#';
+ } else if (validator?.isSafeUrl && !validator.isSafeUrl(trimmed)) {
+ return '#';
}
- // Fallback: block known unsafe schemes
- const lower = trimmed.toLowerCase();
- if (lower.startsWith('javascript:') || lower.startsWith('data:') || lower.startsWith('vbscript:')) return '#';
- return escapeHtml(trimmed);
-}
-// Escape attributes for use in HTML attributes (onclick, etc)
-function escapeAttr(unsafe) {
- if (unsafe === null || unsafe === undefined) return '';
- return String(unsafe)
- .replace(/\\/g, "\\\\")
- .replace(/'/g, "\\'")
- .replace(/"/g, '\\"')
- .replace(/\n/g, "\\n")
- .replace(/\r/g, "\\r");
+ // Keep the canonical browser-parsed destination within the current
+ // origin unless the input contains an explicitly allowed network scheme. This also
+ // protects the fallback path when URLValidator is unavailable.
+ try {
+ const parsed = new URL(trimmed, window.location.href);
+ const hasExplicitScheme = /^[a-z][a-z\d+.-]*:/i.test(trimmed);
+ const isAllowedScheme = ['http:', 'https:', 'ftp:', 'ftps:']
+ .includes(parsed.protocol);
+ if (!isAllowedScheme || (!hasExplicitScheme && parsed.origin !== window.location.origin)) {
+ return '#';
+ }
+ return escapeHtml(trimmed);
+ } catch {
+ return '#';
+ }
}
// Global state
@@ -69,6 +79,9 @@ let subscriptions = [];
let lastVisitTime = null;
let seenNewsIds = new Set();
let searchHistory = [];
+let searchHistoryLoadRequestId = 0;
+let searchHistoryMutationGeneration = 0;
+let searchHistoryWriteQueue = Promise.resolve();
let autoRefreshInterval = null;
let priorityCheckInterval = null;
let refreshIndicatorInterval = null;
@@ -78,6 +91,17 @@ let activeImpactThreshold = 0;
let readNewsIds = new Set();
let expandedNewsIds = new Set();
let savedNewsIds = new Set();
+let voteLoadRequestId = 0;
+const activeVoteRequests = new Map();
+const voteRequestTails = new Map();
+let newsFeedRequestId = 0;
+let newsFeedRequestIntent = 'generic';
+let newsResearchPollId = 0;
+let activeNewsResearchPoll = null;
+let newsResearchReloadTimer = null;
+let newsResearchRestoreId = 0;
+let activeNewsSubscriptionSubmit = null;
+const activeAdvancedNewsSearches = new Map();
// Semantic search state
const NEWS_SM = { HYBRID: 'hybrid', TEXT: 'text', SEMANTIC: 'semantic' };
@@ -222,9 +246,29 @@ function cleanupNewsPage() {
clearTimeout(newsSemanticTimer);
newsSemanticTimer = null;
}
+ if (activeNewsResearchPoll) {
+ stopNewsResearchPoll(activeNewsResearchPoll);
+ }
+ if (newsResearchReloadTimer !== null) {
+ clearTimeout(newsResearchReloadTimer);
+ newsResearchReloadTimer = null;
+ }
+ // Retire responses that were already awaiting I/O when the page exited.
+ newsFeedRequestId++;
+ newsResearchPollId++;
+ newsResearchRestoreId++;
+ searchHistoryLoadRequestId++;
}
function setupEventListeners() {
+ // The checked-in template deliberately avoids an inline onclick handler.
+ // Own the refresh action here so the button still performs the request
+ // when optional design-enhancement scripts are absent or fail to load.
+ const refreshBtn = document.getElementById('refresh-feed-btn');
+ if (refreshBtn) {
+ refreshBtn.addEventListener('click', refreshFeed);
+ }
+
// Search button
// Search button still works as a manual trigger
const searchBtn = document.getElementById('search-btn');
@@ -352,6 +396,81 @@ function setupEventListeners() {
// Category filters removed - LDR uses dynamic topics instead
+ // Actions rendered outside a card use the same declarative pattern. These
+ // controls are also passed through DOMPurify and can be replaced whenever
+ // a search or history request completes.
+ document.addEventListener('click', (e) => {
+ const pageActionControl = e.target.closest('[data-news-page-action]');
+ if (!pageActionControl) return;
+
+ e.preventDefault();
+ switch (pageActionControl.dataset.newsPageAction) {
+ case 'clear-search':
+ clearSearch();
+ break;
+ case 'rerun-search':
+ rerunSearch(
+ pageActionControl.dataset.query || '',
+ pageActionControl.dataset.searchType || 'quick'
+ );
+ break;
+ default:
+ break;
+ }
+ });
+
+ // DOMPurify deliberately removes inline event handlers from the rendered
+ // feed. Keep card actions declarative and dispatch them from this stable
+ // listener so re-rendered cards remain interactive after sanitization.
+ document.addEventListener('click', (e) => {
+ const actionControl = e.target.closest('[data-news-action]');
+ const newsItem = actionControl?.closest('.ldr-news-item');
+ if (!actionControl || !newsItem) return;
+
+ const newsId = newsItem.dataset.newsId;
+ if (!newsId) return;
+
+ const action = actionControl.dataset.newsAction;
+ // Only the report link should retain its normal navigation. The menu
+ // actions use href="#" and the remaining controls are buttons.
+ if (action !== 'mark-read') e.preventDefault();
+
+ switch (action) {
+ case 'toggle-read':
+ toggleReadStatus(newsId);
+ break;
+ case 'share':
+ shareNews(newsId);
+ break;
+ case 'copy-link':
+ copyNewsLink(newsId);
+ break;
+ case 'export-markdown':
+ exportToMarkdown(newsId);
+ break;
+ case 'hide':
+ hideNewsItem(newsId);
+ break;
+ case 'vote':
+ if (actionControl.dataset.voteType === 'up' ||
+ actionControl.dataset.voteType === 'down') {
+ vote(newsId, actionControl.dataset.voteType);
+ }
+ break;
+ case 'mark-read':
+ markAsReadOnClick(newsId);
+ break;
+ case 'toggle-save':
+ toggleSaveItem(newsId);
+ break;
+ case 'subscribe':
+ createSubscriptionFromItem(newsId);
+ break;
+ default:
+ break;
+ }
+ });
+
// Event delegation for news card clicks
document.addEventListener('click', (e) => {
// Find the closest news-item parent
@@ -443,7 +562,35 @@ function clearSearch() {
}
// Advanced search using LDR search system
+function advancedNewsSearchKey(query, strategy, modelConfig) {
+ const normalizedModelConfig = modelConfig ? {
+ provider: modelConfig.provider ?? null,
+ model: modelConfig.model ?? null,
+ customEndpoint: modelConfig.customEndpoint ?? null,
+ searchEngine: modelConfig.searchEngine ?? null,
+ iterations: modelConfig.iterations ?? null,
+ questions: modelConfig.questions ?? null
+ } : null;
+ return JSON.stringify([query, strategy, normalizedModelConfig]);
+}
+
async function performAdvancedNewsSearch(query, strategy = 'source-based', modelConfig = null) {
+ const searchKey = advancedNewsSearchKey(query, strategy, modelConfig);
+ const activeSearch = activeAdvancedNewsSearches.get(searchKey);
+ if (activeSearch) return activeSearch;
+
+ const searchPromise = executeAdvancedNewsSearch(query, strategy, modelConfig);
+ activeAdvancedNewsSearches.set(searchKey, searchPromise);
+ try {
+ return await searchPromise;
+ } finally {
+ if (activeAdvancedNewsSearches.get(searchKey) === searchPromise) {
+ activeAdvancedNewsSearches.delete(searchKey);
+ }
+ }
+}
+
+async function executeAdvancedNewsSearch(query, strategy = 'source-based', modelConfig = null) {
SafeLogger.log('performAdvancedNewsSearch called with:', { query, strategy, modelConfig });
showAlert('Performing advanced news analysis...', 'info');
@@ -489,7 +636,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', model
let errorMessage = 'Error starting research';
try {
const errorData = await response.json();
- errorMessage = errorData.error || errorData.message || errorMessage;
+ errorMessage = errorData.error || errorData.message || errorData.detail || errorMessage;
} catch {
// If response is not JSON, use status text
errorMessage = `${errorMessage}: ${response.statusText}`;
@@ -520,7 +667,7 @@ async function performAdvancedNewsSearch(query, strategy = 'source-based', model
const container = document.getElementById('news-feed-content');
// bearer:disable javascript_lang_dangerous_insert_html
container.innerHTML = `
- <div class="ldr-news-card ldr-priority-high ldr-active-research-card">
+ <div class="ldr-news-card ldr-priority-high ldr-active-research-card" data-research-id="${escapeHtml(data.research_id)}">
<div class="ldr-news-header">
<h2 class="ldr-news-title">
<i class="bi bi-hourglass-split ldr-spinning"></i>
@@ -776,11 +923,17 @@ function selectSubscription(subId) {
activeSubscription = subId;
// renderSubscriptions(); // Removed sidebar subscription list
clearSemanticState();
- loadNewsFeed();
+ return loadNewsFeed(null, true);
}
// Load news feed
-async function loadNewsFeed(focus = null) {
+async function loadNewsFeed(focus = null, explicitView = false) {
+ const requestId = ++newsFeedRequestId;
+ newsFeedRequestIntent = explicitView || focus !== null
+ ? 'explicit'
+ : 'generic';
+ const requestedSubscription = activeSubscription;
+
// Clear stale semantic badges — hybrid search will re-set them if needed
newsSemanticMatches = null;
@@ -795,7 +948,7 @@ async function loadNewsFeed(focus = null) {
updateFeedHeader();
// Handle saved items view
- if (activeSubscription === 'saved') {
+ if (requestedSubscription === 'saved') {
loadSavedNewsFeed();
return;
}
@@ -807,25 +960,28 @@ async function loadNewsFeed(focus = null) {
});
if (focus) params.append('focus', focus);
- if (activeSubscription !== 'all') params.append('subscription_id', activeSubscription);
+ if (requestedSubscription !== 'all') params.append('subscription_id', requestedSubscription);
SafeLogger.log('Fetching news from:', `/news/api/feed?${params}`);
const response = await fetch(`/news/api/feed?${params}`);
+ if (requestId !== newsFeedRequestId) return;
SafeLogger.log('Response status:', response.status);
if (response.ok) {
const data = await response.json();
- newsItems = data.news_items || [];
- SafeLogger.log(`Loaded ${newsItems.length} news items from API`);
+ if (requestId !== newsFeedRequestId) return;
+
+ let loadedNewsItems = data.news_items || [];
+ SafeLogger.log(`Loaded ${loadedNewsItems.length} news items from API`);
SafeLogger.log('API response:', data);
- if (newsItems.length > 0) {
- SafeLogger.log('First news item:', newsItems[0]);
+ if (loadedNewsItems.length > 0) {
+ SafeLogger.log('First news item:', loadedNewsItems[0]);
}
// Apply client-side filtering if focus is provided
if (focus) {
const searchTerm = focus.toLowerCase();
- const filteredItems = newsItems.filter(item => {
+ const filteredItems = loadedNewsItems.filter(item => {
const headline = (item.headline || '').toLowerCase();
const summary = (item.summary || '').toLowerCase();
const query = (item.query || '').toLowerCase();
@@ -839,9 +995,10 @@ async function loadNewsFeed(focus = null) {
SafeLogger.log(`Filtered to ${filteredItems.length} items matching "${focus}"`);
// Update newsItems with filtered results (even if empty)
- newsItems = filteredItems;
+ loadedNewsItems = filteredItems;
}
+ newsItems = loadedNewsItems;
renderNewsItems(focus);
extractTrendingTopics();
updateBulkActionsBar();
@@ -851,10 +1008,12 @@ async function loadNewsFeed(focus = null) {
} else {
SafeLogger.error('Failed to load news feed. Status:', response.status);
const errorText = await response.text();
+ if (requestId !== newsFeedRequestId) return;
SafeLogger.error('Error response:', errorText);
safeRenderHTML(container, `<p class="ldr-error-message">Failed to load news feed (${response.status})</p>`);
}
} catch (error) {
+ if (requestId !== newsFeedRequestId) return;
SafeLogger.error('Error loading news:', error);
safeRenderHTML(container, '<p class="ldr-error-message">Error loading news feed</p>');
}
@@ -934,7 +1093,7 @@ function renderNewsItems(searchQuery = null) {
searchIndicatorHtml = `
<div class="ldr-search-indicator alert alert-info">
<i class="bi bi-search"></i> Showing results for: <strong>"${escapeHtml(searchQuery)}"</strong>
- <button class="btn btn-sm btn-link" onclick="clearSearch()">
+ <button class="btn btn-sm btn-link" data-news-page-action="clear-search">
<i class="bi bi-x-circle"></i> Clear search
</button>
</div>
@@ -1014,7 +1173,7 @@ function renderNewsItems(searchQuery = null) {
: ''}
</div>
<div class="ldr-news-actions-menu">
- <button class="btn btn-sm ldr-btn-ghost" onclick="toggleReadStatus('${escapeAttr(item.id)}')" title="${isRead ? 'Mark as unread' : 'Mark as read'}">
+ <button class="btn btn-sm ldr-btn-ghost" data-news-action="toggle-read" title="${isRead ? 'Mark as unread' : 'Mark as read'}">
<i class="bi ${isRead ? 'bi-envelope-open' : 'bi-envelope'}"></i>
</button>
<div class="dropdown">
@@ -1022,17 +1181,17 @@ function renderNewsItems(searchQuery = null) {
<i class="bi bi-three-dots-vertical"></i>
</button>
<ul class="dropdown-menu dropdown-menu-end">
- <li><a class="dropdown-item" href="#" onclick="shareNews('${escapeAttr(item.id)}'); return false;">
+ <li><a class="dropdown-item" href="#" data-news-action="share">
<i class="bi bi-share"></i> Share
</a></li>
- <li><a class="dropdown-item" href="#" onclick="copyNewsLink('${escapeAttr(item.id)}'); return false;">
+ <li><a class="dropdown-item" href="#" data-news-action="copy-link">
<i class="bi bi-link-45deg"></i> Copy Link
</a></li>
- <li><a class="dropdown-item" href="#" onclick="exportToMarkdown('${escapeAttr(item.id)}'); return false;">
+ <li><a class="dropdown-item" href="#" data-news-action="export-markdown">
<i class="bi bi-markdown"></i> Export as Markdown
</a></li>
<li><hr class="dropdown-divider"></li>
- <li><a class="dropdown-item" href="#" onclick="hideNewsItem('${escapeAttr(item.id)}'); return false;">
+ <li><a class="dropdown-item" href="#" data-news-action="hide">
<i class="bi bi-eye-slash"></i> Hide this item
</a></li>
</ul>
@@ -1055,21 +1214,21 @@ function renderNewsItems(searchQuery = null) {
${renderSourceLinks(item.links)}
<div class="ldr-news-actions">
<div class="ldr-vote-buttons">
- <button class="ldr-vote-btn" onclick="vote('${escapeAttr(item.id)}', 'up')">
+ <button class="ldr-vote-btn" data-news-action="vote" data-vote-type="up">
<i class="fas fa-thumbs-up"></i> ${Number(item.upvotes) || 0}
</button>
- <button class="ldr-vote-btn" onclick="vote('${escapeAttr(item.id)}', 'down')">
+ <button class="ldr-vote-btn" data-news-action="vote" data-vote-type="down">
<i class="fas fa-thumbs-down"></i> ${Number(item.downvotes) || 0}
</button>
</div>
<div class="ldr-action-buttons">
- <a href="${safeHref(item.source_url || `/results/${item.research_id}`)}" class="btn btn-primary btn-sm" onclick="markAsReadOnClick('${escapeAttr(item.id)}')">
+ <a href="${safeHref(item.source_url || `/results/${item.research_id}`)}" class="btn btn-primary btn-sm" data-news-action="mark-read">
<i class="fas fa-file-alt"></i> View Full Report
</a>
- <button class="btn btn-secondary btn-sm ldr-save-btn" onclick="toggleSaveItem('${escapeAttr(item.id)}')" title="${savedNewsIds.has(item.id) ? 'Remove from saved' : 'Save for later'}">
+ <button class="btn btn-secondary btn-sm ldr-save-btn" data-news-action="toggle-save" title="${savedNewsIds.has(item.id) ? 'Remove from saved' : 'Save for later'}">
<i class="${savedNewsIds.has(item.id) ? 'bi bi-bookmark-fill' : 'bi bi-bookmark'}"></i>
</button>
- ${item.query ? `<button class="btn btn-outline-primary btn-sm" onclick="createSubscriptionFromItem('${escapeAttr(item.id)}')" title="Create subscription from this search">
+ ${item.query ? `<button class="btn btn-outline-primary btn-sm" data-news-action="subscribe" title="Create subscription from this search">
<i class="bi bi-bell-plus"></i> Subscribe
</button>` : ''}
</div>
@@ -1196,7 +1355,8 @@ function getImpactClass(score) {
}
// Load existing votes for all displayed news items
-async function loadVotesForNewsItems() {
+async function loadVotesForNewsItems(ownsResponse = null) {
+ const requestId = ++voteLoadRequestId;
if (!newsItems || newsItems.length === 0) return;
try {
@@ -1214,6 +1374,8 @@ async function loadVotesForNewsItems() {
if (response.ok) {
const data = await response.json();
+ if (requestId !== voteLoadRequestId) return;
+ if (ownsResponse && !ownsResponse()) return;
if (data.votes) {
// Update UI with vote counts and user's votes
for (const [cardId, voteInfo] of Object.entries(data.votes)) {
@@ -1248,26 +1410,47 @@ async function loadVotesForNewsItems() {
}
}
} catch (error) {
+ if (requestId !== voteLoadRequestId) return;
+ if (ownsResponse && !ownsResponse()) return;
SafeLogger.error('Error loading votes:', error);
}
}
// Vote on news item
async function vote(newsId, voteType) {
- try {
- const response = await fetch(`/news/api/feedback/${newsId}`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': getCSRFToken()
- },
- body: JSON.stringify({
- vote: voteType
- })
- });
+ const requestToken = {};
+ activeVoteRequests.set(newsId, requestToken);
+ const executeRequest = async () => {
+ try {
+ const response = await fetch(`/news/api/feedback/${newsId}`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken()
+ },
+ body: JSON.stringify({
+ vote: voteType
+ })
+ });
+
+ if (!response.ok) {
+ throw new Error(`Vote request failed with status ${response.status}`);
+ }
- if (response.ok) {
const data = await response.json();
+ if (
+ !data ||
+ typeof data !== 'object' ||
+ Array.isArray(data) ||
+ !Object.hasOwn(data, 'upvotes') ||
+ !Object.hasOwn(data, 'downvotes')
+ ) {
+ throw new Error('Vote response did not include vote counts');
+ }
+ if (activeVoteRequests.get(newsId) !== requestToken) return null;
+ // Also invalidate a batch that began while this write was in
+ // flight; the mutation response is authoritative for the UI.
+ voteLoadRequestId++;
// Update UI
const item = document.querySelector(`[data-news-id="${newsId}"]`);
if (item) {
@@ -1289,9 +1472,45 @@ async function vote(newsId, voteType) {
upBtn.classList.remove('ldr-voted');
}
}
+ return null;
+ } catch (error) {
+ const ownsResponse = () => (
+ activeVoteRequests.get(newsId) === requestToken
+ );
+ if (!ownsResponse()) return null;
+ SafeLogger.error('Error voting:', error);
+ showAlert(
+ 'Failed to save vote. Restoring the latest vote state.',
+ 'error'
+ );
+ return {
+ reconciliation: loadVotesForNewsItems(ownsResponse)
+ };
+ }
+ };
+ const previousRequest = voteRequestTails.get(newsId);
+ const writeRequest = previousRequest
+ ? previousRequest.catch(() => {}).then(executeRequest)
+ : executeRequest();
+ // Only the POST and response parsing own the per-ID write slot. A failed
+ // vote may continue awaiting best-effort reconciliation, but that read
+ // must never delay a newer user retry from reaching the server.
+ const writeTail = writeRequest.then(
+ () => undefined,
+ () => undefined
+ );
+ voteRequestTails.set(newsId, writeTail);
+
+ try {
+ const result = await writeRequest;
+ if (result?.reconciliation) await result.reconciliation;
+ } finally {
+ if (voteRequestTails.get(newsId) === writeTail) {
+ voteRequestTails.delete(newsId);
+ }
+ if (activeVoteRequests.get(newsId) === requestToken) {
+ activeVoteRequests.delete(newsId);
}
- } catch (error) {
- SafeLogger.error('Error voting:', error);
}
}
@@ -1781,6 +2000,7 @@ function clearAllFilters() {
// Update UI
updateActiveTopicUI();
+ updateFilterStatusBar();
// Reset filter chips
document.querySelectorAll('.ldr-time-filter-group .ldr-filter-btn').forEach(chip => {
@@ -2233,6 +2453,9 @@ async function runNewsSemanticSearch(query) {
semanticContainer.appendChild(createCard(result, NEWS_CARD_CONFIG, query));
}
} catch (error) {
+ // A superseded request must not replace the newer search results with
+ // its late network error.
+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.SEMANTIC) return;
SafeLogger.error('Semantic search error:', error);
semanticContainer.innerHTML = '<div class="ldr-empty-state"><p>Error performing semantic search.</p></div>';
}
@@ -2246,18 +2469,22 @@ async function runNewsHybridSearch(query) {
const existingIndicator = document.getElementById('news-hybrid-loading');
if (existingIndicator) existingIndicator.remove();
+ let loadingIndicator = null;
if (feedContent) {
const loadingDiv = document.createElement('div');
loadingDiv.className = 'ldr-hybrid-loading';
loadingDiv.id = 'news-hybrid-loading';
loadingDiv.innerHTML = '<div class="ldr-spinner" style="width: 16px; height: 16px; border-width: 2px;"></div> Searching content...';
feedContent.appendChild(loadingDiv);
+ loadingIndicator = loadingDiv;
}
+ const removeLoadingIndicator = () => {
+ if (loadingIndicator && loadingIndicator.isConnected) loadingIndicator.remove();
+ };
try {
if (!newsCollectionId) {
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
return;
}
@@ -2276,21 +2503,18 @@ async function runNewsHybridSearch(query) {
// Stale guard
if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.HYBRID) {
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
return;
}
if (!resp.ok) {
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
return;
}
const data = await resp.json();
if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.HYBRID) {
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
return;
}
@@ -2301,8 +2525,7 @@ async function runNewsHybridSearch(query) {
// Build tiered results
const buildTiered = window.SemanticSearch && window.SemanticSearch.buildTieredResults;
if (!buildTiered) {
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
return;
}
@@ -2328,8 +2551,7 @@ async function runNewsHybridSearch(query) {
renderNewsItems(query);
// Remove loading indicator
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
+ removeLoadingIndicator();
// Tier 3: semantic-only results not in current feed
if (tiered.tier3.length > 0 && feedContent) {
@@ -2346,9 +2568,9 @@ async function runNewsHybridSearch(query) {
}
}
} catch (error) {
+ removeLoadingIndicator();
+ if (currentId !== newsSearchId || newsSearchMode !== NEWS_SM.HYBRID) return;
SafeLogger.error('Hybrid search error:', error);
- const indicator = document.getElementById('news-hybrid-loading');
- if (indicator) indicator.remove();
}
}
@@ -2439,9 +2661,145 @@ function updateRefreshIndicator() {
}
}
+function stopNewsResearchPoll(poll) {
+ if (!poll) return;
+
+ if (poll.interval !== null) {
+ clearInterval(poll.interval);
+ poll.interval = null;
+ }
+ if (poll.timeout !== null) {
+ clearTimeout(poll.timeout);
+ poll.timeout = null;
+ }
+ poll.requestInFlight = false;
+
+ if (activeNewsResearchPoll === poll) {
+ activeNewsResearchPoll = null;
+ }
+}
+
+function beginNewsResearchPoll(researchId) {
+ // Starting a run directly supersedes any page-load restoration request
+ // that captured an older localStorage entry.
+ newsResearchRestoreId++;
+ if (activeNewsResearchPoll) {
+ const supersededPoll = activeNewsResearchPoll;
+ stopNewsResearchPoll(supersededPoll);
+ clearStoredNewsResearch(supersededPoll.researchId);
+ removeNewsResearchCards(supersededPoll.researchId);
+ }
+ if (newsResearchReloadTimer !== null) {
+ clearTimeout(newsResearchReloadTimer);
+ newsResearchReloadTimer = null;
+ }
+
+ // A progress card now owns the feed surface, so an older feed response
+ // must not be allowed to replace it when that response finally arrives.
+ newsFeedRequestId++;
+
+ const poll = {
+ id: ++newsResearchPollId,
+ researchId: String(researchId),
+ feedRequestId: newsFeedRequestId,
+ interval: null,
+ timeout: null,
+ requestInFlight: false
+ };
+ activeNewsResearchPoll = poll;
+ return poll;
+}
+
+function isCurrentNewsResearchPoll(poll) {
+ return activeNewsResearchPoll === poll;
+}
+
+function clearStoredNewsResearch(researchId) {
+ const storedResearch = localStorage.getItem('active_news_research');
+ if (!storedResearch) return;
+
+ try {
+ const parsedResearch = JSON.parse(storedResearch);
+ if (String(parsedResearch.researchId) !== String(researchId)) return;
+ } catch {
+ // Malformed state cannot be resumed and should not survive a terminal
+ // polling path.
+ }
+
+ localStorage.removeItem('active_news_research');
+}
+
+function findNewsResearchCard(researchId) {
+ return Array.from(document.querySelectorAll('.ldr-active-research-card'))
+ .find(card => (
+ !card.dataset.researchId ||
+ String(card.dataset.researchId) === String(researchId)
+ )) || null;
+}
+
+function removeNewsResearchCards(researchId) {
+ document.querySelectorAll('.ldr-active-research-card').forEach(card => {
+ if (
+ !card.dataset.researchId ||
+ String(card.dataset.researchId) === String(researchId)
+ ) {
+ card.remove();
+ }
+ });
+}
+
+function endNewsResearchPollWithFeed(poll, message, type = 'error') {
+ if (!isCurrentNewsResearchPoll(poll)) return;
+
+ const explicitFeedOwnsSurface = (
+ newsFeedRequestId !== poll.feedRequestId &&
+ newsFeedRequestIntent === 'explicit'
+ );
+ stopNewsResearchPoll(poll);
+ clearStoredNewsResearch(poll.researchId);
+ removeNewsResearchCards(poll.researchId);
+ showAlert(message, type);
+ if (!explicitFeedOwnsSurface) loadNewsFeed();
+}
+
+function completeNewsResearchPoll(poll, message) {
+ if (!isCurrentNewsResearchPoll(poll)) return;
+
+ const explicitFeedOwnsSurface = (
+ newsFeedRequestId !== poll.feedRequestId &&
+ newsFeedRequestIntent === 'explicit'
+ );
+ stopNewsResearchPoll(poll);
+ clearStoredNewsResearch(poll.researchId);
+ removeNewsResearchCards(poll.researchId);
+ showAlert(message, 'success');
+
+ const completedPollId = poll.id;
+ const completedFeedRequestId = newsFeedRequestId;
+ newsResearchReloadTimer = setTimeout(() => {
+ newsResearchReloadTimer = null;
+ if (
+ !explicitFeedOwnsSurface &&
+ newsResearchPollId === completedPollId &&
+ newsFeedRequestId === completedFeedRequestId &&
+ !activeNewsResearchPoll
+ ) {
+ loadNewsFeed();
+ }
+ }, 1000);
+}
+
// Monitor a specific research by ID
async function monitorResearch(researchId, query = null) {
SafeLogger.log('Monitoring research:', researchId);
+ const poll = beginNewsResearchPoll(researchId);
+ poll.timeout = setTimeout(() => {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Research monitoring timed out. Please try again.',
+ 'warning'
+ );
+ }, 5 * 60 * 1000);
// Store in localStorage so it persists across page loads
localStorage.setItem('active_news_research', JSON.stringify({
@@ -2453,162 +2811,238 @@ async function monitorResearch(researchId, query = null) {
// First, get the initial status and query
try {
const statusResponse = await fetch(URLBuilder.researchStatus(researchId));
- if (statusResponse.ok) {
- const statusData = await statusResponse.json();
- query ||= statusData.query || 'News Analysis';
+ if (!isCurrentNewsResearchPoll(poll)) return;
+ if (!statusResponse.ok) {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Failed to check research status. Please try again.'
+ );
+ return;
+ }
- // Show the progress card immediately
- const container = document.getElementById('news-feed-content');
- const progressCard = document.querySelector(`[data-research-id="${researchId}"]`);
+ const statusData = await statusResponse.json();
+ if (!isCurrentNewsResearchPoll(poll)) return;
- if (!progressCard) {
- // Create new progress card at the top
- const newCard = document.createElement('div');
- newCard.className = 'ldr-news-card ldr-priority-high ldr-active-research-card';
- newCard.setAttribute('data-research-id', researchId);
- // bearer:disable javascript_lang_dangerous_insert_html
- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
- newCard.innerHTML = `
- <div class="ldr-news-header">
- <h2 class="ldr-news-title">
- <i class="bi bi-hourglass-split ldr-spinning"></i>
- Analyzing: "${escapeHtml(query.substring(0, 60))}..."
- </h2>
- </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> ${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">
- <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: ${Number(statusData.progress) || 10}%"></div>
- </div>
- <p class="mt-2">${escapeHtml(statusData.message || 'Searching for breaking news and analyzing importance...')}</p>
+ if (ResearchStates.isCompleted(statusData.status)) {
+ completeNewsResearchPoll(
+ poll,
+ 'Test run completed! Loading results...'
+ );
+ return;
+ }
+ if (ResearchStates.isTerminal(statusData.status)) {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Test run failed. Please check your configuration and try again.'
+ );
+ return;
+ }
+
+ query ||= statusData.query || 'News Analysis';
+
+ // Show the progress card immediately
+ const container = document.getElementById('news-feed-content');
+ const progressCard = findNewsResearchCard(researchId);
+
+ if (!progressCard) {
+ // Create new progress card at the top
+ const newCard = document.createElement('div');
+ newCard.className = 'ldr-news-card ldr-priority-high ldr-active-research-card';
+ newCard.setAttribute('data-research-id', researchId);
+ // bearer:disable javascript_lang_dangerous_insert_html
+ // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings
+ newCard.innerHTML = `
+ <div class="ldr-news-header">
+ <h2 class="ldr-news-title">
+ <i class="bi bi-hourglass-split ldr-spinning"></i>
+ Analyzing: "${escapeHtml(query.substring(0, 60))}..."
+ </h2>
+ </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> ${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">
+ <div class="progress-bar progress-bar-striped progress-bar-animated" style="width: ${Number(statusData.progress) || 10}%"></div>
</div>
- `;
+ <p class="mt-2">${escapeHtml(statusData.message || 'Searching for breaking news and analyzing importance...')}</p>
+ </div>
+ `;
- // Insert at the beginning
- if (container.firstChild) {
- container.insertBefore(newCard, container.firstChild);
- } else {
- container.appendChild(newCard);
- }
+ // Insert at the beginning
+ if (container.firstChild) {
+ container.insertBefore(newCard, container.firstChild);
+ } else {
+ container.appendChild(newCard);
}
}
} catch (error) {
+ if (!isCurrentNewsResearchPoll(poll)) return;
SafeLogger.error('Error getting initial status:', error);
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Error checking research status. Please try again.'
+ );
+ return;
}
// Now start polling for updates
- const checkInterval = setInterval(async () => {
+ poll.interval = setInterval(async () => {
+ if (!isCurrentNewsResearchPoll(poll) || poll.requestInFlight) return;
+ poll.requestInFlight = true;
+
try {
const response = await fetch(URLBuilder.researchStatus(researchId));
- if (response.ok) {
- const data = await response.json();
- SafeLogger.log('Research status:', data.status, 'Progress:', data.progress);
-
- // Update progress card
- const progressCard = document.querySelector(`[data-research-id="${researchId}"]`);
- if (progressCard && ResearchStates.isInProgress(data.status)) {
- const progressValue = data.progress || 10;
- // Update ARIA on container and width on fill
- const progressContainer = progressCard.querySelector('[role="progressbar"]');
- if (progressContainer) {
- progressContainer.setAttribute('aria-valuenow', progressValue);
- const progressFill = progressContainer.firstElementChild;
- if (progressFill) {
- progressFill.style.width = `${progressValue}%`;
- }
- }
- const progressText = progressCard.querySelector('.ldr-news-summary p');
- if (progressText && data.message) {
- progressText.textContent = data.message;
- }
- }
-
- if (ResearchStates.isCompleted(data.status)) {
- clearInterval(checkInterval);
- localStorage.removeItem('active_news_research'); // Clear from localStorage
- SafeLogger.log('Research completed, reloading news feed');
+ if (!isCurrentNewsResearchPoll(poll)) return;
+ if (!response.ok) {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Failed to check research status. Please try again.'
+ );
+ return;
+ }
- // Remove the progress card
- const card = document.querySelector(`[data-research-id="${researchId}"]`);
- if (card) {
- card.remove();
- }
+ const data = await response.json();
+ if (!isCurrentNewsResearchPoll(poll)) return;
+ SafeLogger.log('Research status:', data.status, 'Progress:', data.progress);
- // Show success message
- showAlert('Test run completed! Loading results...', 'success');
-
- // Reload the news feed to show the completed research
- // The backend should now include it because it has is_news_search metadata
- setTimeout(() => {
- loadNewsFeed();
- }, 1000);
- } else if (ResearchStates.isFailed(data.status)) {
- clearInterval(checkInterval);
- localStorage.removeItem('active_news_research'); // Clear from localStorage
- // Remove progress card
- const card = document.querySelector(`[data-research-id="${researchId}"]`);
- if (card) {
- card.remove();
+ // Update progress card
+ const progressCard = findNewsResearchCard(researchId);
+ if (progressCard && ResearchStates.isInProgress(data.status)) {
+ const progressValue = data.progress || 10;
+ // Update ARIA on container and width on fill
+ const progressContainer = progressCard.querySelector('[role="progressbar"]');
+ if (progressContainer) {
+ progressContainer.setAttribute('aria-valuenow', progressValue);
+ const progressFill = progressContainer.firstElementChild;
+ if (progressFill) {
+ progressFill.style.width = `${progressValue}%`;
}
- showAlert('Test run failed. Please check your configuration and try again.', 'error');
}
+ const progressText = progressCard.querySelector('.ldr-news-summary p');
+ if (progressText && data.message) {
+ progressText.textContent = data.message;
+ }
+ }
+
+ if (ResearchStates.isCompleted(data.status)) {
+ SafeLogger.log('Research completed, reloading news feed');
+ completeNewsResearchPoll(
+ poll,
+ 'Test run completed! Loading results...'
+ );
+ } else if (ResearchStates.isTerminal(data.status)) {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Test run failed. Please check your configuration and try again.'
+ );
}
} catch (error) {
+ if (!isCurrentNewsResearchPoll(poll)) return;
SafeLogger.error('Error checking research status:', error);
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Error checking research status. Please try again.'
+ );
+ } finally {
+ poll.requestInFlight = false;
}
}, 3000); // Check every 3 seconds
- // Stop checking after 5 minutes
- setTimeout(() => {
- clearInterval(checkInterval);
- }, 5 * 60 * 1000);
}
// Check for active news research on page load
async function checkActiveNewsResearch() {
+ const restoreId = ++newsResearchRestoreId;
+ const storedSnapshot = localStorage.getItem('active_news_research');
+ let restoreTimeout = null;
+ let restoreTimedOut = false;
+ const ownsStoredSnapshot = () => (
+ restoreId === newsResearchRestoreId &&
+ localStorage.getItem('active_news_research') === storedSnapshot
+ );
+
try {
// Check localStorage for active news research
- const activeResearch = localStorage.getItem('active_news_research');
- if (!activeResearch) return;
+ if (!storedSnapshot) return;
+
+ const { researchId, query, startTime } = JSON.parse(storedSnapshot);
- const { researchId, query, startTime } = JSON.parse(activeResearch);
+ // initializeNewsPage may already have started this exact run from
+ // sessionStorage. Do not replace its live poll with a redundant resume.
+ if (
+ activeNewsResearchPoll &&
+ String(activeNewsResearchPoll.researchId) === String(researchId)
+ ) return;
// Check if research is still recent (within 10 minutes)
const elapsed = Date.now() - new Date(startTime).getTime();
if (elapsed > 10 * 60 * 1000) {
- localStorage.removeItem('active_news_research');
+ if (ownsStoredSnapshot()) clearStoredNewsResearch(researchId);
return;
}
// Check research status
- const statusResponse = await fetch(URLBuilder.researchStatus(researchId));
+ const restoreController = new AbortController();
+ const timeoutPromise = new Promise((_, reject) => {
+ restoreTimeout = setTimeout(() => {
+ restoreTimedOut = true;
+ restoreController.abort();
+ const timeoutError = new Error('Active research status timed out');
+ timeoutError.name = 'AbortError';
+ reject(timeoutError);
+ }, 10000);
+ });
+ const statusResponse = await Promise.race([
+ fetch(URLBuilder.researchStatus(researchId), {
+ signal: restoreController.signal
+ }),
+ timeoutPromise
+ ]);
+ if (!ownsStoredSnapshot()) return;
if (!statusResponse.ok) {
- localStorage.removeItem('active_news_research');
+ clearStoredNewsResearch(researchId);
return;
}
- const status = await statusResponse.json();
-
- if (ResearchStates.isInProgress(status.status)) {
- // Use monitorResearch to show the progress card and handle polling
+ // Keep the same wall-clock deadline active while the response body is
+ // consumed. fetch() resolves when headers arrive, so clearing the
+ // timer before json() would let a stalled body block page bootstrap.
+ const status = await Promise.race([
+ statusResponse.json(),
+ timeoutPromise
+ ]);
+ clearTimeout(restoreTimeout);
+ restoreTimeout = null;
+ if (!ownsStoredSnapshot()) return;
+
+ if (ResearchStates.isActive(status.status)) {
+ // Monitoring owns its own timeout and terminal cleanup. Do not
+ // make the rest of page initialization wait for its first status
+ // request, which may be slow or never settle.
monitorResearch(researchId, query);
} else if (ResearchStates.isCompleted(status.status)) {
// Research completed while user was away
- localStorage.removeItem('active_news_research');
+ clearStoredNewsResearch(researchId);
showAlert('Your news analysis has completed! Loading results...', 'success');
// Reload the feed to show the results
await loadNewsFeed();
} else {
// Research failed or was cancelled
- localStorage.removeItem('active_news_research');
+ clearStoredNewsResearch(researchId);
}
} catch (error) {
+ if (!ownsStoredSnapshot()) return;
+ if (restoreTimedOut || error?.name === 'AbortError') {
+ SafeLogger.warn('Timed out checking active research; keeping it for a later retry');
+ return;
+ }
SafeLogger.error('Error checking active research:', error);
localStorage.removeItem('active_news_research');
+ } finally {
+ if (restoreTimeout !== null) clearTimeout(restoreTimeout);
}
}
@@ -2616,6 +3050,14 @@ async function checkActiveNewsResearch() {
async function pollForNewsResearchResults(researchId, originalQuery, isResume = false) {
let pollCount = 0;
const maxPolls = 60; // 5 minutes max
+ const poll = beginNewsResearchPoll(researchId);
+ poll.timeout = setTimeout(() => {
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Research taking too long. Check the progress page.',
+ 'warning'
+ );
+ }, 5 * 60 * 1000);
// Store active research in localStorage
if (!isResume) {
@@ -2626,20 +3068,27 @@ async function pollForNewsResearchResults(researchId, originalQuery, isResume =
}));
}
- const pollInterval = setInterval(async () => {
+ poll.interval = setInterval(async () => {
+ if (!isCurrentNewsResearchPoll(poll) || poll.requestInFlight) return;
+ poll.requestInFlight = true;
+
try {
// Check research status
const statusResponse = await fetch(URLBuilder.researchStatus(researchId));
+ if (!isCurrentNewsResearchPoll(poll)) return;
if (!statusResponse.ok) {
- clearInterval(pollInterval);
- showAlert('Failed to check research status', 'error');
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Failed to check research status. Please try again.'
+ );
return;
}
const status = await statusResponse.json();
+ if (!isCurrentNewsResearchPoll(poll)) return;
// Update progress bar (scoped to the active research card)
- const activeCard = document.querySelector('.ldr-active-research-card');
+ const activeCard = findNewsResearchCard(researchId);
if (activeCard) {
const progressValue = status.progress || 10;
// Update ARIA on container and width on fill
@@ -2654,39 +3103,36 @@ async function pollForNewsResearchResults(researchId, originalQuery, isResume =
}
if (ResearchStates.isCompleted(status.status)) {
- clearInterval(pollInterval);
- localStorage.removeItem('active_news_research');
-
- // Remove any progress card
- const progressCards = document.querySelectorAll('.ldr-active-research-card');
- progressCards.forEach(card => card.remove());
-
- // Show success and reload feed
- showAlert('News analysis completed! Loading results...', 'success');
-
- // Reload the news feed after a short delay
- // The backend should now include the completed research
- setTimeout(() => {
- loadNewsFeed();
- }, 1000);
+ completeNewsResearchPoll(
+ poll,
+ 'News analysis completed! Loading results...'
+ );
+ return;
} 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');
- loadNewsFeed(); // Reload normal feed
+ endNewsResearchPollWithFeed(
+ poll,
+ `Research ${status.status}: ${status.metadata?.error || 'Unknown error'}`
+ );
+ return;
}
pollCount++;
if (pollCount >= maxPolls) {
- clearInterval(pollInterval);
- localStorage.removeItem('active_news_research');
- showAlert('Research taking too long. Check the progress page.', 'warning');
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Research taking too long. Check the progress page.',
+ 'warning'
+ );
}
} catch (error) {
+ if (!isCurrentNewsResearchPoll(poll)) return;
SafeLogger.error('Error polling for results:', error);
- clearInterval(pollInterval);
- localStorage.removeItem('active_news_research');
- showAlert('Error checking research status', 'error');
+ endNewsResearchPollWithFeed(
+ poll,
+ 'Error checking research status. Please try again.'
+ );
+ } finally {
+ poll.requestInFlight = false;
}
}, 5000); // Poll every 5 seconds
}
@@ -2695,6 +3141,13 @@ async function pollForNewsResearchResults(researchId, originalQuery, isResume =
// Search history functions
async function loadSearchHistory() {
+ const loadRequestId = ++searchHistoryLoadRequestId;
+ const loadGeneration = searchHistoryMutationGeneration;
+ const ownsLoad = () => (
+ loadRequestId === searchHistoryLoadRequestId &&
+ loadGeneration === searchHistoryMutationGeneration
+ );
+
try {
SafeLogger.log('Loading search history from /news/api/search-history');
const response = await fetch('/news/api/search-history', {
@@ -2705,11 +3158,13 @@ async function loadSearchHistory() {
'X-CSRFToken': getCSRFToken()
}
});
+ if (!ownsLoad()) return;
SafeLogger.log('Search history response status:', response.status);
SafeLogger.log('Search history response headers:', response.headers);
if (response.ok) {
const data = await response.json();
+ if (!ownsLoad()) return;
SafeLogger.log('Search history data:', data);
searchHistory = data.search_history || [];
displayRecentSearches();
@@ -2721,11 +3176,13 @@ async function loadSearchHistory() {
} else {
SafeLogger.error('Unexpected response status:', response.status);
const text = await response.text();
+ if (!ownsLoad()) return;
SafeLogger.error('Response text:', text);
searchHistory = [];
displayRecentSearches();
}
} catch (e) {
+ if (!ownsLoad()) return;
SafeLogger.error('Failed to load search history:', e);
searchHistory = [];
displayRecentSearches();
@@ -2733,6 +3190,10 @@ async function loadSearchHistory() {
}
async function saveSearchHistory(query, type, resultCount) {
+ const previousWrite = searchHistoryWriteQueue;
+ let releaseWrite;
+ searchHistoryWriteQueue = new Promise(resolve => { releaseWrite = resolve; });
+ await previousWrite;
try {
SafeLogger.log('Saving search history:', { query, type, resultCount });
const response = await fetch('/news/api/search-history', {
@@ -2753,6 +3214,8 @@ async function saveSearchHistory(query, type, resultCount) {
SafeLogger.log('Save search history data:', data);
} catch (e) {
SafeLogger.error('Failed to save search history:', e);
+ } finally {
+ releaseWrite();
}
}
@@ -2780,7 +3243,7 @@ function displayRecentSearches() {
item.type === 'table' ? 'bi-table' : 'bi-search';
return `
- <div class="ldr-recent-search-item" onclick="rerunSearch('${escapeAttr(item.query)}', '${escapeAttr(item.type)}')">
+ <div class="ldr-recent-search-item" data-news-page-action="rerun-search" data-query="${escapeHtml(item.query)}" data-search-type="${escapeHtml(item.type || 'quick')}">
<i class="bi ${typeIcon}"></i>
<div class="flex-grow-1">
<div class="ldr-search-query">${escapeHtml(item.query)}</div>
@@ -2804,6 +3267,12 @@ function rerunSearch(query, _type = 'quick') {
async function clearSearchHistory() {
if (!confirm('Clear all search history?')) return;
+ // Reserve the write slot at click time: older inserts finish before this
+ // delete, and searches started afterwards are saved after it.
+ const previousWrite = searchHistoryWriteQueue;
+ let releaseWrite;
+ searchHistoryWriteQueue = new Promise(resolve => { releaseWrite = resolve; });
+ await previousWrite;
try {
const response = await fetch('/news/api/search-history', {
method: 'DELETE',
@@ -2814,6 +3283,9 @@ async function clearSearchHistory() {
});
if (response.ok) {
+ // A response captured before this destructive mutation must not be
+ // able to restore rows that the server has just deleted.
+ searchHistoryMutationGeneration++;
searchHistory = [];
displayRecentSearches();
showAlert('Search history cleared', 'success');
@@ -2823,6 +3295,8 @@ async function clearSearchHistory() {
} catch (e) {
SafeLogger.error('Failed to clear search history:', e);
showAlert('Failed to clear search history', 'danger');
+ } finally {
+ releaseWrite();
}
}
@@ -2952,11 +3426,29 @@ function collapseAll() {
}
// Share and export functions
+function getNewsItemUrl(item) {
+ const fallbackPath = `/results/${encodeURIComponent(item.research_id)}`;
+ if (!item.source_url) {
+ return new URL(fallbackPath, window.location.origin).href;
+ }
+
+ try {
+ const url = new URL(item.source_url, window.location.origin);
+ if (url.protocol === 'http:' || url.protocol === 'https:') {
+ return url.href;
+ }
+ } catch {
+ // Invalid and unsafe source URLs fall back to the internal report.
+ }
+
+ return new URL(fallbackPath, window.location.origin).href;
+}
+
function shareNews(newsId) {
const item = newsItems.find(n => n.id === newsId);
if (!item) return;
- const shareUrl = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ const shareUrl = getNewsItemUrl(item);
const shareText = `${item.headline}\n\n${shareUrl}`;
if (navigator.share) {
@@ -2982,7 +3474,7 @@ function copyNewsLink(newsId) {
const item = newsItems.find(n => n.id === newsId);
if (!item) return;
- const url = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ const url = getNewsItemUrl(item);
copyToClipboard(url);
}
@@ -3009,7 +3501,7 @@ function exportToMarkdown(newsId) {
markdown += `## Sources\n\n${item.links.map(l => `- [${l.title}](${l.url})`).join('\n')}\n\n`;
}
- const url = window.location.origin + (item.source_url || `/results/${item.research_id}`);
+ const url = getNewsItemUrl(item);
markdown += `\n[View Full Report](${url})`;
// Create and download file
@@ -3625,9 +4117,15 @@ function showNewsSubscriptionModal(query = '', templateName = '') {
async function handleNewsSubscriptionSubmit(e) {
e.preventDefault();
+ // The submit button is not the only way this handler can be reached, and
+ // disabling it does not stop a second programmatic/keyboard submit. Keep
+ // one owner for the complete create -> optional immediate-run workflow so
+ // a rapid re-entry cannot create duplicate subscriptions or runs.
+ if (activeNewsSubscriptionSubmit !== null) return;
+
const query = document.getElementById('news-subscription-query').value;
const name = document.getElementById('news-subscription-name').value || query.substring(0, 50);
- const frequency = document.getElementById('news-subscription-frequency').value;
+ const frequencyHours = document.getElementById('news-subscription-frequency').value;
const folder = document.getElementById('news-subscription-folder').value;
const isActive = document.getElementById('news-subscription-active').checked;
const runNow = document.getElementById('news-subscription-run-now').checked;
@@ -3644,6 +4142,13 @@ async function handleNewsSubscriptionSubmit(e) {
}
const searchStrategy = document.getElementById('news-subscription-strategy').value;
+ const submitButton = document.querySelector(
+ '#news-subscription-form button[type="submit"]'
+ );
+ const submitButtonWasDisabled = submitButton ? submitButton.disabled : false;
+ const submitOwnership = {};
+ activeNewsSubscriptionSubmit = submitOwnership;
+ if (submitButton) submitButton.disabled = true;
try {
// Create the subscription
@@ -3657,7 +4162,8 @@ async function handleNewsSubscriptionSubmit(e) {
query,
name,
subscription_type: 'search',
- refresh_minutes: parseInt(frequency, 10),
+ // The modal presents hours, while the API contract is minutes.
+ refresh_minutes: parseInt(frequencyHours, 10) * 60,
folder_id: folder || null,
is_active: isActive,
model_provider: modelProvider,
@@ -3687,14 +4193,21 @@ async function handleNewsSubscriptionSubmit(e) {
if (runResponse.ok) {
const runData = await runResponse.json();
-
- if (runData.research_id) {
+ const researchId = runData?.research_id;
+ const hasResearchId = (
+ researchId !== undefined &&
+ researchId !== null &&
+ String(researchId).trim() !== ''
+ );
+
+ if (hasResearchId) {
showAlert('Subscription research started...', 'info');
// Show loading state in news feed with progress visualization
const container = document.getElementById('news-feed-content');
const progressCard = document.createElement('div');
progressCard.className = 'ldr-news-card ldr-priority-high ldr-active-research-card';
+ progressCard.setAttribute('data-research-id', researchId);
// bearer:disable javascript_lang_dangerous_insert_html
progressCard.innerHTML = `
<div class="ldr-news-header">
@@ -3704,7 +4217,7 @@ async function handleNewsSubscriptionSubmit(e) {
</h2>
</div>
<div class="ldr-news-meta">
- <span><i class="bi bi-info-circle"></i> Research ID: ${escapeHtml(runData.research_id)}</span>
+ <span><i class="bi bi-info-circle"></i> Research ID: ${escapeHtml(researchId)}</span>
<span><i class="bi bi-clock"></i> Started just now</span>
</div>
<div class="ldr-news-summary">
@@ -3719,13 +4232,18 @@ async function handleNewsSubscriptionSubmit(e) {
container.insertBefore(progressCard, container.firstChild);
// Poll for results
- pollForNewsResearchResults(runData.research_id, query);
+ 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');
}
} else {
SafeLogger.error('Failed to run subscription immediately');
+ showAlert('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');
}
}
@@ -3738,6 +4256,11 @@ async function handleNewsSubscriptionSubmit(e) {
} catch (error) {
SafeLogger.error('Error creating subscription:', error);
showAlert('Failed to create subscription', 'danger');
+ } finally {
+ if (activeNewsSubscriptionSubmit === submitOwnership) {
+ activeNewsSubscriptionSubmit = null;
+ if (submitButton) submitButton.disabled = submitButtonWasDisabled;
+ }
}
}
@@ -3870,6 +4393,7 @@ window.selectSubscription = selectSubscription;
window.showCreateSubscriptionModal = showCreateSubscriptionModal;
window.createSubscription = createSubscription;
window.createSubscriptionFromItem = createSubscriptionFromItem;
+window.handleNewsSubscriptionSubmit = handleNewsSubscriptionSubmit;
// Exposed for test harness: lets XSS-regression tests drive a single render
// cycle with a controlled newsItems payload without going through the full
// DOMContentLoaded -> initializeNewsPage chain.
@@ -3877,3 +4401,6 @@ window.loadNewsFeed = loadNewsFeed;
// Exposed for test harness: lets the search-history XSS-regression test
// drive a single render cycle with a controlled payload.
window.loadSearchHistory = loadSearchHistory;
+// The checked-in template invokes this action from its Clear All control;
+// assigning it explicitly also lets the direct runtime test pin that contract.
+window.clearSearchHistory = clearSearchHistory;
diff --git a/src/local_deep_research/web/static/js/pages/note-detail.js b/src/local_deep_research/web/static/js/pages/note-detail.js
index 32364142ad..ca3743ca05 100644
--- a/src/local_deep_research/web/static/js/pages/note-detail.js
+++ b/src/local_deep_research/web/static/js/pages/note-detail.js
@@ -1379,6 +1379,7 @@ function renderSidebarLoadError(containerId, message, retryFn) {
* Load note research history
*/
async function loadNoteResearch() {
+ const orderIntent = _latestResearchOrderIntent;
try {
const response = await safeFetchWithAuth(`/notes/api/notes/${note.id}/research`, {
credentials: 'same-origin'
@@ -1386,6 +1387,10 @@ async function loadNoteResearch() {
const data = await response.json();
+ // A newer drop may occur while a failure-recovery GET is pending.
+ // Neither that response nor its error owns the newer visible order.
+ if (orderIntent !== _latestResearchOrderIntent) return;
+
if (data.success) {
noteResearch = data.research || [];
renderNoteResearch();
@@ -1393,6 +1398,7 @@ async function loadNoteResearch() {
renderSidebarLoadError('research-list', "Couldn't load research", loadNoteResearch);
}
} catch (error) {
+ if (orderIntent !== _latestResearchOrderIntent) return;
SafeLogger.error('Error loading note research:', error);
renderSidebarLoadError('research-list', "Couldn't load research", loadNoteResearch);
}
@@ -1534,6 +1540,8 @@ async function toggleResearchCollapsed(itemEl) {
* HTML5 drag-and-drop handlers for reordering research items.
*/
let _dragSourceEl = null;
+let _researchOrderWriteQueue = Promise.resolve();
+let _latestResearchOrderIntent = 0;
function attachResearchDragHandlers(itemEl) {
itemEl.addEventListener('dragstart', (e) => {
@@ -1588,38 +1596,51 @@ function attachResearchDragHandlers(itemEl) {
async function persistResearchOrder() {
const container = document.getElementById('research-list');
- if (!container) return;
+ if (!container) return Promise.resolve();
const orderedIds = Array.from(
container.querySelectorAll('.ldr-research-item')
).map(el => el.dataset.researchId).filter(Boolean);
- if (orderedIds.length === 0) return;
+ if (orderedIds.length === 0) return Promise.resolve();
+
+ // Each drop captures its own order, then joins a serialized write queue.
+ // Fast consecutive drops must reach the server in user-intent order;
+ // otherwise an older slow request can commit after the newer request and
+ // resurrect the earlier arrangement on reload.
+ const intentId = ++_latestResearchOrderIntent;
+ const write = async () => {
+ try {
+ const response = await safeFetchWithAuth(
+ `/notes/api/notes/${note.id}/research/reorder`,
+ {
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': getCSRFToken(),
+ },
+ body: JSON.stringify({ research_ids: orderedIds }),
+ }
+ );
+ const data = await response.json();
+ if (!data.success) throw new Error(data.error || 'Failed');
- try {
- const response = await safeFetchWithAuth(
- `/notes/api/notes/${note.id}/research/reorder`,
- {
- method: 'POST',
- credentials: 'same-origin',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': getCSRFToken(),
- },
- body: JSON.stringify({ research_ids: orderedIds }),
- }
- );
- const data = await response.json();
- if (!data.success) throw new Error(data.error || 'Failed');
+ // Update local cache order. The DOM already reflects the drop.
+ noteResearch.sort(
+ (a, b) => orderedIds.indexOf(a.research_id) - orderedIds.indexOf(b.research_id)
+ );
+ } catch (error) {
+ SafeLogger.error('Error persisting research order:', error);
+ // An older failed intent must not roll back a newer queued drop.
+ // Only the latest intent owns the visible error and server reload.
+ if (intentId !== _latestResearchOrderIntent) return;
+ showNoteError('Failed to save new order');
+ await loadNoteResearch();
+ }
+ };
- // Update local cache order
- noteResearch.sort(
- (a, b) => orderedIds.indexOf(a.research_id) - orderedIds.indexOf(b.research_id)
- );
- } catch (error) {
- SafeLogger.error('Error persisting research order:', error);
- showNoteError('Failed to save new order');
- // Re-fetch to restore server state
- await loadNoteResearch();
- }
+ const queued = _researchOrderWriteQueue.then(write, write);
+ _researchOrderWriteQueue = queued;
+ return queued;
}
/**
@@ -4519,6 +4540,11 @@ if (typeof window !== 'undefined' && window.__VITEST_TEST__) {
viewVersion,
// Semantic-diff modal (compare version to current)
compareVersion,
+ resetDiffState: () => {
+ _diffInProgress = false;
+ _diffGeneration = 0;
+ _diffDismissWired = false;
+ },
// Passage-selection scoping
_selectionWithinNote,
// Pure / content helpers
@@ -4610,6 +4636,11 @@ if (typeof window !== 'undefined' && window.__VITEST_TEST__) {
// for their in-flight/revert races).
addSuggestedTag,
toggleResearchCollapsed,
+ // Drag/drop research ordering and serialized mutation ownership
+ renderNoteResearch,
+ persistResearchOrder,
+ setNoteResearch: (items) => { noteResearch = items; },
+ getNoteResearch: () => noteResearch,
bindEditorRefs: () => {
titleInput = document.getElementById('ldr-note-title');
contentEditor = document.getElementById('note-content');
diff --git a/src/local_deep_research/web/static/js/pages/subscriptions.js b/src/local_deep_research/web/static/js/pages/subscriptions.js
index ed1294d78a..ddc8e03c25 100644
--- a/src/local_deep_research/web/static/js/pages/subscriptions.js
+++ b/src/local_deep_research/web/static/js/pages/subscriptions.js
@@ -15,6 +15,11 @@ const currentFilter = {
const fetchOptions = {
credentials: 'same-origin'
};
+const runningSubscriptionIds = new Set();
+const subscriptionToggleIntents = new Map();
+let subscriptionsMutationGeneration = 0;
+let subscriptionsLoadRequestId = 0;
+let foldersLoadRequestId = 0;
// Format next update time correctly
function formatNextUpdate(dateString) {
@@ -95,14 +100,22 @@ function setupEventListeners() {
// Load subscriptions from API
async function loadSubscriptions() {
+ const loadRequestId = ++subscriptionsLoadRequestId;
+ const loadGeneration = subscriptionsMutationGeneration;
+ const ownsLoad = () => (
+ loadRequestId === subscriptionsLoadRequestId &&
+ loadGeneration === subscriptionsMutationGeneration
+ );
SafeLogger.log('Loading subscriptions...');
try {
const response = await fetch('/news/api/subscriptions/current', {
credentials: 'same-origin'
});
+ if (!ownsLoad()) return;
if (response.ok) {
const data = await response.json();
+ if (!ownsLoad()) return;
subscriptions = data.subscriptions || [];
SafeLogger.log('Loaded subscriptions:', subscriptions);
@@ -124,6 +137,7 @@ async function loadSubscriptions() {
showAlert('Failed to load subscriptions', 'error');
}
} catch (error) {
+ if (!ownsLoad()) return;
SafeLogger.error('Error loading subscriptions:', error);
showAlert('Failed to load subscriptions', 'error');
}
@@ -131,18 +145,24 @@ async function loadSubscriptions() {
// Load folders
async function loadFolders() {
+ const loadRequestId = ++foldersLoadRequestId;
+ const ownsLoad = () => loadRequestId === foldersLoadRequestId;
try {
const response = await fetch('/news/api/subscription/folders', {
credentials: 'same-origin'
});
+ if (!ownsLoad()) return;
+
if (response.ok) {
const data = await response.json();
+ if (!ownsLoad()) return;
folders = Array.isArray(data) ? data : (data.folders || []);
renderFolders();
} else {
SafeLogger.error('Failed to load folders:', response.status, response.statusText);
}
} catch (error) {
+ if (!ownsLoad()) return;
SafeLogger.error('Error loading folders:', error);
}
}
@@ -298,7 +318,9 @@ function filterSubscriptions() {
// Run subscription now - uses the same research system as news page
async function runSubscriptionNow(subscriptionId) {
const subscription = subscriptions.find(s => s.id === subscriptionId);
- if (!subscription) return;
+ if (!subscription || runningSubscriptionIds.has(subscriptionId)) return;
+
+ runningSubscriptionIds.add(subscriptionId);
try {
const query = subscription.query || subscription.query_or_topic || '';
@@ -364,18 +386,27 @@ async function runSubscriptionNow(subscriptionId) {
const errorData = await response.json().catch(() => ({}));
SafeLogger.error('Error data:', errorData);
// Safe: showAlert escapes internally
- showAlert(errorData.message || 'Failed to start research', 'error');
+ showAlert(
+ errorData.message || errorData.error || errorData.detail ||
+ 'Failed to start research',
+ 'error'
+ );
}
} catch (error) {
SafeLogger.error('Error running subscription:', error);
showAlert('Failed to start research', 'error');
+ } finally {
+ runningSubscriptionIds.delete(subscriptionId);
}
}
// Toggle subscription active/paused
async function toggleSubscription(subscriptionId) {
const subscription = subscriptions.find(s => s.id === subscriptionId);
- if (!subscription) return;
+ if (!subscription || subscriptionToggleIntents.has(subscriptionId)) return;
+
+ const intendedActiveState = !subscription.is_active;
+ subscriptionToggleIntents.set(subscriptionId, intendedActiveState);
try {
const response = await fetch(`/news/api/subscriptions/${subscriptionId}`, {
@@ -386,18 +417,28 @@ async function toggleSubscription(subscriptionId) {
'X-CSRFToken': getCSRFToken()
},
body: JSON.stringify({
- is_active: !subscription.is_active
+ is_active: intendedActiveState
})
});
- if (response.ok) {
- subscription.is_active = !subscription.is_active;
- renderSubscriptions();
- updateStats();
+ if (!response.ok) {
+ SafeLogger.error('Failed to toggle subscription:', response.status, response.statusText);
+ showAlert('Failed to update subscription', 'error');
+ return;
}
+
+ subscriptionsMutationGeneration += 1;
+ const currentSubscription = subscriptions.find(s => s.id === subscriptionId);
+ if (currentSubscription) currentSubscription.is_active = intendedActiveState;
+ renderSubscriptions();
+ updateStats();
} catch (error) {
SafeLogger.error('Error toggling subscription:', error);
showAlert('Failed to update subscription', 'error');
+ } finally {
+ if (subscriptionToggleIntents.get(subscriptionId) === intendedActiveState) {
+ subscriptionToggleIntents.delete(subscriptionId);
+ }
}
}
@@ -529,6 +570,10 @@ async function deleteSubscriptionDirect(subscriptionId) {
if (response.ok) {
showAlert('Subscription deleted successfully', 'success');
+ subscriptionsMutationGeneration += 1;
+ subscriptions = subscriptions.filter(s => s.id !== subscriptionId);
+ renderSubscriptions();
+ updateStats();
// Reload subscriptions
await loadSubscriptions();
} else {
@@ -748,6 +793,15 @@ function showSchedulerInfo() {
`, 'info');
}
+// Inline card actions are resolved through window in the browser. Assign
+// them explicitly so that contract remains intact if this file is later
+// loaded as a module (and so tests can drive the real page runtime).
+window.runSubscriptionNow = runSubscriptionNow;
+window.toggleSubscription = toggleSubscription;
+window.viewSubscriptionHistory = viewSubscriptionHistory;
+window.deleteSubscriptionDirect = deleteSubscriptionDirect;
+window.showSchedulerInfo = showSchedulerInfo;
+
// Exposed on window so vitest can exercise the pure formatting helper
// without standing up the full subscriptions page DOM.
window.formatNextUpdate = formatNextUpdate;
diff --git a/src/local_deep_research/web/static/js/pages/unified_search.js b/src/local_deep_research/web/static/js/pages/unified_search.js
index 0022906dd6..c79d7cd256 100644
--- a/src/local_deep_research/web/static/js/pages/unified_search.js
+++ b/src/local_deep_research/web/static/js/pages/unified_search.js
@@ -551,6 +551,7 @@ function renderUnifiedSearchResults(results) {
if (typeof window !== 'undefined' && window.__VITEST_TEST__) {
window.__unifiedSearchTest = {
SEARCH_MODE_REGISTRY,
+ UNIFIED_SEARCH_ACTIONS,
setupUnifiedSearchListeners,
runUnifiedSearch,
runKeywordMode,
diff --git a/src/local_deep_research/web/static/js/pdf_upload_handler.js b/src/local_deep_research/web/static/js/pdf_upload_handler.js
index 446d058e09..937abd56fa 100644
--- a/src/local_deep_research/web/static/js/pdf_upload_handler.js
+++ b/src/local_deep_research/web/static/js/pdf_upload_handler.js
@@ -415,7 +415,13 @@ class PDFUploadHandler {
*/
hideProcessing() {
const statusDiv = this.getOrCreateStatusDiv();
- statusDiv.style.display = 'none';
+ // uploadAndExtractPDFs() replaces the spinner with a terminal success
+ // or error message before its finally block runs. Only hide the
+ // in-flight indicator here so that terminal feedback remains visible
+ // for its own five-second timeout.
+ if (statusDiv.querySelector('.fa-spinner')) {
+ statusDiv.style.display = 'none';
+ }
}
/**
diff --git a/src/local_deep_research/web/static/js/research_form.js b/src/local_deep_research/web/static/js/research_form.js
index 45cd12c679..b4c8f96ed9 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -228,6 +228,8 @@ function clearAllWarnings() {
displayWarnings([]);
}
+let warningsRequestGeneration = 0;
+
// Make functions globally available for other scripts
window.refetchSettingsAndUpdateWarnings = refetchSettingsAndUpdateWarnings;
window.displayWarnings = displayWarnings;
@@ -238,9 +240,10 @@ window.checkAndDisplayWarnings = checkAndDisplayWarnings;
* Check warning conditions by fetching from backend
*/
function checkAndDisplayWarnings() {
+ const requestGeneration = ++warningsRequestGeneration;
// Get warnings from backend API instead of calculating locally
- fetch(URLS.SETTINGS_API.WARNINGS)
+ return fetch(URLS.SETTINGS_API.WARNINGS)
.then(response => {
if (!response.ok) {
throw new Error('Failed to fetch warnings');
@@ -248,6 +251,7 @@ function checkAndDisplayWarnings() {
return response.json();
})
.then(data => {
+ if (requestGeneration !== warningsRequestGeneration) return;
if (data && data.warnings) {
displayWarnings(data.warnings);
} else {
@@ -255,6 +259,7 @@ function checkAndDisplayWarnings() {
}
})
.catch(_error => {
+ if (requestGeneration !== warningsRequestGeneration) return;
// Clear warnings on error
displayWarnings([]);
});
@@ -298,7 +303,7 @@ function displayWarnings(warnings) {
// non-dismissible; rendering the button would call dismissWarning('null')
// and POST a bogus "null" settings key.
const dismissHtml = warning.dismissKey
- ? `<button onclick="dismissWarning('${esc(warning.dismissKey)}')" style="
+ ? `<button type="button" class="ldr-warning-dismiss" data-dismiss-key="${esc(warning.dismissKey)}" style="
background: none;
border: none;
color: inherit;
@@ -336,39 +341,54 @@ function displayWarnings(warnings) {
// bearer:disable javascript_lang_dangerous_insert_html
// eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: variable built from escaped/numeric values above
alertContainer.innerHTML = warningsHtml;
+ // Bind dismissals without inline JavaScript. HTML escaping alone is not a
+ // JavaScript-string escape, so putting an API-provided key inside onclick
+ // would make quote handling fragile even though the visible HTML is safe.
+ alertContainer.querySelectorAll('.ldr-warning-dismiss[data-dismiss-key]').forEach(button => {
+ button.addEventListener('click', () => dismissWarning(button.dataset.dismissKey));
+ });
alertContainer.style.display = 'block';
}
/**
* Dismiss a warning by updating the setting
*/
-function dismissWarning(dismissKey) {
+async function dismissWarning(dismissKey) {
// Get CSRF token
const csrfToken = window.api ? window.api.getCsrfToken() : '';
// Update dismissal setting
- fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- 'X-CSRFToken': csrfToken
- },
- body: JSON.stringify({
- [dismissKey]: true
- })
- })
- .then(response => response.json())
- .then(_data => {
+ try {
+ const response = await fetch(URLS.SETTINGS_API.SAVE_ALL_SETTINGS, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': csrfToken
+ },
+ body: JSON.stringify({
+ [dismissKey]: true
+ })
+ });
+ const data = await response.json();
+ if (!response.ok || data.status !== 'success') {
+ throw new Error(
+ data.detail || data.message || data.error || 'Failed to dismiss warning'
+ );
+ }
// Update global settings cache
globalSettings[dismissKey] = { value: true };
// Recheck warnings
- checkAndDisplayWarnings();
- })
- .catch(_error => {
- });
+ return checkAndDisplayWarnings();
+ } catch (error) {
+ SafeLogger.error('Failed to dismiss warning:', error);
+ return undefined;
+ }
}
+// Explicit global contract for templates and direct browser-runtime tests.
+window.dismissWarning = dismissWarning;
+
/**
* Helper function to get settings
*/
diff --git a/src/local_deep_research/web/static/js/security/safe-fetch.js b/src/local_deep_research/web/static/js/security/safe-fetch.js
index 0da1e5b48a..342cbaa5be 100644
--- a/src/local_deep_research/web/static/js/security/safe-fetch.js
+++ b/src/local_deep_research/web/static/js/security/safe-fetch.js
@@ -46,7 +46,10 @@ async function safeFetchWithAuth(url, options = {}) {
*/
class HTTPError extends Error {
constructor({ status, statusText, retryAfter, body, url }) {
- const detail = body && body.error ? body.error : statusText || `HTTP ${status}`;
+ // Flask-era endpoints commonly returned `{ error }`, while FastAPI
+ // uses `{ detail }` for HTTPException responses. Preserve the server's
+ // useful message across both envelopes during the migration.
+ const detail = body?.error || body?.detail || statusText || `HTTP ${status}`;
super(detail);
this.name = 'HTTPError';
this.status = status;
diff --git a/src/local_deep_research/web/static/js/security/url-validator.js b/src/local_deep_research/web/static/js/security/url-validator.js
index 2d87934f52..0a03ced735 100644
--- a/src/local_deep_research/web/static/js/security/url-validator.js
+++ b/src/local_deep_research/web/static/js/security/url-validator.js
@@ -111,25 +111,89 @@ const URLValidator = {
* Use this for any dynamic URL assignments
*/
safeAssign(element, property, url, options = {}) {
- // Special handling for internal navigation
- if (url && (url.startsWith('/') || url.startsWith('#'))) {
- element[property] = url;
- return true;
+ if (typeof url !== 'string') {
+ SafeLogger.warn('Blocked non-string URL assignment');
+ return false;
}
- // Special handling for blob and data URLs (safe for downloads)
- if (url && (url.startsWith('blob:') || url.startsWith('data:'))) {
- element[property] = url;
+ const normalizedUrl = url.trim();
+ if (!normalizedUrl) {
+ SafeLogger.warn('Blocked empty URL assignment');
+ return false;
+ }
+
+ // Special handling for fragment navigation, while preserving callers'
+ // explicit fragment policy.
+ if (normalizedUrl.startsWith('#')) {
+ if (options.allowFragments === false) {
+ SafeLogger.warn('Blocked fragment URL assignment');
+ return false;
+ }
+ element[property] = normalizedUrl;
return true;
}
+ // Anything without a literal scheme is intended to stay on this
+ // origin. Let the browser parser perform its C0-control and backslash
+ // normalization before enforcing that boundary. Checking every
+ // scheme-less value (rather than only strings beginning with '/')
+ // also catches inputs such as NUL + '//evil.test' and 'h<TAB>ttp:'.
+ const hasExplicitScheme = /^[a-z][a-z\d+.-]*:/i.test(normalizedUrl);
+ if (!hasExplicitScheme) {
+ try {
+ const parsed = new URL(normalizedUrl, window.location.href);
+ if (parsed.origin === window.location.origin) {
+ element[property] = normalizedUrl;
+ return true;
+ }
+ } catch (_error) {
+ // Fall through to the shared blocked-assignment warning.
+ }
+ SafeLogger.warn('Blocked ambiguous cross-origin URL assignment');
+ return false;
+ }
+
+ // Blob URLs are created by the current page for owned downloads. Keep
+ // them on anchor hrefs; they must never become a page-navigation sink.
+ if (normalizedUrl.startsWith('blob:')) {
+ const tagName = String(element?.tagName || '').toUpperCase();
+ if (property === 'href' && tagName === 'A') {
+ element[property] = normalizedUrl;
+ return true;
+ }
+ SafeLogger.warn('Blocked blob URL assignment outside a download link');
+ return false;
+ }
+
+ // Data URLs are unsafe for navigation (`data:text/html,...` can load
+ // attacker-controlled active content). The only production use is a
+ // raster image assigned to an <img> or favicon <link>, so keep that
+ // narrow target/MIME contract instead of bypassing isUnsafeScheme for
+ // every data URL.
+ if (/^data:/i.test(normalizedUrl)) {
+ const tagName = String(element?.tagName || '').toUpperCase();
+ const isImageTarget = property === 'src' && tagName === 'IMG';
+ const isFaviconTarget = property === 'href' && tagName === 'LINK' &&
+ String(element.rel || '').toLowerCase().split(/\s+/).includes('icon');
+ const isRasterImage = /^data:image\/(?:png|jpe?g|gif|webp|bmp|avif|x-icon);base64,/i
+ .test(normalizedUrl);
+
+ if (isRasterImage && (isImageTarget || isFaviconTarget)) {
+ element[property] = normalizedUrl;
+ return true;
+ }
+
+ SafeLogger.warn('Blocked unsafe data URL assignment');
+ return false;
+ }
+
// Validate external URLs
if (this.isSafeUrl(url, options)) {
element[property] = url;
return true;
}
- SafeLogger.warn(`Blocked unsafe URL assignment: ${url}`);
+ SafeLogger.warn('Blocked unsafe URL assignment:', url);
return false;
}
};
diff --git a/src/local_deep_research/web/static/js/services/api.js b/src/local_deep_research/web/static/js/services/api.js
index 84e2923399..ac6204bd43 100644
--- a/src/local_deep_research/web/static/js/services/api.js
+++ b/src/local_deep_research/web/static/js/services/api.js
@@ -80,9 +80,30 @@ function redirectToLogin() {
* @returns {Promise<any>} The parsed response data
*/
async function fetchWithErrorHandling(url, options = {}) {
- const { timeout = 30000, ...fetchOptions } = options;
+ const {
+ timeout = 30000,
+ signal: callerSignal,
+ ...fetchOptions
+ } = options;
const controller = new AbortController();
- const timeoutId = setTimeout(() => controller.abort(), timeout);
+ let abortCause = null;
+ const abortFromCaller = () => {
+ if (controller.signal.aborted) return;
+ abortCause = 'caller';
+ controller.abort(callerSignal?.reason);
+ };
+ if (callerSignal) {
+ if (callerSignal.aborted) {
+ abortFromCaller();
+ } else {
+ callerSignal.addEventListener('abort', abortFromCaller, { once: true });
+ }
+ }
+ const timeoutId = setTimeout(() => {
+ if (controller.signal.aborted) return;
+ abortCause = 'timeout';
+ controller.abort();
+ }, timeout);
try {
const csrfToken = getCsrfToken();
@@ -124,12 +145,21 @@ async function fetchWithErrorHandling(url, options = {}) {
return await response.json();
} catch (error) {
if (error.name === 'AbortError') {
- throw new Error('Request timed out');
+ if (abortCause === 'timeout') {
+ throw new Error('Request timed out');
+ }
+ // Caller-owned cancellation is expected control flow (for
+ // example, a newer request superseding an older one). Preserve
+ // the original AbortError without reporting it as an API failure.
+ if (abortCause === 'caller') {
+ throw error;
+ }
}
SafeLogger.error('API Error:', error);
throw error;
} finally {
clearTimeout(timeoutId);
+ callerSignal?.removeEventListener('abort', abortFromCaller);
}
}
diff --git a/src/local_deep_research/web/static/js/services/help.js b/src/local_deep_research/web/static/js/services/help.js
index 72d9183d9a..1102f8fb55 100644
--- a/src/local_deep_research/web/static/js/services/help.js
+++ b/src/local_deep_research/web/static/js/services/help.js
@@ -21,7 +21,7 @@ const HelpService = (function() {
const SETTINGS_API_BASE = '/settings/api/';
// Cache for dismissed panel states
- let dismissedCache = {};
+ const dismissedCache = {};
let initialized = false;
/**
@@ -196,6 +196,7 @@ const HelpService = (function() {
*/
async function resetDismissedPanels() {
const panels = document.querySelectorAll('.ldr-help-panel');
+ let failedCount = 0;
// Get CSRF token
const csrfToken = window.api ? window.api.getCsrfToken() : '';
@@ -209,27 +210,32 @@ const HelpService = (function() {
try {
// Delete from backend
const apiUrl = SETTINGS_API_BASE + encodeURIComponent(settingKey);
- await fetch(apiUrl, {
+ const response = await fetch(apiUrl, {
method: 'DELETE',
headers: {
'X-CSRFToken': csrfToken
}
});
+ if (!response.ok) {
+ throw new Error(`HTTP ${response.status}`);
+ }
+ delete dismissedCache[panelId];
+ panel.style.display = '';
} catch (e) {
+ failedCount++;
SafeLogger.warn('Failed to reset panel dismissal:', panelId, e);
}
}
- // Clear cache
- dismissedCache = {};
-
- // Show all hidden panels
- panels.forEach(panel => {
- panel.style.display = '';
- });
-
if (window.ui && window.ui.showMessage) {
- window.ui.showMessage('Help panels reset', 'success');
+ if (failedCount > 0) {
+ window.ui.showMessage(
+ `Could not reset ${failedCount} help panel${failedCount === 1 ? '' : 's'}`,
+ 'error'
+ );
+ } else {
+ window.ui.showMessage('Help panels reset', 'success');
+ }
}
}
diff --git a/src/local_deep_research/web/static/js/services/keyboard.js b/src/local_deep_research/web/static/js/services/keyboard.js
index 44e7f022af..81570b292a 100644
--- a/src/local_deep_research/web/static/js/services/keyboard.js
+++ b/src/local_deep_research/web/static/js/services/keyboard.js
@@ -95,6 +95,7 @@
const isTyping = activeElement && (
activeElement.tagName === 'INPUT' ||
activeElement.tagName === 'TEXTAREA' ||
+ activeElement.tagName === 'SELECT' ||
activeElement.contentEditable === 'true'
);
@@ -122,12 +123,20 @@
}
// Check each shortcut
- for (const [name, shortcut] of Object.entries(shortcuts)) {
+ // Resolve this per keypress so page-specific shortcuts returned by
+ // getAvailableShortcuts() (for example Enter on progress pages)
+ // are actually reachable, and newly registered shortcuts remain
+ // live without rebinding the document listener.
+ for (const [name, shortcut] of Object.entries(getAvailableShortcuts())) {
for (const pattern of shortcut.keys) {
if (matchesShortcut(event, pattern)) {
SafeLogger.log('Shortcut matched:', name, pattern);
+ const handled = shortcut.handler(event);
+ // Conditional shortcuts return false when their target
+ // is unavailable/unsafe. Do not swallow the browser's
+ // normal key behavior in that case.
+ if (handled === false) continue;
event.preventDefault();
- shortcut.handler(event);
return;
}
}
@@ -165,10 +174,11 @@
// same-origin validated on preceding line
// bearer:disable javascript_lang_open_redirect
window.location.href = viewBtn.href;
- } else {
- SafeLogger.error('Blocked non-same-origin redirect in keyboard shortcut');
+ return true;
}
+ SafeLogger.error('Blocked non-same-origin redirect in keyboard shortcut');
}
+ return false;
}
};
}
diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.js
index 19b44a60da..ffbbfbbb55 100644
--- a/src/local_deep_research/web/static/js/services/socket.js
+++ b/src/local_deep_research/web/static/js/services/socket.js
@@ -17,6 +17,15 @@ window.socket = (function() {
// Track if we're using polling fallback
let usingPolling = false;
+ let pollingResearchId = null;
+ let pollingGeneration = 0;
+ let pagePollingFallback = null;
+
+ // Pages with resource-specific or always-on polling retain ownership of
+ // it. The generic research endpoint is only a fallback for other callers.
+ function setPollingFallback(callback) {
+ pagePollingFallback = callback;
+ }
/**
* Initialize the Socket.IO connection
@@ -27,12 +36,13 @@ window.socket = (function() {
return socket;
}
- // Only initialize socket.io on research pages.
+ // Only initialize socket.io on research pages. The primary research
+ // form is served at `/`; `/research` is not a browser page.
// `/chat/` must include the trailing slash so we match the page
// route (e.g. `/chat/<session-id>`) but not API paths that happen
// to contain `/chat` as a substring (e.g. `/api/chat/sessions`).
const currentPath = window.location.pathname;
- const isResearchPage = currentPath.includes('/research') ||
+ const isResearchPage = currentPath === '/' ||
currentPath.includes('/progress') ||
currentPath.includes('/benchmark') ||
currentPath.includes('/chat/');
@@ -76,6 +86,8 @@ window.socket = (function() {
SafeLogger.log('Socket connected');
connectionAttempts = 0;
usingPolling = false;
+ pollingResearchId = null;
+ pollingGeneration++;
// Clear any polling intervals left over from fallback paths.
// The websocket is now the authoritative transport.
@@ -103,15 +115,38 @@ window.socket = (function() {
if (connectionAttempts >= MAX_CONNECTION_ATTEMPTS) {
SafeLogger.warn(`Failed to connect after ${MAX_CONNECTION_ATTEMPTS} attempts, falling back to polling`);
- usingPolling = true;
// If we can't establish a socket connection, use polling for any active research
- if (currentResearchId && typeof window.pollResearchStatus === 'function') {
- window.pollResearchStatus(currentResearchId);
+ if (currentResearchId) {
+ fallbackToPolling(currentResearchId);
+ } else {
+ usingPolling = true;
}
}
});
+ socket.on('subscribe_error', (data) => {
+ const rejectedResearchId = data && data.research_id;
+
+ // FastAPI scopes every subscribe_error to the requested research_id.
+ // An unscoped error cannot safely claim whichever run happens to be
+ // active when a delayed packet arrives, so ignore it as malformed.
+ // A delayed rejection for a research the page has already left
+ // must not switch the currently active run to polling.
+ if (
+ !currentResearchId ||
+ rejectedResearchId === undefined ||
+ rejectedResearchId === null ||
+ String(rejectedResearchId) !== String(currentResearchId)
+ ) {
+ SafeLogger.warn('Ignoring subscription error for inactive research:', rejectedResearchId);
+ return;
+ }
+
+ SafeLogger.warn('Research subscription failed, falling back to polling:', data.error || 'Unknown error');
+ fallbackToPolling(currentResearchId);
+ });
+
// Add handler for search engine selection events
socket.on('search_engine_selected', (data) => {
SafeLogger.log('Received search_engine_selected event:', data);
@@ -190,6 +225,14 @@ window.socket = (function() {
if (!socket && !usingPolling) {
SafeLogger.warn('Socket not initialized, initializing now');
initializeSocket();
+
+ // io() can fail synchronously (for example when the client bundle
+ // did not load). initializeSocket records that failure by setting
+ // usingPolling; start the fallback for this first subscription
+ // instead of waiting for a second subscribe that may never come.
+ if (!socket && usingPolling) {
+ fallbackToPolling(researchId);
+ }
return;
}
@@ -524,8 +567,22 @@ window.socket = (function() {
* @param {string} researchId - The research ID
*/
function fallbackToPolling(researchId) {
+ if (
+ pollingResearchId !== null &&
+ String(pollingResearchId) === String(researchId)
+ ) {
+ SafeLogger.log('Polling already active for research', researchId);
+ return;
+ }
+
SafeLogger.log('Falling back to polling for research', researchId);
usingPolling = true;
+ pollingResearchId = researchId;
+
+ if (typeof pagePollingFallback === 'function') {
+ pagePollingFallback(researchId);
+ return;
+ }
// Start polling if the global polling function exists
if (typeof window.pollResearchStatus === 'function') {
@@ -538,15 +595,55 @@ window.socket = (function() {
return;
}
+ const ownerGeneration = ++pollingGeneration;
+ let nextRequestGeneration = 0;
+ let latestAppliedRequestGeneration = 0;
+
const pollInterval = setInterval(async () => {
+ const requestGeneration = ++nextRequestGeneration;
try {
const data = await window.api.getResearchStatus(id);
+ const isTerminalSnapshot = Boolean(
+ data && ResearchStates.isTerminal(data.status)
+ );
+ if (
+ ownerGeneration !== pollingGeneration ||
+ window.pollIntervals?.[id] !== pollInterval ||
+ (
+ !isTerminalSnapshot &&
+ requestGeneration < latestAppliedRequestGeneration
+ )
+ ) {
+ return;
+ }
+ latestAppliedRequestGeneration = Math.max(
+ latestAppliedRequestGeneration,
+ requestGeneration
+ );
if (data) {
handleProgressUpdate(id, data);
// Stop polling if the research is complete
- if (ResearchStates.isTerminal(data.status)) {
+ if (isTerminalSnapshot) {
+ const ownsPollingGeneration = (
+ ownerGeneration === pollingGeneration &&
+ pollingResearchId !== null &&
+ String(pollingResearchId) === String(id)
+ );
+
clearInterval(pollInterval);
+ if (window.pollIntervals?.[id] === pollInterval) {
+ delete window.pollIntervals[id];
+ }
+ if (ownsPollingGeneration) {
+ // A terminal callback may synchronously
+ // move polling to another research. Only
+ // retire the generation this interval still
+ // owns after those callbacks have run.
+ usingPolling = !socket || !socket.connected;
+ pollingResearchId = null;
+ pollingGeneration++;
+ }
}
}
} catch (error) {
@@ -573,12 +670,29 @@ window.socket = (function() {
SafeLogger.log('Unsubscribing from research:', researchId);
+ const ownsPollingGeneration = (
+ pollingResearchId !== null &&
+ String(pollingResearchId) === String(researchId)
+ );
+
// Clear any polling intervals
if (window.pollIntervals && window.pollIntervals[researchId]) {
clearInterval(window.pollIntervals[researchId]);
delete window.pollIntervals[researchId];
}
+ if (ownsPollingGeneration) {
+ // Only the room that owns the active fallback generation may
+ // retire it. Delayed cleanup for an older room must not invalidate
+ // the newer room's in-flight/current polling responses.
+ pollingGeneration++;
+ // No active poll remains for this research. Keep fallback mode
+ // armed while the transport itself is still unavailable so the
+ // next research starts polling immediately.
+ usingPolling = !socket || !socket.connected;
+ pollingResearchId = null;
+ }
+
// If we have a socket connection, leave the research room
if (socket && socket.connected) {
try {
@@ -593,7 +707,10 @@ window.socket = (function() {
}
// Clear handlers
- if (researchId === currentResearchId) {
+ if (
+ currentResearchId !== null &&
+ String(researchId) === String(currentResearchId)
+ ) {
currentResearchId = null;
}
@@ -659,6 +776,7 @@ window.socket = (function() {
* Disconnect the socket
*/
function disconnectSocket() {
+ pollingGeneration++;
// Clear any polling intervals
if (window.pollIntervals) {
Object.keys(window.pollIntervals).forEach(id => {
@@ -681,6 +799,7 @@ window.socket = (function() {
currentResearchId = null;
connectionAttempts = 0;
usingPolling = false;
+ pollingResearchId = null;
}
/**
@@ -689,7 +808,10 @@ window.socket = (function() {
*/
function filterLogsByType(type) {
// If the logpanel's filter function is available, use it
- if (typeof window.filterLogsByType === 'function') {
+ if (
+ typeof window.filterLogsByType === 'function' &&
+ window.filterLogsByType !== filterLogsByType
+ ) {
SafeLogger.log('Using logpanel\'s filterLogsByType for filter:', type);
window.filterLogsByType(type);
return;
@@ -779,7 +901,7 @@ window.socket = (function() {
// streams: chat.js calls subscribeToResearch (which lazily initializes
// the socket) on send and when resuming an in-progress research, and
// has an HTTP polling backup either way. Other realtime pages
- // (/research, /progress, /benchmark) keep eager connect — they aren't
+ // (/, /progress, /benchmark) keep eager connect — they aren't
// navigated in the same churny way.
function autoInitSocket() {
// Match the chat page (/chat/ and /chat/<session_id>) precisely —
@@ -812,6 +934,7 @@ window.socket = (function() {
return {
init: initializeSocket,
subscribeToResearch,
+ setPollingFallback,
unsubscribeFromResearch,
onReconnect: setReconnectCallback,
disconnect: disconnectSocket,
@@ -866,6 +989,7 @@ if (!window.filterLogsByType) {
* @param {Object} metadata - Optional metadata
*/
if (!window.addConsoleLog) {
+ const socketLogConnector = window._socketAddLogEntry;
window.addConsoleLog = function(message, level = 'info', metadata = null) {
SafeLogger.log(`Adding console log (socket.js fallback): ${message} (${level})`);
@@ -884,8 +1008,13 @@ if (!window.addConsoleLog) {
return;
}
- // Then try the socket's connector function
- if (window._socketAddLogEntry) {
+ // Only delegate to a replacement connector. The socket's own
+ // connector calls addConsoleLog and would recurse back into this shim.
+ if (typeof window._socketAddLogEntry === 'function') {
+ if (window._socketAddLogEntry === socketLogConnector) {
+ SafeLogger.warn('LogPanel is not available; dropping socket log entry:', message);
+ return;
+ }
SafeLogger.log('Using _socketAddLogEntry to add log entry');
window._socketAddLogEntry(logEntry);
return;
diff --git a/src/local_deep_research/web/static/js/services/theme.js b/src/local_deep_research/web/static/js/services/theme.js
index 400041b3e4..c79ac66218 100644
--- a/src/local_deep_research/web/static/js/services/theme.js
+++ b/src/local_deep_research/web/static/js/services/theme.js
@@ -33,6 +33,8 @@
// Theme cycle order for quick toggle button (subset of popular themes)
const THEME_CYCLE = ['hashed', 'light', 'nord', 'dracula'];
+ let themeIntentGeneration = 0;
+ let themeSaveTail = Promise.resolve();
/**
* Get user ID from page context (if available)
@@ -117,14 +119,18 @@
return Promise.resolve();
}
- return fetch(`/settings/api/${SETTING_KEY}`, {
+ const runSave = () => fetch(`/settings/api/${SETTING_KEY}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
},
body: JSON.stringify({ value: theme })
- })
+ });
+ const saveRequest = themeSaveTail.then(runSave);
+ themeSaveTail = saveRequest.catch(() => {});
+
+ return saveRequest
.then(response => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
@@ -162,6 +168,7 @@
* Set theme with both local and server sync
*/
function setTheme(theme, syncToServer = true) {
+ themeIntentGeneration++;
// Validate theme using VALID_THEMES array
if (!VALID_THEMES.includes(theme)) {
SafeLogger.warn('Invalid theme:', theme, '- falling back to hashed');
@@ -341,6 +348,7 @@
* Initialize theme on page load
*/
function initializeTheme() {
+ const hydrationGeneration = ++themeIntentGeneration;
// Get stored theme - FOUC prevention script in <head> already applied it
const storedTheme = getCurrentTheme();
@@ -356,7 +364,12 @@
// Try to load from server and sync (for logged-in users)
// Only update if server theme is valid AND different
loadThemeFromServer().then(serverTheme => {
- if (serverTheme && VALID_THEMES.includes(serverTheme) && serverTheme !== getCurrentTheme()) {
+ if (
+ hydrationGeneration === themeIntentGeneration &&
+ serverTheme &&
+ VALID_THEMES.includes(serverTheme) &&
+ serverTheme !== getCurrentTheme()
+ ) {
SafeLogger.log('Server has different theme, syncing:', serverTheme);
applyTheme(serverTheme);
}
diff --git a/src/local_deep_research/web/static/js/utils/sse-completion.js b/src/local_deep_research/web/static/js/utils/sse-completion.js
index 38b2fef458..ef47e522ac 100644
--- a/src/local_deep_research/web/static/js/utils/sse-completion.js
+++ b/src/local_deep_research/web/static/js/utils/sse-completion.js
@@ -1,3 +1,44 @@
+/**
+ * Create a JSON SSE parser that preserves records split across byte chunks.
+ *
+ * ReadableStream chunk boundaries are unrelated to SSE line boundaries, and
+ * TextDecoder must stay in streaming mode when a multi-byte character is split
+ * across chunks. Call push() for each Uint8Array and finish() once at EOF.
+ *
+ * @param {Function} onData - Called once for each complete `data:` JSON line
+ * @returns {{push: Function, finish: Function}} Stateful stream parser
+ */
+function createSSEJsonParser(onData) {
+ const decoder = new window.TextDecoder();
+ let pending = '';
+
+ const emitLines = (flush) => {
+ const lines = pending.split(/\r?\n/);
+ pending = flush ? '' : lines.pop();
+
+ for (const line of lines) {
+ if (!line.startsWith('data:')) continue;
+
+ const payload = line.slice(5).trimStart();
+ if (payload) onData(JSON.parse(payload));
+ }
+ };
+
+ return {
+ push(chunk) {
+ pending += decoder.decode(chunk, { stream: true });
+ emitLines(false);
+ },
+ finish() {
+ pending += decoder.decode();
+ // EOF terminates the final SSE line even if the server omitted a
+ // trailing newline.
+ pending += '\n';
+ emitLines(true);
+ },
+ };
+}
+
/**
* Shared SSE completion handler for download/extraction streams.
*
@@ -6,9 +47,10 @@
*
* @param {Object} data - Parsed SSE event data
* @param {Function} onSuccess - Called (with data) on successful completion
+ * @param {Function} [isCurrent] - Re-check caller ownership before delayed UI
* @returns {boolean} Whether the stream completed
*/
-function handleSSECompletion(data, onSuccess) {
+function handleSSECompletion(data, onSuccess, isCurrent = () => true) {
if (!data.complete) return false;
// closeProgressModal is page-specific — defined inline in
@@ -23,14 +65,22 @@ function handleSSECompletion(data, onSuccess) {
if (data.error) {
setTimeout(() => {
+ if (!isCurrent()) return;
closeModalIfDefined();
alert(data.error);
}, 1000);
} else {
setTimeout(() => {
+ if (!isCurrent()) return;
closeModalIfDefined();
onSuccess(data);
}, 2000);
}
return true;
}
+
+// This file is loaded as a classic script before the page-level inline
+// consumers. Publish the helpers explicitly rather than relying on implicit
+// top-level bindings.
+window.createSSEJsonParser = createSSEJsonParser;
+window.handleSSECompletion = handleSSECompletion;
diff --git a/src/local_deep_research/web/templates/pages/benchmark.html b/src/local_deep_research/web/templates/pages/benchmark.html
index 23b2311637..ff59b8d974 100644
--- a/src/local_deep_research/web/templates/pages/benchmark.html
+++ b/src/local_deep_research/web/templates/pages/benchmark.html
@@ -450,6 +450,18 @@ const csrfToken = document.querySelector('meta[name="csrf-token"]')?.getAttribut
// Benchmark configuration and progress tracking
let currentBenchmarkId = null;
let progressInterval = null;
+let progressRunGeneration = 0;
+let progressStatusRequestId = 0;
+let latestAppliedProgressStatusRequestId = 0;
+let benchmarkIntentGeneration = 0;
+let benchmarkStartInFlight = false;
+let terminalBenchmarkRunGeneration = 0;
+let hydratedTerminalBenchmarkRunGeneration = 0;
+let recentResultsRequestId = 0;
+let latestAppliedRecentResultsRequestId = 0;
+let historicalChartRequestId = 0;
+let searchQualityRequestId = 0;
+let latestAppliedSearchQualityRequestId = 0;
// Global variables for evaluation settings data
let evalProviderData = null;
@@ -511,9 +523,9 @@ let searchQualityAlert = false;
document.addEventListener('DOMContentLoaded', function() {
// Initialize socket service first - but don't let it keep retrying if it fails
- if (window.socket && typeof window.socket.initializeSocket === 'function') {
+ if (window.socket && typeof window.socket.init === 'function') {
try {
- window.socket.initializeSocket();
+ window.socket.init();
} catch (e) {
console.warn('Socket initialization failed, continuing without real-time updates');
}
@@ -663,13 +675,16 @@ function getConfigurationData() {
}
function startBenchmark() {
+ if (benchmarkStartInFlight) return Promise.resolve();
+ benchmarkStartInFlight = true;
+ const intentGeneration = ++benchmarkIntentGeneration;
const config = getConfigurationData();
// Disable form
document.getElementById('benchmark-form').style.display = 'none';
document.getElementById('benchmark-progress').style.display = 'block';
- fetch('/benchmark/api/start', {
+ return fetch('/benchmark/api/start', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
@@ -677,27 +692,81 @@ function startBenchmark() {
},
body: JSON.stringify(config)
})
- .then(response => response.json())
+ .then(async response => {
+ let data = {};
+ try {
+ data = await response.json();
+ } catch (error) {
+ if (response.ok) throw error;
+ }
+
+ if (!response.ok) {
+ const payloadError = data.error ?? data.detail ?? data.message;
+ let errorMessage = `HTTP ${response.status}`;
+ if (typeof payloadError === 'string' && payloadError.trim()) {
+ errorMessage = payloadError;
+ } else if (payloadError !== undefined && payloadError !== null) {
+ errorMessage = JSON.stringify(payloadError);
+ }
+ throw new Error(errorMessage);
+ }
+ return data;
+ })
.then(data => {
- if (data.success) {
+ if (intentGeneration !== benchmarkIntentGeneration) return;
+ const runId = data.benchmark_run_id;
+ const hasRunId = (
+ (typeof runId === 'string' && runId.trim() !== '') ||
+ (typeof runId === 'number' && Number.isFinite(runId))
+ );
+ if (data.success && hasRunId) {
currentBenchmarkId = data.benchmark_run_id;
showAlert('Benchmark started successfully!', 'success');
startProgressTracking();
} else {
- showAlert('Error starting benchmark: ' + data.error, 'error');
+ const payloadError = data.error ?? data.detail ?? data.message;
+ let errorMessage = 'response did not include a benchmark run ID';
+ if (typeof payloadError === 'string' && payloadError.trim()) {
+ errorMessage = payloadError;
+ } else if (payloadError !== undefined && payloadError !== null) {
+ errorMessage = JSON.stringify(payloadError);
+ }
+ showAlert('Error starting benchmark: ' + errorMessage, 'error');
resetForm();
}
})
.catch(error => {
+ if (intentGeneration !== benchmarkIntentGeneration) return;
console.error('Start error:', error);
showAlert('Error starting benchmark: ' + error.message, 'error');
resetForm();
+ })
+ .finally(() => {
+ benchmarkStartInFlight = false;
});
}
function startProgressTracking() {
if (!currentBenchmarkId) return;
+ const trackedBenchmarkId = currentBenchmarkId;
+ const trackingGeneration = ++progressRunGeneration;
+ progressStatusRequestId++;
+ recentResultsRequestId++;
+ historicalChartRequestId++;
+ searchQualityRequestId++;
+ lastResultsUpdate = 0;
+ lastChartsUpdate = 0;
+ lastResultsData = null;
+ const recentResultsContainer = document.getElementById('recent-results-container');
+ if (recentResultsContainer) {
+ recentResultsContainer.innerHTML = '<div class="ldr-no-results">No results yet...</div>';
+ }
+ if (progressInterval) {
+ clearInterval(progressInterval);
+ progressInterval = null;
+ }
+
// Initialize charts
initializeCharts();
@@ -706,7 +775,11 @@ function startProgressTracking() {
// Load historical data if reconnecting to running benchmark
setTimeout(() => {
- loadHistoricalChartData();
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
+ loadHistoricalChartData(trackedBenchmarkId, trackingGeneration);
}, 1000);
progressInterval = setInterval(() => {
@@ -714,20 +787,40 @@ function startProgressTracking() {
}, 3000); // Update every 3 seconds (reduced from 2 for better performance)
// Initialize socket if not already done
- if (!window.socket || !window.socket.initializeSocket) {
+ if (!window.socket || typeof window.socket.init !== 'function') {
console.log('Socket service not available');
- } else if (!window.socket.socket) {
+ } else if (
+ typeof window.socket.getSocketInstance !== 'function' ||
+ !window.socket.getSocketInstance()
+ ) {
console.log('Socket not initialized, initializing now...');
- window.socket.initializeSocket();
+ window.socket.init();
}
// Connect to WebSocket for detailed progress updates (reuse socket service)
setTimeout(() => {
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
if (window.socket && typeof window.socket.subscribeToResearch === 'function') {
- console.log('Subscribing to benchmark progress for ID:', currentBenchmarkId);
+ // Benchmark polling above uses benchmark run IDs and its own API;
+ // the socket service's generic research-status poll is not valid.
+ window.socket.setPollingFallback?.(() => {});
+ console.log('Subscribing to benchmark progress for ID:', trackedBenchmarkId);
// Subscribe to benchmark progress events using research subscription (same format)
- window.socket.subscribeToResearch(currentBenchmarkId, (eventData) => {
+ window.socket.subscribeToResearch(trackedBenchmarkId, (eventData) => {
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId) ||
+ terminalBenchmarkRunGeneration === trackingGeneration
+ ) return;
handleDetailedProgress(eventData);
+ if (
+ ['completed', 'failed', 'cancelled'].includes(eventData?.status)
+ ) {
+ terminalBenchmarkRunGeneration = trackingGeneration;
+ }
});
} else {
console.warn('Socket service not available, falling back to polling only');
@@ -738,8 +831,9 @@ function startProgressTracking() {
function handleDetailedProgress(data) {
// Update current task display
const currentTask = document.getElementById('current-task');
- if (currentTask && data.status) {
- currentTask.textContent = `Example ${data.example_id}: ${data.status}`;
+ const progressMessage = data.log_entry?.message || data.message || data.status;
+ if (currentTask && progressMessage) {
+ currentTask.textContent = progressMessage;
}
}
@@ -749,13 +843,33 @@ let lastResultsUpdate = 0;
let lastChartsUpdate = 0;
function updateBenchmarkProgress() {
- if (!currentBenchmarkId) return;
+ const trackedBenchmarkId = currentBenchmarkId;
+ const trackingGeneration = progressRunGeneration;
+ const requestId = ++progressStatusRequestId;
+ if (!trackedBenchmarkId) return;
- fetch(`/benchmark/api/status/${currentBenchmarkId}`)
+ return fetch(`/benchmark/api/status/${trackedBenchmarkId}`)
.then(response => response.json())
.then(data => {
+ const terminalSnapshot = Boolean(
+ data?.success &&
+ ['completed', 'failed', 'cancelled'].includes(data.status?.status)
+ );
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId) ||
+ hydratedTerminalBenchmarkRunGeneration === trackingGeneration ||
+ (
+ terminalBenchmarkRunGeneration === trackingGeneration &&
+ !terminalSnapshot
+ ) ||
+ (requestId < latestAppliedProgressStatusRequestId && !terminalSnapshot)
+ ) return;
if (data.success) {
const status = data.status;
+ latestAppliedProgressStatusRequestId = Math.max(
+ latestAppliedProgressStatusRequestId, requestId
+ );
updateProgressDisplay(status);
// Update question/answer displays
@@ -764,7 +878,7 @@ function updateBenchmarkProgress() {
// Only update results every 10 seconds to avoid performance issues
const now = Date.now();
if (now - lastResultsUpdate > 10000) {
- updateRecentResults();
+ updateRecentResults(trackedBenchmarkId, trackingGeneration);
lastResultsUpdate = now;
}
@@ -775,14 +889,20 @@ function updateBenchmarkProgress() {
}
// Update search result monitoring
- updateSearchQualityMonitoring();
+ updateSearchQualityMonitoring(trackedBenchmarkId, trackingGeneration);
// Update rate limiting status
updateRateLimitingStatus();
if (status.status === 'completed' || status.status === 'failed' || status.status === 'cancelled') {
+ terminalBenchmarkRunGeneration = trackingGeneration;
+ hydratedTerminalBenchmarkRunGeneration = trackingGeneration;
+ progressStatusRequestId++;
clearInterval(progressInterval);
progressInterval = null;
+ if (window.socket?.unsubscribeFromResearch) {
+ window.socket.unsubscribeFromResearch(trackedBenchmarkId);
+ }
if (status.status === 'completed') {
showAlert('Benchmark completed successfully!', 'success');
@@ -793,6 +913,11 @@ function updateBenchmarkProgress() {
}
})
.catch(error => {
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId) ||
+ requestId !== progressStatusRequestId
+ ) return;
console.error('Progress update error:', error);
});
}
@@ -904,7 +1029,16 @@ function resetForm() {
document.getElementById('benchmark-form').style.display = 'block';
document.getElementById('benchmark-progress').style.display = 'none';
document.getElementById('performance-charts-section').style.display = 'none';
+ const idToUnsubscribe = currentBenchmarkId;
currentBenchmarkId = null;
+ progressRunGeneration++;
+ lastResultsUpdate = 0;
+ lastChartsUpdate = 0;
+ lastResultsData = null;
+ const recentResultsContainer = document.getElementById('recent-results-container');
+ if (recentResultsContainer) {
+ recentResultsContainer.innerHTML = '<div class="ldr-no-results">No results yet...</div>';
+ }
// Clear any running intervals
if (progressInterval) {
@@ -944,7 +1078,7 @@ function resetForm() {
// Unsubscribe from socket events if connected
if (window.socket && window.socket.unsubscribeFromResearch) {
- window.socket.unsubscribeFromResearch(currentBenchmarkId);
+ window.socket.unsubscribeFromResearch(idToUnsubscribe);
}
}
@@ -970,9 +1104,11 @@ function showAlert(message, type) {
function checkForRunningBenchmark() {
// Check if there's a running benchmark when page loads
+ const intentGeneration = ++benchmarkIntentGeneration;
fetch('/benchmark/api/running')
.then(response => response.json())
.then(data => {
+ if (intentGeneration !== benchmarkIntentGeneration) return;
if (data.success && data.benchmark_run_id) {
currentBenchmarkId = data.benchmark_run_id;
showAlert(`Reconnected to running benchmark #${currentBenchmarkId}`, 'info');
@@ -986,6 +1122,7 @@ function checkForRunningBenchmark() {
}
})
.catch(error => {
+ if (intentGeneration !== benchmarkIntentGeneration) return;
console.log('No running benchmark found (this is normal)');
});
}
@@ -1182,13 +1319,23 @@ function updateCurrentQuestion(status) {
// Cache last results to avoid unnecessary re-renders
let lastResultsData = null;
-function updateRecentResults() {
- if (!currentBenchmarkId) return;
+function updateRecentResults(
+ trackedBenchmarkId = currentBenchmarkId,
+ trackingGeneration = progressRunGeneration
+) {
+ const requestId = ++recentResultsRequestId;
+ if (!trackedBenchmarkId) return;
- fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=50`) // Reduced from 100 for performance
+ return fetch(`/benchmark/api/results/${trackedBenchmarkId}?limit=50`) // Reduced from 100 for performance
.then(response => response.json())
.then(data => {
+ if (
+ requestId < latestAppliedRecentResultsRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
if (data.persistence_error) {
+ latestAppliedRecentResultsRequestId = requestId;
const container = document.getElementById('recent-results-container');
container.replaceChildren();
const error = document.createElement('div');
@@ -1200,6 +1347,10 @@ function updateRecentResults() {
return;
}
if (data.success && data.results) {
+ // A newer request starting is not evidence of a newer result.
+ // Accept slow in-order responses, but never replace a result that
+ // has already been rendered with an older snapshot.
+ latestAppliedRecentResultsRequestId = requestId;
// Only update if data has changed
const newResultsStr = JSON.stringify(data.results);
const oldResultsStr = JSON.stringify(lastResultsData);
@@ -1211,6 +1362,11 @@ function updateRecentResults() {
}
})
.catch(error => {
+ if (
+ requestId !== recentResultsRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
console.error('Error fetching all results:', error);
});
}
@@ -1538,13 +1694,22 @@ function updateCharts(status) {
}
// Load historical chart data when reconnecting to running benchmark
-async function loadHistoricalChartData() {
- if (!currentBenchmarkId || !accuracyChart || !timingChart) return;
+async function loadHistoricalChartData(
+ trackedBenchmarkId = currentBenchmarkId,
+ trackingGeneration = progressRunGeneration
+) {
+ const requestId = ++historicalChartRequestId;
+ if (!trackedBenchmarkId || !accuracyChart || !timingChart) return;
try {
// Get benchmark status to populate initial chart data
- const response = await fetch(`/benchmark/api/status/${currentBenchmarkId}`);
+ const response = await fetch(`/benchmark/api/status/${trackedBenchmarkId}`);
const data = await response.json();
+ if (
+ requestId !== historicalChartRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
if (data.success && data.status.completed_examples > 0) {
// Create simulated historical data points for a smooth chart
@@ -1576,20 +1741,37 @@ async function loadHistoricalChartData() {
timingChart.update();
}
} catch (error) {
+ if (
+ requestId !== historicalChartRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
console.error('Error loading historical chart data:', error);
}
}
// Search quality monitoring functions
-async function updateSearchQualityMonitoring() {
- if (!currentBenchmarkId) return;
+async function updateSearchQualityMonitoring(
+ trackedBenchmarkId = currentBenchmarkId,
+ trackingGeneration = progressRunGeneration
+) {
+ const requestId = ++searchQualityRequestId;
+ if (!trackedBenchmarkId) return;
try {
// Fetch recent results to get search counts
- const response = await fetch(`/benchmark/api/results/${currentBenchmarkId}?limit=5`);
+ const response = await fetch(`/benchmark/api/results/${trackedBenchmarkId}?limit=5`);
const data = await response.json();
-
- if (data.success && data.results && data.results.length > 0) {
+ if (
+ requestId < latestAppliedSearchQualityRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
+
+ if (data.success && Array.isArray(data.results)) {
+ // Empty successful snapshots also retire older results. Failed
+ // reads do not claim ownership over a usable in-flight response.
+ latestAppliedSearchQualityRequestId = requestId;
// Process search result counts (already calculated by backend)
const recentResults = data.results;
let totalSearchResults = 0;
@@ -1609,6 +1791,11 @@ async function updateSearchQualityMonitoring() {
}
}
} catch (error) {
+ if (
+ requestId !== searchQualityRequestId ||
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
console.error('Error updating search quality monitoring:', error);
}
}
@@ -1786,6 +1973,7 @@ let evaluationProviderSelect = null;
let evaluationModelInput = null;
let evaluationEndpointInput = null;
let evaluationTemperatureInput = null;
+let evaluationModelsRequestVersion = 0;
function initializeEvaluationSettings() {
console.log('Initializing evaluation settings...');
@@ -1827,6 +2015,8 @@ function initializeEvaluationSettings() {
function populateEvaluationProviders() {
if (!evaluationProviderSelect) return;
+ const currentProvider = evaluationProviderSelect.value;
+
// Clear existing options
evaluationProviderSelect.innerHTML = '';
@@ -1850,16 +2040,20 @@ function populateEvaluationProviders() {
// Set initial value from data attribute
const initialProvider = evaluationProviderSelect.getAttribute('data-initial-value') || 'openai_endpoint';
- console.log('Setting initial evaluation provider to:', initialProvider);
- evaluationProviderSelect.value = initialProvider;
-
- // Show/hide endpoint field based on initial provider
+ const selectedProvider = currentProvider && Array.from(evaluationProviderSelect.options)
+ .some(option => option.value === currentProvider)
+ ? currentProvider
+ : initialProvider;
+ console.log('Setting evaluation provider to:', selectedProvider);
+ evaluationProviderSelect.value = selectedProvider;
+
+ // Show/hide endpoint field based on the retained provider
if (evaluationEndpointInput && evaluationEndpointInput.parentNode) {
evaluationEndpointInput.parentNode.style.display =
- initialProvider === 'openai_endpoint' ? 'block' : 'none';
+ selectedProvider === 'openai_endpoint' ? 'block' : 'none';
}
- console.log('Populated evaluation providers with initial value:', initialProvider);
+ console.log('Populated evaluation providers with value:', selectedProvider);
}
function setupEvaluationModelDropdown() {
@@ -1914,11 +2108,14 @@ function setupEvaluationModelDropdown() {
}
// Force reload models from API
- window.modelsLoading = false; // Reset the flag
+ loadEvaluationModelsFromAPI.cancel();
+ window.modelsLoading = true;
+ const requestVersion = ++evaluationModelsRequestVersion;
fetch('/settings/api/available-models?force_refresh=true')
.then(response => response.json())
.then(data => {
+ if (requestVersion !== evaluationModelsRequestVersion) return;
console.log('Force refresh received model data:', data);
if (data && data.providers) {
@@ -1960,6 +2157,7 @@ function setupEvaluationModelDropdown() {
console.error('Error loading evaluation models:', error);
})
.finally(() => {
+ if (requestVersion !== evaluationModelsRequestVersion) return;
// Remove loading state
if (icon) {
icon.classList.remove('fa-spin');
@@ -1984,7 +2182,7 @@ function getEvaluationModelOptions() {
// Load models from API if not already loading
if (!window.modelsLoading) {
- window.modelsLoading = true;
+ // The debounced loader owns the in-flight flag when its request starts.
loadEvaluationModelsFromAPI();
}
@@ -2016,14 +2214,18 @@ function getEvaluationModelOptions() {
// Debounce function to prevent too many API calls
function debounce(func, wait) {
let timeout;
- return function executedFunction(...args) {
+ function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
+ }
+ executedFunction.cancel = function() {
+ clearTimeout(timeout);
};
+ return executedFunction;
}
// Debounced version of loadEvaluationModelsFromAPI
@@ -2037,6 +2239,7 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
}
window.modelsLoading = true;
+ const requestVersion = ++evaluationModelsRequestVersion;
// Use the correct API endpoint with optional force_refresh parameter
const url = forceRefresh ? '/settings/api/available-models?force_refresh=true' : '/settings/api/available-models';
@@ -2044,6 +2247,7 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
fetch(url)
.then(response => response.json())
.then(data => {
+ if (requestVersion !== evaluationModelsRequestVersion) return;
console.log('Received model data:', data);
if (data && data.providers) {
@@ -2085,7 +2289,9 @@ const loadEvaluationModelsFromAPI = debounce(function(forceRefresh = false) {
console.error('Error loading evaluation models:', error);
})
.finally(() => {
- window.modelsLoading = false;
+ if (requestVersion === evaluationModelsRequestVersion) {
+ window.modelsLoading = false;
+ }
});
}, 500); // Wait 500ms before making the API call
diff --git a/src/local_deep_research/web/templates/pages/benchmark_simple.html b/src/local_deep_research/web/templates/pages/benchmark_simple.html
index 618845e6e9..9a286cde75 100644
--- a/src/local_deep_research/web/templates/pages/benchmark_simple.html
+++ b/src/local_deep_research/web/templates/pages/benchmark_simple.html
@@ -214,6 +214,10 @@
<script>
let currentBenchmarkId = null;
let progressInterval = null;
+let progressRunGeneration = 0;
+let progressStatusRequestId = 0;
+let latestAppliedProgressStatusRequestId = 0;
+let terminalProgressRunGeneration = null;
document.addEventListener('DOMContentLoaded', function() {
loadCurrentConfig();
@@ -309,7 +313,9 @@ async function startBenchmark() {
}
// Disable start button
- document.getElementById('start-benchmark').disabled = true;
+ const startButton = document.getElementById('start-benchmark');
+ if (startButton.disabled) return;
+ startButton.disabled = true;
try {
// Get CSRF token
@@ -324,21 +330,49 @@ async function startBenchmark() {
body: JSON.stringify({ datasets_config: datasets })
});
- const data = await response.json();
+ let data = {};
+ try {
+ data = await response.json();
+ } catch (error) {
+ if (response.ok) throw error;
+ }
- if (data.success) {
- currentBenchmarkId = data.benchmark_run_id;
+ if (!response.ok) {
+ const payloadError = data.error ?? data.detail ?? data.message;
+ let errorMessage = `HTTP ${response.status}`;
+ if (typeof payloadError === 'string' && payloadError.trim()) {
+ errorMessage = payloadError;
+ } else if (payloadError !== undefined && payloadError !== null) {
+ errorMessage = JSON.stringify(payloadError);
+ }
+ throw new Error(errorMessage);
+ }
+
+ const runId = data.benchmark_run_id;
+ const hasRunId = (
+ (typeof runId === 'string' && runId.trim() !== '') ||
+ (typeof runId === 'number' && Number.isFinite(runId))
+ );
+ if (data.success && hasRunId) {
+ currentBenchmarkId = runId;
showProgress();
startProgressTracking();
showAlert('Benchmark started!', 'success');
} else {
- showAlert('Error: ' + data.error, 'error');
- document.getElementById('start-benchmark').disabled = false;
+ const payloadError = data.error ?? data.detail ?? data.message;
+ let errorMessage = 'response did not include a benchmark run ID';
+ if (typeof payloadError === 'string' && payloadError.trim()) {
+ errorMessage = payloadError;
+ } else if (payloadError !== undefined && payloadError !== null) {
+ errorMessage = JSON.stringify(payloadError);
+ }
+ showAlert('Error: ' + errorMessage, 'error');
+ startButton.disabled = false;
}
} catch (error) {
console.error('Error starting benchmark:', error);
- showAlert('Failed to start benchmark', 'error');
- document.getElementById('start-benchmark').disabled = false;
+ showAlert('Failed to start benchmark: ' + error.message, 'error');
+ startButton.disabled = false;
}
}
@@ -356,19 +390,49 @@ function hideProgress() {
}
function startProgressTracking() {
- updateProgress(); // Initial update
+ progressRunGeneration++;
+ progressStatusRequestId++;
+ if (progressInterval) {
+ clearInterval(progressInterval);
+ progressInterval = null;
+ }
+ const initialUpdate = updateProgress(); // Initial update
progressInterval = setInterval(updateProgress, 2000);
+ return initialUpdate;
+}
+
+function formatBenchmarkAccuracy(value) {
+ return typeof value === 'number' && Number.isFinite(value)
+ ? value.toFixed(1) + '%'
+ : 'N/A';
}
async function updateProgress() {
- if (!currentBenchmarkId) return;
+ const trackedBenchmarkId = currentBenchmarkId;
+ const trackingGeneration = progressRunGeneration;
+ const requestId = ++progressStatusRequestId;
+ if (!trackedBenchmarkId) return;
try {
- const response = await fetch(`/benchmark/api/status/${currentBenchmarkId}`);
+ const response = await fetch(`/benchmark/api/status/${trackedBenchmarkId}`);
const data = await response.json();
+ const terminalSnapshot = Boolean(
+ data?.success &&
+ ['completed', 'failed', 'cancelled'].includes(data.status?.status)
+ );
+
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId) ||
+ terminalProgressRunGeneration === trackingGeneration ||
+ (requestId < latestAppliedProgressStatusRequestId && !terminalSnapshot)
+ ) return;
if (data.success) {
const status = data.status;
+ latestAppliedProgressStatusRequestId = Math.max(
+ latestAppliedProgressStatusRequestId, requestId
+ );
// Update progress bar
const percentage = status.total_examples > 0 ?
@@ -377,7 +441,7 @@ async function updateProgress() {
// Update stats
document.getElementById('stat-accuracy').textContent =
- status.overall_accuracy ? status.overall_accuracy.toFixed(1) + '%' : '--%';
+ formatBenchmarkAccuracy(status.overall_accuracy);
document.getElementById('stat-completed').textContent =
`${status.completed_examples}/${status.total_examples}`;
document.getElementById('stat-rate').textContent =
@@ -394,22 +458,37 @@ async function updateProgress() {
// Check if completed
if (status.status === 'completed' || status.status === 'failed' || status.status === 'cancelled') {
+ terminalProgressRunGeneration = trackingGeneration;
+ progressStatusRequestId++;
clearInterval(progressInterval);
progressInterval = null;
if (status.status === 'completed') {
- showAlert(`Benchmark completed! Final accuracy: ${status.overall_accuracy.toFixed(1)}%`, 'success');
+ showAlert(
+ `Benchmark completed! Final accuracy: ${formatBenchmarkAccuracy(status.overall_accuracy)}`,
+ 'success'
+ );
} else {
showAlert(`Benchmark ${status.status}`, 'error');
}
setTimeout(() => {
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId)
+ ) return;
hideProgress();
currentBenchmarkId = null;
+ progressRunGeneration++;
}, 3000);
}
}
} catch (error) {
+ if (
+ trackingGeneration !== progressRunGeneration ||
+ String(currentBenchmarkId) !== String(trackedBenchmarkId) ||
+ requestId !== progressStatusRequestId
+ ) return;
console.error('Error updating progress:', error);
}
}
diff --git a/src/local_deep_research/web/templates/pages/collection_upload.html b/src/local_deep_research/web/templates/pages/collection_upload.html
index 5060f543fc..9aa139725d 100644
--- a/src/local_deep_research/web/templates/pages/collection_upload.html
+++ b/src/local_deep_research/web/templates/pages/collection_upload.html
@@ -133,7 +133,7 @@
<i aria-hidden="true" class="fas fa-cloud-upload-alt fa-4x"></i>
<p class="ldr-drop-zone-text">🚀 Drag and drop files here</p>
<p class="ldr-drop-zone-subtext">or</p>
- <button type="button" class="ldr-btn-collections ldr-btn-collections-primary" onclick="document.getElementById('files-input').click()">
+ <button type="button" class="ldr-btn-collections ldr-btn-collections-primary">
<i aria-hidden="true" class="fas fa-folder-open"></i> Browse Files
</button>
<input type="file" id="files-input" name="files" multiple style="display: none;">
diff --git a/src/local_deep_research/web/templates/pages/download_manager.html b/src/local_deep_research/web/templates/pages/download_manager.html
index d4bf158d23..783fc127a6 100644
--- a/src/local_deep_research/web/templates/pages/download_manager.html
+++ b/src/local_deep_research/web/templates/pages/download_manager.html
@@ -409,6 +409,13 @@ function resetStatusCounts() {
statusCounts = {succeeded: 0, skipped: 0, failed: 0};
const breakdown = document.querySelector('.ldr-status-breakdown');
if (breakdown) breakdown.style.display = 'none';
+ const progressBar = document.getElementById('overall-progress');
+ progressBar.classList.remove('ldr-cancelled');
+ progressBar.style.removeProperty('background-color');
+ progressBar.style.width = '0%';
+ document.getElementById('current-count').textContent = '0';
+ document.getElementById('total-count').textContent = '0';
+ document.getElementById('download-log').innerHTML = '';
document.getElementById('succeeded-count').textContent = '0';
document.getElementById('skipped-count').textContent = '0';
document.getElementById('failed-count').textContent = '0';
@@ -553,8 +560,14 @@ document.getElementById('download-text-db')?.addEventListener('click', () => {
});
let currentDownloadController = null;
+let currentDownloadRunId = 0;
async function startBulkDownload(researchIds, mode = 'pdf') {
+ const downloadRunId = ++currentDownloadRunId;
+ if (currentDownloadController) {
+ currentDownloadController.abort();
+ }
+
// Reset per-status counters + breakdown for this run.
resetStatusCounts();
@@ -566,7 +579,8 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
const collectionId = collectionSelect ? collectionSelect.value : null;
// Create abort controller for cancellation
- currentDownloadController = new AbortController();
+ const downloadController = new AbortController();
+ currentDownloadController = downloadController;
// Set modal title based on mode
const modalTitles = {
@@ -593,32 +607,66 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
'X-CSRFToken': csrfToken
},
body: JSON.stringify(requestBody),
- signal: currentDownloadController.signal
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
const reader = response.body.getReader();
- const decoder = new TextDecoder();
+ let terminalSeen = false;
+ const parser = createSSEJsonParser((data) => {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (data.complete) terminalSeen = true;
+ updateProgress(data);
+
+ // Check if download is complete
+ if (handleSSECompletion(
+ data,
+ () => location.reload(),
+ () => downloadRunId === currentDownloadRunId
+ )) {
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ }
+ });
while (true) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
const {done, value} = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value);
- const lines = chunk.split('\n');
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = JSON.parse(line.slice(6));
- updateProgress(data);
-
- // Check if download is complete
- if (handleSSECompletion(data, () => location.reload())) {
- currentDownloadController = null;
- }
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+ if (done) {
+ parser.finish();
+ if (!terminalSeen) {
+ throw new Error('Download stream ended before completion');
}
+ break;
}
+ parser.push(value);
}
} catch (error) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (error.name === 'AbortError') {
console.log('Download cancelled by user');
const log = document.getElementById('download-log');
@@ -628,9 +676,12 @@ async function startBulkDownload(researchIds, mode = 'pdf') {
log.appendChild(entry);
} else {
console.error('Download error:', error);
+ alert('Failed to start downloads. Please try again.');
}
} finally {
- currentDownloadController = null;
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
}
}
@@ -717,9 +768,18 @@ function closeProgressModal() {
// Cancel downloads
function cancelDownloads() {
- if (currentDownloadController) {
- currentDownloadController.abort();
- currentDownloadController = null;
+ const downloadController = currentDownloadController;
+ // Completion already owns its delayed close/reload once the controller
+ // is cleared. A late Cancel click must not invalidate that callback.
+ if (!downloadController) {
+ closeProgressModal();
+ return;
+ }
+ const cancellationRunId = ++currentDownloadRunId;
+ currentDownloadController = null;
+
+ if (downloadController) {
+ downloadController.abort();
// Update UI to show cancellation
const progressBar = document.getElementById('overall-progress');
@@ -734,19 +794,26 @@ function cancelDownloads() {
// Close modal after a delay
setTimeout(() => {
+ if (cancellationRunId !== currentDownloadRunId) return;
closeProgressModal();
location.reload();
}, 1500);
- } else {
- // If no active download, just close modal
- closeProgressModal();
}
}
// Download ALL PDFs function
async function downloadAllNew() {
const btn = event.target.closest('button');
+ if (btn.disabled) return;
+
const originalContent = btn.innerHTML;
+ const downloadRunId = ++currentDownloadRunId;
+ if (currentDownloadController) {
+ currentDownloadController.abort();
+ }
+ const downloadController = new AbortController();
+ currentDownloadController = downloadController;
+ resetStatusCounts();
btn.innerHTML = '<i aria-hidden="true" class="fas fa-spinner fa-spin"></i> Preparing...';
btn.disabled = true;
@@ -759,14 +826,24 @@ async function downloadAllNew() {
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
- }
+ },
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (!queueResponse.ok) {
throw new Error(`HTTP error! status: ${queueResponse.status}`);
}
const queueResult = await queueResponse.json();
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
if (queueResult.queued === 0) {
alert('No new articles to download. All available articles have already been downloaded.');
@@ -780,17 +857,9 @@ async function downloadAllNew() {
document.querySelector('#download-progress-modal h2').textContent = 'Downloading ALL PDFs';
// Reset progress
- document.getElementById('overall-progress').style.width = '0%';
- document.getElementById('current-count').textContent = '0';
document.getElementById('total-count').textContent = queueResult.queued;
- document.getElementById('download-log').innerHTML = '';
- resetStatusCounts();
btn.innerHTML = originalContent;
- btn.disabled = false;
-
- // Create abort controller
- currentDownloadController = new AbortController();
// Start streaming download
const downloadResponse = await fetch('/library/api/download-bulk', {
@@ -800,32 +869,66 @@ async function downloadAllNew() {
'X-CSRFToken': csrfToken
},
body: JSON.stringify({research_ids: queueResult.research_ids || []}),
- signal: currentDownloadController.signal
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (!downloadResponse.ok) {
+ throw new Error(`HTTP error! status: ${downloadResponse.status}`);
+ }
+
const reader = downloadResponse.body.getReader();
- const decoder = new TextDecoder();
+ let terminalSeen = false;
+ const parser = createSSEJsonParser((data) => {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (data.complete) terminalSeen = true;
+ updateProgress(data);
+
+ if (handleSSECompletion(
+ data,
+ () => location.reload(),
+ () => downloadRunId === currentDownloadRunId
+ )) {
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ }
+ });
while (true) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
const {done, value} = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value);
- const lines = chunk.split('\n');
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = JSON.parse(line.slice(6));
- updateProgress(data);
-
- if (handleSSECompletion(data, () => location.reload())) {
- currentDownloadController = null;
- }
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+ if (done) {
+ parser.finish();
+ if (!terminalSeen) {
+ throw new Error('Download stream ended before completion');
}
+ break;
}
+ parser.push(value);
}
} catch (error) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (error.name === 'AbortError') {
console.log('Download cancelled by user');
} else {
@@ -835,7 +938,11 @@ async function downloadAllNew() {
btn.innerHTML = originalContent;
btn.disabled = false;
} finally {
- currentDownloadController = null;
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
}
}
@@ -843,6 +950,12 @@ async function downloadAllNew() {
async function downloadAllAsText() {
const btn = event.target.closest('button');
const originalContent = btn.innerHTML;
+ const downloadRunId = ++currentDownloadRunId;
+ if (currentDownloadController) {
+ currentDownloadController.abort();
+ }
+ const downloadController = new AbortController();
+ currentDownloadController = downloadController;
btn.innerHTML = '<i aria-hidden="true" class="fas fa-spinner fa-spin"></i> Extracting...';
btn.disabled = true;
@@ -860,8 +973,6 @@ async function downloadAllAsText() {
document.getElementById('download-log').innerHTML = '';
resetStatusCounts();
- currentDownloadController = new AbortController();
-
const response = await fetch('/library/api/download-all-text', {
method: 'POST',
headers: {
@@ -869,32 +980,66 @@ async function downloadAllAsText() {
'X-CSRFToken': csrfToken
},
body: JSON.stringify({}),
- signal: currentDownloadController.signal
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
const reader = response.body.getReader();
- const decoder = new TextDecoder();
+ let terminalSeen = false;
+ const parser = createSSEJsonParser((data) => {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (data.complete) terminalSeen = true;
+ updateTextExtractionProgress(data);
+
+ if (handleSSECompletion(
+ data,
+ (d) => alert(`Text extraction complete! Extracted ${d.total} documents to encrypted database.`),
+ () => downloadRunId === currentDownloadRunId
+ )) {
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ }
+ });
while (true) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
const {done, value} = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value);
- const lines = chunk.split('\n');
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = JSON.parse(line.slice(6));
- updateTextExtractionProgress(data);
-
- if (handleSSECompletion(data, (d) => alert(`Text extraction complete! Extracted ${d.total} documents to encrypted database.`))) {
- currentDownloadController = null;
- }
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+ if (done) {
+ parser.finish();
+ if (!terminalSeen) {
+ throw new Error('Text extraction stream ended before completion');
}
+ break;
}
+ parser.push(value);
}
} catch (error) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (error.name === 'AbortError') {
console.log('Text extraction cancelled by user');
} else {
@@ -904,7 +1049,9 @@ async function downloadAllAsText() {
} finally {
btn.innerHTML = originalContent;
btn.disabled = false;
- currentDownloadController = null;
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
}
}
diff --git a/src/local_deep_research/web/templates/pages/journal_quality.html b/src/local_deep_research/web/templates/pages/journal_quality.html
index aaafc831e4..e731eb2061 100644
--- a/src/local_deep_research/web/templates/pages/journal_quality.html
+++ b/src/local_deep_research/web/templates/pages/journal_quality.html
@@ -575,6 +575,8 @@ function switchTab(tab) {
/* ------------------------------------------------------------------ */
let thresholdLoaded = false;
let thresholdSaveTimer = null;
+let thresholdIntentGeneration = 0;
+let thresholdSaveTail = Promise.resolve();
const THRESHOLD_DESCRIPTIONS = {
1: { label: 'Filter is OFF', detail: 'Nothing is removed. Even predatory journals (score 1) pass because the filter keeps everything ≥ 1.' },
@@ -611,11 +613,13 @@ function updateThresholdExplanation(value) {
function onThresholdInput(value, _src) {
// Live preview while dragging — no save yet
+ thresholdIntentGeneration++;
updateThresholdExplanation(value);
}
function onThresholdChange(value, _src) {
// Debounce save by 300 ms in case the user keeps moving
+ thresholdIntentGeneration++;
updateThresholdExplanation(value);
clearTimeout(thresholdSaveTimer);
['ldr-threshold-save-status', 'ldr-threshold-save-status-top'].forEach(id => {
@@ -626,26 +630,30 @@ function onThresholdChange(value, _src) {
}
async function loadThreshold() {
+ const intentGeneration = ++thresholdIntentGeneration;
try {
const resp = await fetch('/settings/api/search.journal_reputation.threshold');
if (!resp.ok) throw new Error('HTTP ' + resp.status);
const data = await resp.json();
+ if (intentGeneration !== thresholdIntentGeneration) return;
const value = (data.setting && data.setting.value) ?? data.value ?? 2;
updateThresholdExplanation(value);
} catch (e) {
+ if (intentGeneration !== thresholdIntentGeneration) return;
console.error('Failed to load threshold setting:', e);
updateThresholdExplanation(2);
}
}
async function saveThreshold(value) {
+ const intentGeneration = ++thresholdIntentGeneration;
const setStatus = (text, color) => {
['ldr-threshold-save-status', 'ldr-threshold-save-status-top'].forEach(id => {
const s = document.getElementById(id);
if (s) { s.textContent = text; s.style.color = color; }
});
};
- try {
+ const runSave = async () => {
const csrf = document.querySelector('meta[name="csrf-token"]');
const headers = { 'Content-Type': 'application/json' };
if (csrf) headers['X-CSRFToken'] = csrf.content;
@@ -655,8 +663,19 @@ async function saveThreshold(value) {
body: JSON.stringify({ value: value })
});
if (!resp.ok) throw new Error('HTTP ' + resp.status);
+ return resp;
+ };
+ const saveRequest = thresholdSaveTail.then(runSave);
+ thresholdSaveTail = saveRequest.catch(() => {});
+
+ try {
+ await saveRequest;
+ if (intentGeneration !== thresholdIntentGeneration) return;
setStatus('✓ Saved', 'var(--success-color, #34c759)');
- setTimeout(() => setStatus('', 'var(--text-secondary)'), 2000);
+ setTimeout(() => {
+ if (intentGeneration !== thresholdIntentGeneration) return;
+ setStatus('', 'var(--text-secondary)');
+ }, 2000);
// Global toast — same green slide-in the rest of the app uses
// when a setting is updated.
if (window.ui && window.ui.showMessage) {
@@ -666,6 +685,7 @@ async function saveThreshold(value) {
);
}
} catch (e) {
+ if (intentGeneration !== thresholdIntentGeneration) return;
console.error('Failed to save threshold:', e);
setStatus('✗ Save failed', 'var(--error-color, #ff6347)');
if (window.ui && window.ui.showMessage) {
@@ -710,10 +730,14 @@ function renderSourcesBanner(sources) {
}).join('');
}
-async function checkDataStatus() {
+async function checkDataStatus(generation = _ldrProgressGeneration) {
try {
const resp = await fetch('/metrics/api/journal-data/status');
const status = await resp.json();
+ if (
+ generation !== _ldrProgressGeneration ||
+ _ldrProgressTimer !== null
+ ) return true;
const banner = document.getElementById('ldr-data-banner');
const text = document.getElementById('ldr-data-banner-text');
const btn = document.getElementById('ldr-data-download-btn');
@@ -739,6 +763,9 @@ async function checkDataStatus() {
}
let _ldrProgressTimer = null;
+let _ldrProgressGeneration = 0;
+let _ldrProgressRequestId = 0;
+let _ldrLatestAppliedProgressRequestId = 0;
function _stateColor(state) {
// Keep in sync with the dashboard's palette vars defined in app CSS.
@@ -806,15 +833,57 @@ function _renderProgress(snap) {
}).join('');
}
-async function _pollDownloadProgress() {
+async function _pollDownloadProgress(generation = _ldrProgressGeneration) {
+ const requestId = ++_ldrProgressRequestId;
try {
const resp = await fetch('/metrics/api/journal-data/status', {
headers: {'Accept': 'application/json'},
});
if (!resp.ok) return;
const status = await resp.json();
+ if (generation !== _ldrProgressGeneration) return;
const snap = status.download_progress || {state: 'idle'};
- if (snap.state === 'running') _renderProgress(snap);
+ const terminalSnapshot = snap.state === 'success' || snap.state === 'error';
+ if (
+ !terminalSnapshot &&
+ requestId < _ldrLatestAppliedProgressRequestId
+ ) return;
+ _ldrLatestAppliedProgressRequestId = Math.max(
+ _ldrLatestAppliedProgressRequestId,
+ requestId
+ );
+ if (snap.state === 'running') {
+ _renderProgress(snap);
+ } else if (snap.state === 'success' || snap.state === 'error') {
+ _renderProgress(snap);
+ const completedGeneration = ++_ldrProgressGeneration;
+ if (_ldrProgressTimer !== null) {
+ clearInterval(_ldrProgressTimer);
+ _ldrProgressTimer = null;
+ }
+
+ const btn = document.getElementById('ldr-data-download-btn');
+ const progressText = document.getElementById('ldr-data-progress-intro');
+ if (snap.state === 'success') {
+ if (progressText) progressText.textContent = '[100%] Complete — Journal data is ready.';
+ if (btn) {
+ btn.textContent = 'Downloaded';
+ btn.disabled = true;
+ }
+ // Polling may settle before the download POST returns, or
+ // resume a download after navigation. It must refresh the
+ // journal table itself when it owns successful completion.
+ setTimeout(() => {
+ if (completedGeneration === _ldrProgressGeneration) location.reload();
+ }, 1500);
+ } else {
+ if (progressText) progressText.textContent = 'Error: ' + (snap.error_msg || 'Download failed');
+ if (btn) {
+ btn.textContent = 'Retry Download';
+ btn.disabled = false;
+ }
+ }
+ }
} catch (e) {
// Polling is best-effort; swallow network hiccups silently.
}
@@ -822,6 +891,9 @@ async function _pollDownloadProgress() {
async function downloadJournalData() {
const btn = document.getElementById('ldr-data-download-btn');
+ const progressText = document.getElementById('ldr-data-progress-intro');
+ const generation = ++_ldrProgressGeneration;
+ let progressTimer = null;
btn.disabled = true;
btn.textContent = 'Downloading...';
@@ -831,8 +903,9 @@ async function downloadJournalData() {
// Poll the status endpoint while the POST is in flight so the user
// sees real per-source progress instead of a frozen bar.
- if (_ldrProgressTimer) clearInterval(_ldrProgressTimer);
- _ldrProgressTimer = setInterval(_pollDownloadProgress, 2000);
+ if (_ldrProgressTimer !== null) clearInterval(_ldrProgressTimer);
+ progressTimer = setInterval(() => _pollDownloadProgress(generation), 2000);
+ _ldrProgressTimer = progressTimer;
try {
const csrfToken = window.api ? window.api.getCsrfToken() : '';
@@ -845,24 +918,28 @@ async function downloadJournalData() {
body: JSON.stringify({force: false})
});
const result = await resp.json();
+ if (generation !== _ldrProgressGeneration) return;
+ const completedGeneration = ++_ldrProgressGeneration;
if (result.success) {
- progressBar.style.width = '100%';
progressText.textContent = '[100%] Complete — ' + result.message;
- setTimeout(() => location.reload(), 1500);
+ setTimeout(() => {
+ if (completedGeneration === _ldrProgressGeneration) location.reload();
+ }, 1500);
} else {
progressText.textContent = 'Error: ' + result.message;
- progressBar.style.width = '0%';
btn.disabled = false;
btn.textContent = 'Retry Download';
}
} catch (e) {
+ if (generation !== _ldrProgressGeneration) return;
+ _ldrProgressGeneration++;
progressText.textContent = 'Network error: ' + e.message;
btn.disabled = false;
btn.textContent = 'Retry Download';
} finally {
- if (_ldrProgressTimer) {
- clearInterval(_ldrProgressTimer);
+ if (_ldrProgressTimer === progressTimer) {
+ clearInterval(progressTimer);
_ldrProgressTimer = null;
}
}
@@ -872,10 +949,12 @@ async function downloadJournalData() {
// user reloaded the page mid-download, or a background init triggered
// one), show its live status immediately instead of a blank banner.
document.addEventListener('DOMContentLoaded', async () => {
+ const generation = _ldrProgressGeneration;
try {
const resp = await fetch('/metrics/api/journal-data/status');
if (!resp.ok) return;
const status = await resp.json();
+ if (generation !== _ldrProgressGeneration) return;
const snap = status.download_progress;
if (snap && snap.state === 'running') {
const btn = document.getElementById('ldr-data-download-btn');
@@ -884,7 +963,13 @@ document.addEventListener('DOMContentLoaded', async () => {
btn.textContent = 'Downloading...';
}
_renderProgress(snap);
- _ldrProgressTimer = setInterval(_pollDownloadProgress, 2000);
+ if (_ldrProgressTimer !== null) {
+ clearInterval(_ldrProgressTimer);
+ }
+ _ldrProgressTimer = setInterval(
+ () => _pollDownloadProgress(generation),
+ 2000
+ );
}
} catch (e) {
// Best-effort; not critical if this probe fails.
@@ -993,12 +1078,16 @@ function buildApiUrl(page, includeSummary) {
/* Data loading — server-side pagination */
/* ------------------------------------------------------------------ */
let summaryLoaded = false;
+let journalPageRequestId = 0;
async function loadJournalPage(page, includeSummary) {
const error = document.getElementById('ldr-error');
+ const requestId = ++journalPageRequestId;
+ const url = buildApiUrl(page, includeSummary);
try {
- const resp = await fetch(buildApiUrl(page, includeSummary));
+ const resp = await fetch(url);
+ if (requestId !== journalPageRequestId) return;
// 503 with "reference database not available" is the expected
// first-install state, not an error — the data-banner above
// carries the install CTA. Suppress the red error box so the
@@ -1009,6 +1098,7 @@ async function loadJournalPage(page, includeSummary) {
return;
}
const result = await resp.json();
+ if (requestId !== journalPageRequestId) return;
if (result.status !== 'success') throw new Error(result.message || 'Failed');
@@ -1035,6 +1125,7 @@ async function loadJournalPage(page, includeSummary) {
renderPagination();
summaryLoaded = true;
} catch (err) {
+ if (requestId !== journalPageRequestId) return;
error.textContent = 'Failed to load journal data. ' + err.message;
error.style.display = 'block';
}
diff --git a/src/local_deep_research/web/templates/pages/library.html b/src/local_deep_research/web/templates/pages/library.html
index c28c43d77d..98e61c5f30 100644
--- a/src/local_deep_research/web/templates/pages/library.html
+++ b/src/local_deep_research/web/templates/pages/library.html
@@ -553,14 +553,15 @@
<script>
// Store current PDF data globally
let currentPDFData = null;
+let documentViewerRequestId = 0;
// Route to appropriate viewer based on availability
function openDocument(docId, hasPdf, hasTextDb) {
// Prefer PDF if available, otherwise fall back to text
if (hasPdf) {
- openPDF(docId);
+ return openPDF(docId);
} else if (hasTextDb) {
- openText(docId);
+ return openText(docId);
} else {
console.error('No content available for document', docId);
alert('No content available for this document');
@@ -569,9 +570,14 @@ function openDocument(docId, hasPdf, hasTextDb) {
// Open PDF in modal
function openPDF(docId) {
- fetch(`/library/api/document/${docId}/pdf-url`)
- .then(res => res.json())
+ const requestId = ++documentViewerRequestId;
+ return fetch(`/library/api/document/${docId}/pdf-url`)
+ .then(res => {
+ if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
+ return res.json();
+ })
.then(data => {
+ if (requestId !== documentViewerRequestId) return;
currentPDFData = data;
document.getElementById('pdf-viewer').src = data.url;
document.getElementById('ldr-pdf-title').textContent = data.title;
@@ -579,11 +585,17 @@ function openPDF(docId) {
// Add escape key listener
document.addEventListener('keydown', handleEscapeKey);
+ })
+ .catch(err => {
+ if (requestId !== documentViewerRequestId) return;
+ console.error('Error loading PDF:', err);
+ alert('Failed to load PDF content');
});
}
// Close PDF modal
function closePDFModal() {
+ documentViewerRequestId++;
document.getElementById('ldr-pdf-modal').style.display = 'none';
document.getElementById('pdf-viewer').src = '';
currentPDFData = null;
@@ -627,9 +639,14 @@ document.getElementById('ldr-pdf-modal').addEventListener('click', function(e) {
let currentTextData = null;
function openText(docId) {
- fetch(`/library/api/document/${docId}/text`)
- .then(res => res.json())
+ const requestId = ++documentViewerRequestId;
+ return fetch(`/library/api/document/${docId}/text`)
+ .then(res => {
+ if (!res.ok) throw new Error(`HTTP error! status: ${res.status}`);
+ return res.json();
+ })
.then(data => {
+ if (requestId !== documentViewerRequestId) return;
currentTextData = data;
document.getElementById('text-viewer').textContent = data.text_content;
document.getElementById('text-title').textContent = data.title;
@@ -639,12 +656,14 @@ function openText(docId) {
document.addEventListener('keydown', handleTextEscapeKey);
})
.catch(err => {
+ if (requestId !== documentViewerRequestId) return;
console.error('Error loading text:', err);
alert('Failed to load text content');
});
}
function closeTextModal() {
+ documentViewerRequestId++;
document.getElementById('text-modal').style.display = 'none';
document.getElementById('text-viewer').textContent = '';
currentTextData = null;
@@ -710,11 +729,28 @@ function copyPath(path) {
// Current download controller for cancellation
let currentDownloadController = null;
+let currentDownloadRunId = 0;
+
+function resetDownloadProgress() {
+ const progressBar = document.getElementById('ldr-overall-progress');
+ progressBar.style.removeProperty('background-color');
+ progressBar.style.width = '0%';
+ document.getElementById('current-count').textContent = '0';
+ document.getElementById('total-count').textContent = '0';
+ document.getElementById('ldr-download-log').innerHTML = '';
+}
// Download all as text for RAG
async function downloadAllAsText() {
const btn = event.target.closest('button');
const originalContent = btn.innerHTML;
+ const downloadRunId = ++currentDownloadRunId;
+ if (currentDownloadController) {
+ currentDownloadController.abort();
+ }
+ const downloadController = new AbortController();
+ currentDownloadController = downloadController;
+ resetDownloadProgress();
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Extracting...';
btn.disabled = true;
@@ -726,15 +762,6 @@ async function downloadAllAsText() {
showDownloadProgressModal();
document.querySelector('#download-progress-modal h2').textContent = 'Text Extraction to Database';
- // Reset progress
- document.getElementById('ldr-overall-progress').style.width = '0%';
- document.getElementById('current-count').textContent = '0';
- document.getElementById('total-count').textContent = '0';
- document.getElementById('ldr-download-log').innerHTML = '';
-
- // Create abort controller for cancellation
- currentDownloadController = new AbortController();
-
// Start streaming text extraction
const response = await fetch('/library/api/download-all-text', {
method: 'POST',
@@ -743,38 +770,69 @@ async function downloadAllAsText() {
'X-CSRFToken': csrfToken
},
body: JSON.stringify({}),
- signal: currentDownloadController.signal
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
const reader = response.body.getReader();
- const decoder = new TextDecoder();
+ let terminalSeen = false;
+ const parser = createSSEJsonParser((data) => {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (data.complete) terminalSeen = true;
+ updateTextExtractionProgress(data);
+
+ // Check if extraction is complete
+ if (handleSSECompletion(
+ data,
+ (d) => {
+ alert(`Text extraction complete! Extracted ${d.total} documents to encrypted database.`);
+ },
+ () => downloadRunId === currentDownloadRunId
+ )) {
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ }
+ });
while (true) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
const {done, value} = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value);
- const lines = chunk.split('\n');
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = JSON.parse(line.slice(6));
- updateTextExtractionProgress(data);
-
- // Check if extraction is complete
- if (handleSSECompletion(data, (d) => {
- const message = saveFiles
- ? `Text extraction complete! Extracted ${d.total} documents to encrypted database and txt/ folder for RAG.`
- : `Text extraction complete! Extracted ${d.total} documents to encrypted database only.`;
- alert(message);
- })) {
- currentDownloadController = null;
- }
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+ if (done) {
+ parser.finish();
+ if (!terminalSeen) {
+ throw new Error('Text extraction stream ended before completion');
}
+ break;
}
+ parser.push(value);
}
} catch (error) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (error.name === 'AbortError') {
console.log('Text extraction cancelled by user');
const log = document.getElementById('ldr-download-log');
@@ -791,7 +849,9 @@ async function downloadAllAsText() {
} finally {
btn.innerHTML = originalContent;
btn.disabled = false;
- currentDownloadController = null;
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
}
}
@@ -838,7 +898,16 @@ function updateTextExtractionProgress(data) {
// Download all new articles with progress
async function downloadAllNew() {
const btn = event.target.closest('button');
+ if (btn.disabled) return;
+
const originalContent = btn.innerHTML;
+ const downloadRunId = ++currentDownloadRunId;
+ if (currentDownloadController) {
+ currentDownloadController.abort();
+ }
+ const downloadController = new AbortController();
+ currentDownloadController = downloadController;
+ resetDownloadProgress();
btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Preparing...';
btn.disabled = true;
@@ -852,14 +921,24 @@ async function downloadAllNew() {
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': csrfToken
- }
+ },
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (!queueResponse.ok) {
throw new Error(`HTTP error! status: ${queueResponse.status}`);
}
const queueResult = await queueResponse.json();
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
if (queueResult.queued === 0) {
alert('No new articles to download. All available articles have already been downloaded.');
@@ -871,18 +950,10 @@ async function downloadAllNew() {
// Show progress modal
showDownloadProgressModal();
- // Reset progress
- document.getElementById('ldr-overall-progress').style.width = '0%';
- document.getElementById('current-count').textContent = '0';
document.getElementById('total-count').textContent = queueResult.queued;
- document.getElementById('ldr-download-log').innerHTML = '';
// Start the bulk download with the research IDs
btn.innerHTML = originalContent;
- btn.disabled = false;
-
- // Create abort controller for cancellation
- currentDownloadController = new AbortController();
// Start streaming download
const downloadResponse = await fetch('/library/api/download-bulk', {
@@ -892,33 +963,67 @@ async function downloadAllNew() {
'X-CSRFToken': csrfToken
},
body: JSON.stringify({research_ids: queueResult.research_ids || []}),
- signal: currentDownloadController.signal
+ signal: downloadController.signal
});
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (!downloadResponse.ok) {
+ throw new Error(`HTTP error! status: ${downloadResponse.status}`);
+ }
+
const reader = downloadResponse.body.getReader();
- const decoder = new TextDecoder();
+ let terminalSeen = false;
+ const parser = createSSEJsonParser((data) => {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
+ if (data.complete) terminalSeen = true;
+ updateDownloadProgress(data);
+
+ // Check if download is complete
+ if (handleSSECompletion(
+ data,
+ () => location.reload(),
+ () => downloadRunId === currentDownloadRunId
+ )) {
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ }
+ });
while (true) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
const {done, value} = await reader.read();
- if (done) break;
-
- const chunk = decoder.decode(value);
- const lines = chunk.split('\n');
-
- for (const line of lines) {
- if (line.startsWith('data: ')) {
- const data = JSON.parse(line.slice(6));
- updateDownloadProgress(data);
-
- // Check if download is complete
- if (handleSSECompletion(data, () => location.reload())) {
- currentDownloadController = null;
- }
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+ if (done) {
+ parser.finish();
+ if (!terminalSeen) {
+ throw new Error('Download stream ended before completion');
}
+ break;
}
+ parser.push(value);
}
} catch (error) {
+ if (
+ downloadRunId !== currentDownloadRunId ||
+ currentDownloadController !== downloadController
+ ) return;
+
if (error.name === 'AbortError') {
console.log('Download cancelled by user');
const log = document.getElementById('ldr-download-log');
@@ -933,7 +1038,11 @@ async function downloadAllNew() {
btn.innerHTML = originalContent;
btn.disabled = false;
} finally {
- currentDownloadController = null;
+ if (currentDownloadController === downloadController) {
+ currentDownloadController = null;
+ }
+ btn.innerHTML = originalContent;
+ btn.disabled = false;
}
}
@@ -995,9 +1104,18 @@ function closeProgressModal() {
// Cancel downloads
function cancelDownloads() {
- if (currentDownloadController) {
- currentDownloadController.abort();
- currentDownloadController = null;
+ const downloadController = currentDownloadController;
+ // Completion already owns its delayed close/reload once the controller
+ // is cleared. A late Cancel click must not invalidate that callback.
+ if (!downloadController) {
+ closeProgressModal();
+ return;
+ }
+ const cancellationRunId = ++currentDownloadRunId;
+ currentDownloadController = null;
+
+ if (downloadController) {
+ downloadController.abort();
// Update UI to show cancellation
const progressBar = document.getElementById('ldr-overall-progress');
@@ -1005,12 +1123,10 @@ function cancelDownloads() {
// Close modal after a delay
setTimeout(() => {
+ if (cancellationRunId !== currentDownloadRunId) return;
closeProgressModal();
location.reload();
}, 1500);
- } else {
- // If no active download, just close modal
- closeProgressModal();
}
}
diff --git a/src/local_deep_research/web/templates/pages/link_analytics.html b/src/local_deep_research/web/templates/pages/link_analytics.html
index a2100f2133..a5a7979b65 100644
--- a/src/local_deep_research/web/templates/pages/link_analytics.html
+++ b/src/local_deep_research/web/templates/pages/link_analytics.html
@@ -197,8 +197,24 @@ let topDomainsChart = null;
let domainDistributionChart = null;
let sourceTypeChart = null;
let temporalTrendChart = null;
+let linkAnalyticsRequestId = 0;
+// The content script runs before base.html's deferred xss-protection.js.
+// Prefer its canonical global when available, with a scoped fallback for a
+// fast initial response or a failed dependency load.
+const linkAnalyticsEscapeHtml = window.escapeHtml || (value => String(value ?? '').replace(
+ /[&<>"'/]/g,
+ character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ '/': '&#x2F;',
+ })[character],
+));
async function loadLinkAnalytics(period = '30d') {
+ const requestId = ++linkAnalyticsRequestId;
const loading = document.getElementById('loading');
const content = document.getElementById('content');
const error = document.getElementById('error');
@@ -210,6 +226,7 @@ async function loadLinkAnalytics(period = '30d') {
try {
const response = await fetch(`/metrics/api/link-analytics?period=${period}`);
const result = await response.json();
+ if (requestId !== linkAnalyticsRequestId) return;
if (result.status === 'success') {
const data = result.data;
@@ -239,6 +256,7 @@ async function loadLinkAnalytics(period = '30d') {
throw new Error(result.message || 'Failed to load data');
}
} catch (err) {
+ if (requestId !== linkAnalyticsRequestId) return;
console.error('Error loading link analytics:', err);
error.textContent = 'Failed to load link analytics data. Please try again later.';
error.style.display = 'block';
@@ -264,7 +282,7 @@ function generateCategoryGrid(domainCategories) {
const cardHtml = `
<div class="ldr-category-card" style="border-left: 4px solid ${cardColor};">
- <div class="ldr-category-name">${window.escapeHtml(categoryName)}</div>
+ <div class="ldr-category-name">${linkAnalyticsEscapeHtml(categoryName)}</div>
<div class="ldr-category-count">${Number(count) || 0}</div>
<div class="ldr-category-percentage">${Number(percentage) || 0}%</div>
</div>
@@ -538,6 +556,8 @@ loadLinkAnalytics('30d');
// Domain Classification functionality
let classificationInProgress = false;
let domainsToClassify = [];
+let classificationRunId = 0;
+let classificationAbortController = null;
let currentDomainIndex = 0;
// Modal elements
@@ -591,7 +611,13 @@ async function loadClassificationProgress() {
}
// Start classification
-startBtn.addEventListener('click', async () => {
+async function startDomainClassification() {
+ // The start button is normally hidden as soon as a run begins, but guard
+ // the state as well so rapid/programmatic clicks cannot create two loops.
+ if (classificationInProgress) {
+ return;
+ }
+
const forceReclassify = document.getElementById('force-reclassify').checked;
// Hide info, show progress
@@ -600,56 +626,123 @@ startBtn.addEventListener('click', async () => {
document.getElementById('classification-complete').style.display = 'none';
classificationInProgress = true;
+ startBtn.disabled = true;
+ const runId = ++classificationRunId;
+ const abortController = new AbortController();
+ classificationAbortController = abortController;
+ const isCurrentRun = () => (
+ classificationInProgress &&
+ runId === classificationRunId &&
+ classificationAbortController === abortController
+ );
// Get list of domains to classify
try {
- const response = await fetch('/metrics/api/domain-classifications/progress');
+ const response = await fetch('/metrics/api/domain-classifications/progress', {
+ signal: abortController.signal
+ });
+ if (!isCurrentRun()) return;
+ if (!response.ok) {
+ throw new Error(`Unable to load classification progress (HTTP ${response.status})`);
+ }
const result = await response.json();
+ if (!isCurrentRun()) return;
- if (result.status === 'success') {
- const totalDomains = result.progress.total_domains;
-
- // Start classification process
- await classifyAllDomains(forceReclassify);
+ if (result.status !== 'success') {
+ throw new Error(result.message || 'Unable to load classification progress');
}
+
+ // Start classification process
+ await classifyAllDomains(forceReclassify, runId, abortController.signal);
} catch (error) {
+ if (!isCurrentRun() || error.name === 'AbortError') return;
console.error('Error starting classification:', error);
addLogEntry(`Error: ${error.message}`, 'error');
+ // Make the start control reachable again so a transient failure can
+ // be retried without closing and reopening the modal.
+ document.getElementById('classification-info').style.display = 'block';
+ document.getElementById('classification-progress').style.display = 'none';
+ } finally {
+ if (runId === classificationRunId) {
+ classificationInProgress = false;
+ classificationAbortController = null;
+ startBtn.disabled = false;
+ }
}
-});
+}
+
+startBtn.addEventListener('click', startDomainClassification);
// Stop classification
stopBtn.addEventListener('click', () => {
classificationInProgress = false;
+ classificationRunId++;
+ if (classificationAbortController) {
+ classificationAbortController.abort();
+ classificationAbortController = null;
+ }
+ startBtn.disabled = false;
addLogEntry('Classification stopped by user', 'error');
});
// Classify all domains
-async function classifyAllDomains(forceUpdate = false) {
+async function classifyAllDomains(
+ forceUpdate = false,
+ runId = classificationRunId,
+ signal = classificationAbortController?.signal
+) {
+ const isCurrentRun = () => (
+ classificationInProgress && runId === classificationRunId
+ );
const logContainer = document.getElementById('classification-log');
logContainer.innerHTML = '';
try {
// Get all domains from the progress endpoint which now includes all domains
- const progressResponse = await fetch('/metrics/api/domain-classifications/progress');
+ const progressResponse = await fetch('/metrics/api/domain-classifications/progress', {
+ signal
+ });
+ if (!isCurrentRun()) return;
+ if (!progressResponse.ok) {
+ throw new Error(`Unable to load domains (HTTP ${progressResponse.status})`);
+ }
const progressResult = await progressResponse.json();
+ if (!isCurrentRun()) return;
+
+ if (progressResult.status !== 'success') {
+ throw new Error(progressResult.message || 'Unable to load domains for classification');
+ }
- if (progressResult.status === 'success' && progressResult.progress.all_domains) {
+ if (!progressResult.progress?.all_domains) {
+ throw new Error('Classification progress did not include a domain list');
+ }
+
+ {
// Get all domains from the progress endpoint
const allDomains = new Set(progressResult.progress.all_domains);
// Get existing classifications to check which need updating
if (!forceUpdate) {
- const classResponse = await fetch('/metrics/api/domain-classifications');
+ const classResponse = await fetch('/metrics/api/domain-classifications', {
+ signal
+ });
+ if (!isCurrentRun()) return;
+ if (!classResponse.ok) {
+ throw new Error(`Unable to load existing classifications (HTTP ${classResponse.status})`);
+ }
const classResult = await classResponse.json();
+ if (!isCurrentRun()) return;
- if (classResult.status === 'success') {
- const classified = new Set(classResult.classifications.map(c => c.domain));
- // Remove already classified domains
- classified.forEach(d => allDomains.delete(d));
+ if (classResult.status !== 'success') {
+ throw new Error(classResult.message || 'Unable to load existing classifications');
}
+ const classified = new Set(classResult.classifications.map(c => c.domain));
+ // Remove already classified domains
+ classified.forEach(d => allDomains.delete(d));
}
+ if (!isCurrentRun()) return;
+
domainsToClassify = Array.from(allDomains);
const totalToClassify = domainsToClassify.length;
@@ -690,14 +783,17 @@ async function classifyAllDomains(forceUpdate = false) {
method: 'POST',
headers: headers,
credentials: 'same-origin', // Include cookies for session
+ signal,
body: JSON.stringify({
domain: domain,
force_update: forceUpdate
})
});
+ if (!isCurrentRun()) return;
if (!response.ok) {
const errorText = await response.text();
+ if (!isCurrentRun()) return;
console.error(`HTTP error! status: ${response.status}, body: ${errorText}`);
failed++;
addLogEntry(`✗ ${domain}: HTTP ${response.status} error`, 'error');
@@ -705,6 +801,7 @@ async function classifyAllDomains(forceUpdate = false) {
}
const result = await response.json();
+ if (!isCurrentRun()) return;
if (result.status === 'success') {
classified++;
@@ -720,6 +817,7 @@ async function classifyAllDomains(forceUpdate = false) {
await new Promise(resolve => setTimeout(resolve, 1000)); // Increased delay
} catch (error) {
+ if (!isCurrentRun() || error.name === 'AbortError') return;
console.error(`Error classifying ${domain}:`, error);
failed++;
addLogEntry(`✗ ${domain}: ${error.message}`, 'error');
@@ -732,11 +830,12 @@ async function classifyAllDomains(forceUpdate = false) {
}
} catch (error) {
+ if (!isCurrentRun() || error.name === 'AbortError') return;
console.error('Error during classification:', error);
addLogEntry(`Fatal error: ${error.message}`, 'error');
+ throw error;
}
- classificationInProgress = false;
}
// Add log entry
@@ -781,7 +880,7 @@ async function loadClassificationsAndUpdateDisplay() {
const badge = document.createElement('span');
badge.className = 'ldr-classified-badge';
badge.textContent = classification.category;
- badge.title = `${window.escapeHtml(classification.subcategory)} (${Math.round(Number(classification.confidence) * 100)}% confidence)`;
+ badge.title = `${linkAnalyticsEscapeHtml(classification.subcategory)} (${Math.round(Number(classification.confidence) * 100)}% confidence)`;
domainName.appendChild(badge);
}
}
diff --git a/src/local_deep_research/web/templates/pages/metrics.html b/src/local_deep_research/web/templates/pages/metrics.html
index b871bff674..a4bdb6cc35 100644
--- a/src/local_deep_research/web/templates/pages/metrics.html
+++ b/src/local_deep_research/web/templates/pages/metrics.html
@@ -523,6 +523,7 @@
let timeSeriesChart = null;
let currentPeriod = '30d'; // Default period
let currentMode = 'all'; // Default research mode
+ let metricsRequestId = 0;
// Format large numbers with commas
function formatNumber(num) {
return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
@@ -559,21 +560,31 @@
}
// Load metrics data for current time period
async function loadMetrics(period = currentPeriod) {
+ const requestId = ++metricsRequestId;
+ // A mode click can land while the basic request is awaiting. Capture
+ // the complete filter intent once so the enhanced and secondary
+ // requests cannot accidentally belong to a different mode.
+ const requestMode = currentMode;
+ const isCurrentRequest = () => requestId === metricsRequestId;
try {
// Show loading state
document.getElementById('loading').style.display = 'block';
document.getElementById('metrics-content').style.display = 'none';
document.getElementById('error').style.display = 'none';
- const basicResponse = await fetch(`/metrics/api/metrics?period=${period}&mode=${currentMode}`);
+ const basicResponse = await fetch(`/metrics/api/metrics?period=${period}&mode=${requestMode}`);
+ if (!isCurrentRequest()) return;
if (!basicResponse.ok) {
throw new Error(`Basic API failed: ${basicResponse.status}`);
}
const basicData = await basicResponse.json();
- const enhancedResponse = await fetch(`/metrics/api/metrics/enhanced?period=${period}&mode=${currentMode}`);
+ if (!isCurrentRequest()) return;
+ const enhancedResponse = await fetch(`/metrics/api/metrics/enhanced?period=${period}&mode=${requestMode}`);
+ if (!isCurrentRequest()) return;
if (!enhancedResponse.ok) {
throw new Error(`Enhanced API failed: ${enhancedResponse.status}`);
}
const enhancedData = await enhancedResponse.json();
+ if (!isCurrentRequest()) return;
if (basicData.status === 'success') {
metricsData = basicData.metrics;
// Check if we have any data at all
@@ -589,12 +600,14 @@
createTimeSeriesChart(enhancedData.metrics.time_series_data);
createSearchActivityChart(enhancedData.metrics.search_time_series);
// Re-setup tooltips for any new content
- setTimeout(setupTooltipPositioning, 100);
+ setTimeout(() => {
+ if (isCurrentRequest()) setupTooltipPositioning();
+ }, 100);
}
// Load cost analytics
- loadCostAnalytics(period);
+ loadCostAnalytics(period, requestId);
// Load rate limiting analytics
- loadRateLimitingAnalytics(period);
+ loadRateLimitingAnalytics(period, requestId);
document.getElementById('loading').style.display = 'none';
document.getElementById('metrics-content').style.display = 'block';
} else {
@@ -604,13 +617,16 @@
if (enhancedData.status === 'success') {
displayEnhancedMetrics(enhancedData.metrics);
// Re-setup tooltips for any new content
- setTimeout(setupTooltipPositioning, 100);
+ setTimeout(() => {
+ if (isCurrentRequest()) setupTooltipPositioning();
+ }, 100);
}
}
} else {
showError();
}
} catch (error) {
+ if (!isCurrentRequest()) return;
showError();
}
}
@@ -1371,20 +1387,23 @@
}
}
// Load cost analytics data
- async function loadCostAnalytics(period = currentPeriod) {
+ async function loadCostAnalytics(period = currentPeriod, requestId = metricsRequestId) {
try {
const response = await fetch(`/metrics/api/cost-analytics?period=${period}`);
+ if (requestId !== metricsRequestId) return;
if (!response.ok) {
displayCostData(null);
return;
}
const data = await response.json();
+ if (requestId !== metricsRequestId) return;
if (data.status === 'success') {
displayCostData(data);
} else {
displayCostData(null);
}
} catch (error) {
+ if (requestId !== metricsRequestId) return;
displayCostData(null);
}
}
@@ -1411,20 +1430,23 @@
document.getElementById('total-cost-breakdown').textContent = formatCurrency(overview.total_cost);
}
// Load rate limiting analytics
- async function loadRateLimitingAnalytics(period = currentPeriod) {
+ async function loadRateLimitingAnalytics(period = currentPeriod, requestId = metricsRequestId) {
try {
const response = await fetch(`/metrics/api/rate-limiting?period=${period}`);
+ if (requestId !== metricsRequestId) return;
if (!response.ok) {
displayRateLimitingData(null);
return;
}
const data = await response.json();
+ if (requestId !== metricsRequestId) return;
if (data.status === 'success') {
displayRateLimitingData(data.data);
} else {
displayRateLimitingData(null);
}
} catch (error) {
+ if (requestId !== metricsRequestId) return;
displayRateLimitingData(null);
}
}
diff --git a/src/local_deep_research/web/templates/pages/news-subscription-form.html b/src/local_deep_research/web/templates/pages/news-subscription-form.html
index 3ebe4af998..40ccc02656 100644
--- a/src/local_deep_research/web/templates/pages/news-subscription-form.html
+++ b/src/local_deep_research/web/templates/pages/news-subscription-form.html
@@ -54,7 +54,7 @@
<div class="ldr-form-text">
Common values: 1 (every minute), 60 (hourly), 1440 (daily), 10080 (weekly)
<br>
- <small class="text-muted">A random jitter will be added to prevent all subscriptions from running at once</small>
+ <small id="subscription-jitter-info" class="text-muted">A random jitter will be added to prevent all subscriptions from running at once</small>
</div>
</div>
@@ -190,6 +190,22 @@ let modelOptions = [];
let modelDropdownInstance = null;
let searchEngineOptions = [];
let searchEngineDropdownInstance = null;
+let subscriptionActionInFlight = false;
+let subscriptionNavigationPending = false;
+
+function isValidResearchId(researchId) {
+ return (typeof researchId === 'string' && researchId.trim() !== '') ||
+ (typeof researchId === 'number' && Number.isFinite(researchId));
+}
+
+function scheduleSubscriptionRedirect(url) {
+ subscriptionNavigationPending = true;
+ setTimeout(() => {
+ subscriptionNavigationPending = false;
+ subscriptionActionInFlight = false;
+ window.location.href = url;
+ }, 1500);
+}
// Debug: Log initial values from server
console.log('Initial values from server:', {
@@ -686,6 +702,11 @@ async function handleSubscriptionSubmit(e) {
const questionsPerIteration = document.getElementById('subscription-questions').value;
const strategy = document.getElementById('subscription-strategy').value;
+ if (subscriptionActionInFlight) {
+ return;
+ }
+ subscriptionActionInFlight = true;
+
try {
const url = {% if subscription %}'/news/api/subscriptions/{{ subscription.id }}'{% else %}'/news/api/subscribe'{% endif %};
const method = {% if subscription %}'PUT'{% else %}'POST'{% endif %};
@@ -720,26 +741,28 @@ async function handleSubscriptionSubmit(e) {
showAlert('Subscription {{ "updated" if subscription else "created" }} successfully!', 'success');
// Redirect to appropriate page after a short delay
- setTimeout(() => {
- {% if subscription %}
- // Editing - go back to subscriptions page
- window.location.href = '/news/subscriptions';
- {% else %}
- // Creating - go to news feed
- window.location.href = '/news';
- {% endif %}
- }, 1500);
+ {% if subscription %}
+ // Editing - go back to subscriptions page
+ scheduleSubscriptionRedirect('/news/subscriptions');
+ {% else %}
+ // Creating - go to news feed
+ scheduleSubscriptionRedirect('/news');
+ {% endif %}
} else {
const error = await response.json();
showAlert('Error: ' + (error.error || 'Failed to save subscription'), 'error');
}
} catch (error) {
showAlert('Error: ' + error.message, 'error');
+ } finally {
+ if (!subscriptionNavigationPending) {
+ subscriptionActionInFlight = false;
+ }
}
}
// Handle test run
-async function handleTestRun(event) {
+async function handleTestRun(event, actionAlreadyOwned = false) {
if (event) {
event.preventDefault();
event.stopPropagation();
@@ -747,6 +770,7 @@ async function handleTestRun(event) {
console.log('Test Run button clicked');
+ let ownsSubscriptionAction = false;
try {
const query = document.getElementById('subscription-query').value;
console.log('Query value:', query);
@@ -772,6 +796,14 @@ async function handleTestRun(event) {
return;
}
+ if (!actionAlreadyOwned) {
+ if (subscriptionActionInFlight) {
+ return;
+ }
+ subscriptionActionInFlight = true;
+ ownsSubscriptionAction = true;
+ }
+
const iterations = document.getElementById('subscription-iterations').value;
const questions = document.getElementById('subscription-questions').value;
const strategy = document.getElementById('subscription-strategy').value || 'source-based';
@@ -845,7 +877,8 @@ async function handleTestRun(event) {
const data = await response.json();
console.log('Research started:', data);
- if (data.status === 'success' && data.research_id) {
+ if (['success', 'queued'].includes(data.status) &&
+ isValidResearchId(data.research_id)) {
showAlert('Research started successfully! Redirecting to news page...', 'success');
// Store the research ID and query so the news page can track it
@@ -853,9 +886,7 @@ async function handleTestRun(event) {
sessionStorage.setItem('activeTestRunQuery', query);
// Redirect to news page after a short delay
- setTimeout(() => {
- window.location.href = '/news';
- }, 1500);
+ scheduleSubscriptionRedirect('/news');
} else {
showAlert('Unexpected response from server', 'error');
}
@@ -867,6 +898,10 @@ async function handleTestRun(event) {
} catch (outerError) {
console.error('Error in handleTestRun:', outerError);
showAlert('An unexpected error occurred', 'error');
+ } finally {
+ if (ownsSubscriptionAction && !subscriptionNavigationPending) {
+ subscriptionActionInFlight = false;
+ }
}
}
@@ -879,6 +914,11 @@ async function handleCreateAndRun(event) {
console.log('Create and Run button clicked');
+ if (subscriptionActionInFlight) {
+ return;
+ }
+ subscriptionActionInFlight = true;
+
try {
// First create the subscription
const query = document.getElementById('subscription-query').value;
@@ -941,11 +981,15 @@ async function handleCreateAndRun(event) {
// Now run the subscription using the test run functionality
console.log('Subscription created, now starting immediate research run');
- await handleTestRun();
+ await handleTestRun(undefined, true);
} catch (error) {
console.error('Error in create and run:', error);
showAlert('Error: ' + error.message, 'error');
+ } finally {
+ if (!subscriptionNavigationPending) {
+ subscriptionActionInFlight = false;
+ }
}
}
@@ -978,7 +1022,18 @@ async function loadJitterInfo() {
});
if (response.ok) {
const data = await response.json();
- const maxJitter = data.settings?.max_jitter_seconds || 300;
+ // FastAPI exposes the scheduler configuration under `config`.
+ // Keep the legacy `settings` fallback for older deployments, and
+ // normalize before interpolating the value into the static hint.
+ const rawMaxJitter = data.config?.max_jitter_seconds
+ ?? data.settings?.max_jitter_seconds
+ ?? 300;
+ const numericMaxJitter = (
+ typeof rawMaxJitter === 'number' ||
+ (typeof rawMaxJitter === 'string' && rawMaxJitter.trim() !== '')
+ ) ? Number(rawMaxJitter) : NaN;
+ const maxJitter = Number.isFinite(numericMaxJitter) &&
+ numericMaxJitter >= 0 ? numericMaxJitter : 300;
// Calculate jitter range in human-readable format
const formatJitter = (seconds) => {
@@ -1001,7 +1056,7 @@ async function loadJitterInfo() {
const element = document.getElementById('subscription-jitter-info');
if (element) {
- element.innerHTML = `<small class="text-muted">${jitterText}</small>`;
+ element.innerHTML = jitterText;
}
}
} catch (error) {
diff --git a/src/local_deep_research/web/templates/pages/star_reviews.html b/src/local_deep_research/web/templates/pages/star_reviews.html
index 51601c7378..8097abf600 100644
--- a/src/local_deep_research/web/templates/pages/star_reviews.html
+++ b/src/local_deep_research/web/templates/pages/star_reviews.html
@@ -230,6 +230,7 @@
<script>
let llmChart, searchEngineChart, trendsChart, doughnutChart, modeChart, llmBreakdownChart, qualityRadarChart;
+let starReviewsRequestId = 0;
const escapeHtml = window.escapeHtml || function(text) {
const div = document.createElement('div');
@@ -243,16 +244,19 @@ document.addEventListener('DOMContentLoaded', function() {
});
async function loadStarReviews() {
+ const requestId = ++starReviewsRequestId;
const period = document.getElementById('period-select').value;
showLoading();
try {
const response = await fetch(`/metrics/api/star-reviews?period=${period}`);
+ if (requestId !== starReviewsRequestId) return;
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const data = await response.json();
+ if (requestId !== starReviewsRequestId) return;
if (data.error) {
showError(data.error);
return;
@@ -273,6 +277,7 @@ async function loadStarReviews() {
showContent();
announceChartStates();
} catch (error) {
+ if (requestId !== starReviewsRequestId) return;
console.error('Error loading star reviews:', error);
showError('Failed to load star reviews data: ' + error.message);
}
diff --git a/src/local_deep_research/web/templates/pages/zotero.html b/src/local_deep_research/web/templates/pages/zotero.html
index a6f8bd6174..f9f1d90633 100644
--- a/src/local_deep_research/web/templates/pages/zotero.html
+++ b/src/local_deep_research/web/templates/pages/zotero.html
@@ -232,6 +232,8 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
const csrf = document.querySelector('meta[name="csrf-token"]')?.content || '';
const msg = document.getElementById('zotero-msg');
const $ = (id) => document.getElementById(id);
+ let nextStatusRequestId = 0;
+ let latestRenderedStatusRequestId = 0;
function setMsg(text, ok) {
msg.textContent = text || '';
@@ -501,14 +503,19 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
}
async function loadStatus() {
- // Returns true while any collection is still syncing. Must never reject:
- // it is polled on an interval while a sync runs, and a rejection there
- // would stall the Sync button's restore loop.
+ // Returns true/false for a current successful snapshot and null for a
+ // transient failure or stale response. Polling must not mistake a
+ // failed request for proof that a previously observed sync completed.
+ const requestId = ++nextStatusRequestId;
const el = $('zotero-status');
try {
const s = await getJSON('/library/api/zotero/status');
+ if (!s || !s.success || !Array.isArray(s.collections)) return null;
+ if (requestId < latestRenderedStatusRequestId) return null;
+
+ latestRenderedStatusRequestId = requestId;
renderProgress(s && s.progress);
- if (!s.success || !s.collections || !s.collections.length) {
+ if (!s.collections.length) {
el.innerHTML = '<div class="ldr-zotero-empty">No syncs yet.</div>';
return false;
}
@@ -529,7 +536,7 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
return anySyncing;
} catch (e) {
// Transient error — keep the previous content and let polling continue.
- return false;
+ return null;
}
}
@@ -659,18 +666,42 @@ table.ldr-zotero-table th, table.ldr-zotero-table td {
// grace window, or after a hard cap — so a large-library sync
// isn't cut off and the button doesn't restore prematurely.
// Fast cadence: the poll also drives the progress bar.
- let elapsed = 0, sawSyncing = false;
+ let elapsed = 0, sawSyncing = false, pollInFlight = false;
+ let pollFinished = false;
const STEP = 1500, GRACE = 20000, MAX = 15 * 60 * 1000;
- const t = setInterval(async () => {
- const syncing = await loadStatus();
- if (syncing) sawSyncing = true;
+ let t = null;
+ const finishPolling = (completed) => {
+ if (pollFinished) return;
+ pollFinished = true;
+ clearInterval(t);
+ restore();
+ if (completed) setSaveMsg('Sync finished.', true);
+ // Collections may have changed Zotero-side.
+ loadCollectionsList(false);
+ };
+ t = setInterval(async () => {
elapsed += STEP;
- if ((sawSyncing && !syncing) || (!sawSyncing && elapsed >= GRACE) || elapsed >= MAX) {
- clearInterval(t);
- restore();
- if (sawSyncing && !syncing) setSaveMsg('Sync finished.', true);
- // Collections may have changed Zotero-side.
- loadCollectionsList(false);
+ if (elapsed >= MAX) {
+ finishPolling(false);
+ return;
+ }
+ if (pollFinished || pollInFlight) return;
+
+ pollInFlight = true;
+ try {
+ const syncing = await loadStatus();
+ if (pollFinished) return;
+ if (syncing === null) return;
+
+ if (syncing) sawSyncing = true;
+ if (
+ (sawSyncing && !syncing) ||
+ (!sawSyncing && elapsed >= GRACE)
+ ) {
+ finishPolling(sawSyncing && !syncing);
+ }
+ } finally {
+ pollInFlight = false;
}
}, STEP);
} else {
diff --git a/tests/ci/test_fastapi_migration_quality_workflow.py b/tests/ci/test_fastapi_migration_quality_workflow.py
index 4bada86b70..ed1aed0ee4 100644
--- a/tests/ci/test_fastapi_migration_quality_workflow.py
+++ b/tests/ci/test_fastapi_migration_quality_workflow.py
@@ -48,6 +48,15 @@ REQUIRED_TEST_SUPPORT_TRIGGERS = {
"tests/test_end_to_end_journeys.py",
}
+REQUIRED_VITEST_TRIGGERS = {
+ "package.json",
+ "package-lock.json",
+ "vite.config.js",
+ "src/local_deep_research/web/static/js/**",
+ "src/local_deep_research/web/templates/**",
+ "tests/js/**",
+}
+
@pytest.fixture(scope="module")
def workflow():
@@ -114,6 +123,24 @@ def test_cross_module_test_support_changes_trigger_the_quality_workflow(
)
+def test_frontend_changes_trigger_the_vitest_job(workflow):
+ triggers = _pull_request_paths(workflow)
+ missing = REQUIRED_VITEST_TRIGGERS - triggers
+ assert not missing, (
+ "frontend migration changes can bypass Vitest; missing "
+ f"pull_request.paths entries: {sorted(missing)}"
+ )
+
+
+def test_vitest_job_runs_the_full_seeded_suite(workflow):
+ steps = {step["name"]: step for step in workflow["jobs"]["vitest"]["steps"]}
+ assert steps["Set up Node.js"]["with"]["node-version"] == "24"
+ assert steps["Install frontend dependencies"]["run"] == "npm ci"
+ assert steps["Run full Vitest suite (shuffle seed 3299)"]["run"] == (
+ "npm test -- --sequence.shuffle --sequence.seed=3299"
+ )
+
+
def test_workflow_guards_its_definition_and_both_target_branches(workflow):
"""The focused gate must run when its own contract or either target moves."""
pull_request = workflow["on"]["pull_request"]
diff --git a/tests/infrastructure_tests/test_csrf_api.test.js b/tests/infrastructure_tests/test_csrf_api.test.js
index 29e008f644..f1f278726a 100644
--- a/tests/infrastructure_tests/test_csrf_api.test.js
+++ b/tests/infrastructure_tests/test_csrf_api.test.js
@@ -357,6 +357,10 @@ describe('Error handling - network and timeout', () => {
clearMetaToken();
});
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
test('network error: CSRF header still set before rejection', async () => {
setMetaToken('net-error-token');
global.fetch.mockRejectedValue(new TypeError('Failed to fetch'));
@@ -365,21 +369,44 @@ describe('Error handling - network and timeout', () => {
expect(global.SafeLogger.error).toHaveBeenCalled();
});
- test('AbortError maps to "Request timed out"', async () => {
- const abortError = new Error('The operation was aborted');
- abortError.name = 'AbortError';
- global.fetch.mockRejectedValue(abortError);
+ test('an internally triggered AbortError maps to "Request timed out"', async () => {
+ jest.useFakeTimers();
+ global.fetch.mockImplementation((_url, options) =>
+ new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => {
+ const abortError = new Error('The operation was aborted');
+ abortError.name = 'AbortError';
+ reject(abortError);
+ }, { once: true });
+ })
+ );
- await expect(fetchWithErrorHandling('/api/test'))
- .rejects.toThrow('Request timed out');
+ const request = fetchWithErrorHandling('/api/test', { timeout: 25 });
+ const rejection = expect(request).rejects.toThrow('Request timed out');
+
+ await jest.advanceTimersByTimeAsync(25);
+ await rejection;
});
- test('SafeLogger.error NOT called on AbortError', async () => {
+ test('SafeLogger.error is not called for caller cancellation', async () => {
+ const callerController = new AbortController();
const abortError = new Error('The operation was aborted');
abortError.name = 'AbortError';
- global.fetch.mockRejectedValue(abortError);
+ global.fetch.mockImplementation((_url, options) =>
+ new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => {
+ reject(abortError);
+ }, { once: true });
+ })
+ );
+
+ const request = fetchWithErrorHandling('/api/test', {
+ signal: callerController.signal
+ });
+ const rejection = expect(request).rejects.toBe(abortError);
- await expect(fetchWithErrorHandling('/api/test')).rejects.toThrow();
+ callerController.abort();
+ await rejection;
expect(global.SafeLogger.error).not.toHaveBeenCalled();
});
diff --git a/tests/js/app-runtime.test.js b/tests/js/app-runtime.test.js
new file mode 100644
index 0000000000..2c0aadc720
--- /dev/null
+++ b/tests/js/app-runtime.test.js
@@ -0,0 +1,147 @@
+/**
+ * Direct contract tests for the Vite application entry point.
+ *
+ * The browser bundle is also exercised by the build and UI suites, but these
+ * tests pin the global compatibility surface consumed by classic scripts and
+ * the DOMContentLoaded bootstrap without requiring a browser process.
+ */
+
+const mocks = vi.hoisted(() => ({
+ marked: {
+ setOptions: vi.fn(),
+ use: vi.fn(),
+ },
+ io: vi.fn(),
+ hljs: {
+ getLanguage: vi.fn(),
+ highlight: vi.fn(),
+ highlightElement: vi.fn(),
+ },
+ jsPDF: vi.fn(),
+ html2canvas: vi.fn(),
+ DOMPurify: { sanitize: vi.fn() },
+ markedKatex: vi.fn(() => ({ name: 'katex-extension' })),
+ Chart: { register: vi.fn() },
+ annotationPlugin: { id: 'annotation' },
+ Tooltip: vi.fn(),
+ Popover: vi.fn(),
+}));
+
+vi.mock('marked', () => ({ marked: mocks.marked }));
+vi.mock('socket.io-client', () => ({ default: mocks.io }));
+vi.mock('highlight.js', () => ({ default: mocks.hljs }));
+vi.mock('jspdf', () => ({ default: mocks.jsPDF }));
+vi.mock('html2canvas', () => ({ default: mocks.html2canvas }));
+vi.mock('dompurify', () => ({ default: mocks.DOMPurify }));
+vi.mock('marked-katex-extension', () => ({ default: mocks.markedKatex }));
+vi.mock('bootstrap', () => ({
+ Tooltip: mocks.Tooltip,
+ Popover: mocks.Popover,
+}));
+vi.mock('chart.js/auto', () => ({ default: mocks.Chart }));
+vi.mock('chartjs-adapter-date-fns', () => ({}));
+vi.mock('chartjs-plugin-annotation', () => ({
+ default: mocks.annotationPlugin,
+}));
+
+let app;
+
+beforeAll(async () => {
+ document.body.innerHTML = `
+ <pre><code id="code-block">const value = 1;</code></pre>
+ <button id="tooltip" data-bs-toggle="tooltip"></button>
+ <button id="popover" data-bs-toggle="popover"></button>
+ `;
+ app = await import('@js/app.js');
+});
+
+afterAll(() => {
+ document.body.innerHTML = '';
+ for (const name of [
+ 'marked',
+ 'io',
+ 'Chart',
+ 'hljs',
+ 'jsPDF',
+ 'html2canvas',
+ 'bootstrap',
+ 'DOMPurify',
+ ]) {
+ delete window[name];
+ }
+});
+
+it('publishes the checked-in vendor compatibility API on window', () => {
+ expect(window.marked).toBe(mocks.marked);
+ expect(window.io).toBe(mocks.io);
+ expect(window.Chart).toBe(mocks.Chart);
+ expect(window.hljs).toBe(mocks.hljs);
+ expect(window.jsPDF).toBe(mocks.jsPDF);
+ expect(window.html2canvas).toBe(mocks.html2canvas);
+ expect(window.DOMPurify).toBe(mocks.DOMPurify);
+ expect(window.bootstrap).toMatchObject({
+ Tooltip: mocks.Tooltip,
+ Popover: mocks.Popover,
+ });
+
+ expect(app).toMatchObject({
+ marked: mocks.marked,
+ io: mocks.io,
+ Chart: mocks.Chart,
+ DOMPurify: mocks.DOMPurify,
+ });
+ expect(mocks.Chart.register).toHaveBeenCalledWith(mocks.annotationPlugin);
+});
+
+it('configures safe Markdown highlighting and the KaTeX extension', () => {
+ expect(mocks.marked.setOptions).toHaveBeenCalledOnce();
+ const options = mocks.marked.setOptions.mock.calls[0][0];
+ expect(options).toMatchObject({
+ headerIds: false,
+ mangle: false,
+ smartypants: false,
+ });
+
+ mocks.hljs.getLanguage.mockReturnValueOnce(false);
+ expect(options.highlight('plain code', 'unknown')).toBe('plain code');
+
+ mocks.hljs.getLanguage.mockReturnValueOnce(true);
+ mocks.hljs.highlight.mockReturnValueOnce({ value: '&lt;safe&gt;' });
+ expect(options.highlight('<safe>', 'javascript')).toBe('&lt;safe&gt;');
+ expect(mocks.hljs.highlight).toHaveBeenCalledWith('<safe>', {
+ language: 'javascript',
+ });
+
+ const highlightError = new Error('bad grammar');
+ mocks.hljs.getLanguage.mockReturnValueOnce(true);
+ mocks.hljs.highlight.mockImplementationOnce(() => {
+ throw highlightError;
+ });
+ const errorSpy = vi.spyOn(SafeLogger, 'error');
+ expect(options.highlight('fallback', 'javascript')).toBe('fallback');
+ expect(errorSpy).toHaveBeenCalledWith('Highlight error:', highlightError);
+ errorSpy.mockRestore();
+
+ expect(mocks.markedKatex).toHaveBeenCalledWith({
+ throwOnError: false,
+ errorColor: 'currentColor',
+ });
+ expect(mocks.marked.use).toHaveBeenCalledWith({
+ name: 'katex-extension',
+ });
+});
+
+it('initializes code highlighting, tooltips, and popovers when the DOM is ready', () => {
+ mocks.hljs.highlightElement.mockClear();
+ mocks.Tooltip.mockClear();
+ mocks.Popover.mockClear();
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ expect(mocks.hljs.highlightElement)
+ .toHaveBeenCalledWith(document.getElementById('code-block'));
+ expect(mocks.Tooltip)
+ .toHaveBeenCalledWith(document.getElementById('tooltip'));
+ expect(mocks.Popover)
+ .toHaveBeenCalledWith(document.getElementById('popover'));
+});
diff --git a/tests/js/collection-create-runtime.test.js b/tests/js/collection-create-runtime.test.js
new file mode 100644
index 0000000000..f11eeac61d
--- /dev/null
+++ b/tests/js/collection-create-runtime.test.js
@@ -0,0 +1,254 @@
+/**
+ * Browser contracts for creating a collection through the migrated RAG
+ * router. The page owns this fetch directly, so generic API-helper tests do
+ * not cover its JSON shape or its success/error rendering.
+ */
+
+function installFixture() {
+ document.body.innerHTML = `
+ <form id="create-collection-form">
+ <input id="collection-name" name="name" value=" Evidence ">
+ <textarea name="description"> Sources for review </textarea>
+ <input id="collection-is-public" type="checkbox" checked>
+ <input id="collection-agent-enabled" type="checkbox">
+ <button id="create-collection-btn" type="submit">Create</button>
+ </form>
+ <span id="name-counter"></span>
+ <div id="create-results" style="display: none"></div>
+ `;
+}
+
+let documentListeners = [];
+
+async function loadPage() {
+ await import('@js/collection_create.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ documentListeners = [];
+ const addDocumentListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ installFixture();
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: { COLLECTION_CREATE: '/library/api/collections' },
+ });
+ vi.stubGlobal('URLValidator', {});
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-collection') };
+ window.escapeHtml = value => String(value ?? '').replace(
+ /[&<>"']/g,
+ character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ })[character],
+ );
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.escapeHtml;
+ delete window.__collectionCreateXss;
+ document.body.replaceChildren();
+});
+
+it('POSTs the page fields and renders the FastAPI success envelope', async () => {
+ const safeFetchWithAuth = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ collection: { id: 'collection-3299' },
+ }),
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ await vi.waitFor(() => expect(safeFetchWithAuth).toHaveBeenCalledOnce());
+ expect(safeFetchWithAuth).toHaveBeenCalledWith(
+ '/library/api/collections',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-collection',
+ },
+ body: JSON.stringify({
+ name: 'Evidence',
+ description: 'Sources for review',
+ type: 'user_uploads',
+ is_public: true,
+ agent_enabled: false,
+ }),
+ },
+ );
+ await vi.waitFor(() => {
+ expect(document.getElementById('create-results').textContent)
+ .toContain('Collection Created!');
+ });
+ expect(document.getElementById('create-results').textContent)
+ .toContain('collection-3299');
+ expect(document.getElementById('create-collection-btn').disabled)
+ .toBe(false);
+});
+
+it('shows the migrated error envelope and restores the submit control', async () => {
+ const safeFetchWithAuth = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: 'A collection with this name already exists',
+ }),
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('create-results').textContent)
+ .toContain('A collection with this name already exists');
+ });
+ const submit = document.getElementById('create-collection-btn');
+ expect(submit.disabled).toBe(false);
+ expect(submit.textContent).toContain('Create Collection');
+});
+
+it('renders a hostile server error as inert text', async () => {
+ const hostile = '<img src=x onerror="window.__collectionCreateXss=true">';
+ vi.stubGlobal('safeFetchWithAuth', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: hostile,
+ }),
+ }));
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ const results = document.getElementById('create-results');
+ await vi.waitFor(() => expect(results.textContent).toContain(hostile));
+ expect(results.querySelector('img')).toBeNull();
+ expect(window.__collectionCreateXss).toBeUndefined();
+});
+
+it('rejects a whitespace-only name before issuing a request', async () => {
+ const safeFetchWithAuth = vi.fn();
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+ await loadPage();
+
+ document.getElementById('collection-name').value = ' ';
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ expect(safeFetchWithAuth).not.toHaveBeenCalled();
+ expect(document.getElementById('create-results').textContent)
+ .toContain('Collection name is required');
+ expect(document.getElementById('create-collection-btn').disabled)
+ .toBe(false);
+});
+
+it('uses safe defaults when optional fields and the API helper are absent', async () => {
+ document.querySelector('[name="description"]').remove();
+ document.getElementById('collection-is-public').remove();
+ document.getElementById('collection-agent-enabled').remove();
+ delete window.api;
+ const safeFetchWithAuth = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: false, error: 'Not created' }),
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ await vi.waitFor(() => {
+ expect(safeFetchWithAuth).toHaveBeenCalledOnce();
+ expect(document.getElementById('create-results').textContent)
+ .toContain('Not created');
+ });
+ expect(safeFetchWithAuth.mock.calls[0][1]).toMatchObject({
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': '',
+ },
+ body: JSON.stringify({
+ name: 'Evidence',
+ description: '',
+ type: 'user_uploads',
+ is_public: false,
+ agent_enabled: true,
+ }),
+ });
+});
+
+it('renders a rejected request safely and restores the submit control', async () => {
+ const hostile = '<img src=x onerror="window.__collectionCreateXss=true">';
+ vi.stubGlobal('safeFetchWithAuth', vi.fn().mockRejectedValue(new Error(hostile)));
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ const results = document.getElementById('create-results');
+ await vi.waitFor(() => expect(results.textContent).toContain(hostile));
+ expect(results.querySelector('img')).toBeNull();
+ expect(window.__collectionCreateXss).toBeUndefined();
+ expect(document.getElementById('create-collection-btn').disabled)
+ .toBe(false);
+});
+
+it('renders the compatibility success state when the response omits an id', async () => {
+ vi.stubGlobal('safeFetchWithAuth', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ }));
+ await loadPage();
+
+ document.getElementById('create-collection-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+
+ const results = document.getElementById('create-results');
+ await vi.waitFor(() => {
+ expect(results.textContent).toContain('Collection created!');
+ });
+ expect(results.textContent).toContain('View All Collections');
+ expect(results.textContent).toContain('Create Another Collection');
+});
+
+it('updates the remaining-character counter from the live input value', async () => {
+ vi.stubGlobal('safeFetchWithAuth', vi.fn());
+ await loadPage();
+
+ const nameInput = document.getElementById('collection-name');
+ nameInput.value = '12345678';
+ nameInput.dispatchEvent(new Event('input', { bubbles: true }));
+
+ expect(document.getElementById('name-counter').textContent)
+ .toBe('92 characters remaining');
+});
diff --git a/tests/js/collection-details-direct-runtime.test.js b/tests/js/collection-details-direct-runtime.test.js
new file mode 100644
index 0000000000..c47e17ff92
--- /dev/null
+++ b/tests/js/collection-details-direct-runtime.test.js
@@ -0,0 +1,1032 @@
+/** Direct browser-runtime coverage for collection_details.js. */
+
+const COLLECTION_ID = 'collection-direct-3299';
+const COLLECTION_DOCUMENTS_URL = `/library/api/collections/${COLLECTION_ID}/documents`;
+const COLLECTION_DETAILS_URL = `/library/api/collections/${COLLECTION_ID}`;
+const INDEX_STATUS_URL = `/library/api/collections/${COLLECTION_ID}/index/status`;
+
+let documentListeners = [];
+let originalSemanticSearch;
+
+function renderCollectionPage() {
+ document.body.innerHTML = `
+ <button id="index-collection-btn">Index</button>
+ <button id="reindex-collection-btn">Re-index</button>
+ <button id="delete-collection-btn">Delete</button>
+ <button id="cancel-indexing-btn" style="display:none">Cancel</button>
+ <input id="collection-is-public" type="checkbox">
+ <input id="collection-agent-enabled" type="checkbox">
+ <h1 id="collection-name"></h1>
+ <p id="collection-description"></p>
+ <span id="stat-total-docs"></span>
+ <span id="stat-indexed-docs"></span>
+ <span id="stat-unindexed-docs"></span>
+ <span id="stat-total-chunks"></span>
+ <div id="collection-embedding-info"></div>
+ <div class="ldr-filter-controls">
+ <button id="filter-all" class="ldr-btn-collections ldr-active">All</button>
+ <button id="filter-indexed" class="ldr-btn-collections">Indexed</button>
+ <button id="filter-unindexed" class="ldr-btn-collections">Not Indexed</button>
+ </div>
+ <div id="documents-list"></div>
+ <div id="no-documents-message"></div>
+ <section id="notes-section"><div id="notes-list"></div></section>
+ <section id="indexing-progress" style="display:none">
+ <div id="indexing-spinner"></div>
+ <div id="progress-fill"></div>
+ <div id="progress-text"></div>
+ <div id="progress-log"></div>
+ </section>
+ <section id="collection-search-section" style="display:none">
+ <input id="collection-search-input">
+ <button id="collection-search-btn">Search</button>
+ <div id="collection-search-results"></div>
+ </section>
+ `;
+}
+
+function collectionPayload({ isProtected = false } = {}) {
+ return {
+ success: true,
+ collection: {
+ name: 'Direct collection',
+ description: 'Rendered from the migration API',
+ is_public: true,
+ agent_enabled: false,
+ is_protected: isProtected,
+ embedding_model_type: 'openai',
+ embedding_model: '<img src=x onerror="window.__detailsXss=true">',
+ chunk_size: 1000,
+ chunk_overlap: 100,
+ embedding_dimension: 1536,
+ splitter_type: 'recursive',
+ distance_metric: 'cosine',
+ index_type: 'flat',
+ normalize_vectors: false,
+ index_file_size: 4096,
+ },
+ documents: [
+ {
+ id: 'doc/indexed',
+ filename: '<img src=x onerror="window.__documentXss=true">.pdf',
+ indexed: true,
+ chunk_count: 4,
+ file_size: 2048,
+ source_type: 'web_page',
+ has_pdf: true,
+ has_text_db: true,
+ in_other_collections: true,
+ other_collections_count: 2,
+ last_indexed_at: '2026-08-01T12:00:00Z',
+ },
+ {
+ id: 'doc-unindexed',
+ filename: 'draft.txt',
+ indexed: false,
+ chunk_count: 0,
+ source_type: 'unknown',
+ },
+ ],
+ notes: [
+ {
+ id: 'note/indexed',
+ title: 'Pinned note',
+ indexed: true,
+ chunk_count: 3,
+ pinned: true,
+ updated_at: '2026-08-02T12:00:00Z',
+ },
+ {
+ id: 'note-unindexed',
+ title: '',
+ indexed: false,
+ chunk_count: 0,
+ },
+ ],
+ };
+}
+
+function response(payload, { ok = true, status = 200 } = {}) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+async function loadCollectionPage(safeFetch) {
+ vi.stubGlobal('safeFetch', safeFetch);
+ vi.stubGlobal('COLLECTION_ID', COLLECTION_ID);
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ COLLECTION_DOCUMENTS: '/library/api/collections/{id}/documents',
+ COLLECTION_DETAILS: '/library/api/collections/{id}',
+ },
+ });
+ vi.stubGlobal('URLBuilder', {
+ build: (template, id) => template.replace('{id}', id),
+ });
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ vi.stubGlobal('alert', vi.fn());
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-direct-details') };
+ window.RESEARCH_STATUS = {
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ SUSPENDED: 'suspended',
+ CANCELLED: 'cancelled',
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ ERROR: 'error',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'suspended', 'failed', 'error', 'cancelled',
+ ]);
+
+ await import('@js/security/xss-protection.js');
+ await import('@js/config/constants.js');
+ await import('@js/collection_details.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ documentListeners = [];
+ originalSemanticSearch = window.SemanticSearch;
+ const addDocumentListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ renderCollectionPage();
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ window.SemanticSearch = originalSemanticSearch;
+ delete window.LibrarySearch;
+ delete window.api;
+ delete window.escapeHtml;
+ delete window.escapeHtmlAttribute;
+ delete window.getProviderLabel;
+ delete window.renderIndexingFailure;
+ delete window.checkAndResumeIndexing;
+ delete window.showProgressUI;
+ delete window.hideProgressUI;
+ delete window.startPolling;
+ delete window.updateCollectionIsPublic;
+ delete window.updateCollectionAgentEnabled;
+ delete window.filterDocuments;
+ delete window.removeDocumentFromCollection;
+ delete window.deleteDocumentCompletely;
+ delete window.DeleteManager;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.RESEARCH_TERMINAL_STATES;
+ delete window.__detailsXss;
+ delete window.__documentXss;
+ document.body.replaceChildren();
+});
+
+it('hydrates collection content and searches indexed members through real listeners', async () => {
+ const payload = collectionPayload({ isProtected: true });
+ const safeFetch = vi.fn(async url => {
+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);
+ if (url === INDEX_STATUS_URL) return response({ status: 'idle' });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ const resultCard = document.createElement('article');
+ resultCard.textContent = 'Semantic result card';
+ window.LibrarySearch = {
+ performSemanticSearch: vi.fn().mockResolvedValue({
+ success: true,
+ results: [{ id: 'doc/indexed', score: 0.91 }],
+ }),
+ getLibraryCardConfig: vi.fn(() => ({ compact: true })),
+ };
+ window.SemanticSearch = {
+ ...originalSemanticSearch,
+ createSemanticResultCard: vi.fn(() => resultCard),
+ };
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ expect(document.getElementById('collection-description').textContent)
+ .toBe('Rendered from the migration API');
+ expect(document.getElementById('collection-is-public').checked).toBe(true);
+ expect(document.getElementById('collection-agent-enabled').checked).toBe(false);
+ expect(document.getElementById('delete-collection-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('stat-total-docs').textContent).toBe('4');
+ expect(document.getElementById('stat-indexed-docs').textContent).toBe('2');
+ expect(document.getElementById('stat-unindexed-docs').textContent).toBe('2');
+ expect(document.getElementById('stat-total-chunks').textContent).toBe('7');
+
+ const embeddingInfo = document.getElementById('collection-embedding-info');
+ expect(embeddingInfo.textContent).toContain('OpenAI');
+ expect(embeddingInfo.textContent).toContain(payload.collection.embedding_model);
+ expect(embeddingInfo.querySelector('img')).toBeNull();
+ const documents = document.getElementById('documents-list');
+ expect(documents.textContent).toContain(payload.documents[0].filename);
+ expect(documents.textContent).toContain('2 KB');
+ expect(documents.querySelector('img')).toBeNull();
+ expect(documents.querySelector('a').getAttribute('href'))
+ .toBe('/library/document/doc%2Findexed');
+ expect(document.getElementById('notes-list').textContent)
+ .toContain('Pinned note');
+ expect(document.getElementById('notes-list').textContent)
+ .toContain('Untitled');
+ expect(window.__detailsXss).toBeUndefined();
+ expect(window.__documentXss).toBeUndefined();
+ expect(document.getElementById('collection-search-section').style.display)
+ .toBe('block');
+
+ document.getElementById('collection-search-input').value = 'migration query';
+ document.getElementById('collection-search-btn').click();
+ await vi.waitFor(() => {
+ expect(window.LibrarySearch.performSemanticSearch).toHaveBeenCalledWith(
+ COLLECTION_ID,
+ 'migration query',
+ 20,
+ );
+ });
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-search-results').textContent)
+ .toBe('Semantic result card');
+ });
+ expect(window.SemanticSearch.createSemanticResultCard).toHaveBeenCalledWith(
+ { id: 'doc/indexed', score: 0.91 },
+ { compact: true },
+ 'migration query',
+ );
+});
+
+it('ignores an older collection reload before reading its response body', async () => {
+ const olderRequest = deferred();
+ const baselinePayload = collectionPayload();
+ const olderPayload = collectionPayload();
+ olderPayload.collection.name = 'Older collection snapshot';
+ const newerPayload = collectionPayload();
+ newerPayload.collection.name = 'Newest collection snapshot';
+ newerPayload.documents = [newerPayload.documents[0]];
+ newerPayload.notes = [];
+ let detailsRequests = 0;
+ const safeFetch = vi.fn(url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ detailsRequests += 1;
+ if (detailsRequests === 1) return Promise.resolve(response(baselinePayload));
+ if (detailsRequests === 2) return olderRequest.promise;
+ return Promise.resolve(response(newerPayload));
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ window.DeleteManager = { removeFromCollection: vi.fn() };
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ await window.removeDocumentFromCollection('older-document');
+ const olderLoad = window.DeleteManager.removeFromCollection
+ .mock.calls[0][2].onSuccess();
+ await vi.waitFor(() => expect(detailsRequests).toBe(2));
+
+ await window.removeDocumentFromCollection('newer-document');
+ await window.DeleteManager.removeFromCollection
+ .mock.calls[1][2].onSuccess();
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Newest collection snapshot');
+ expect(document.getElementById('stat-total-docs').textContent).toBe('1');
+
+ const olderResponse = response(olderPayload);
+ olderRequest.resolve(olderResponse);
+ await olderLoad;
+
+ expect(olderResponse.json).not.toHaveBeenCalled();
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Newest collection snapshot');
+ expect(document.getElementById('stat-total-docs').textContent).toBe('1');
+});
+
+it('ignores an older collection reload whose response body finishes last', async () => {
+ const olderBody = deferred();
+ const olderResponse = {
+ ok: true,
+ status: 200,
+ json: vi.fn(() => olderBody.promise),
+ };
+ const olderPayload = collectionPayload();
+ olderPayload.collection.name = 'Older decoded snapshot';
+ const newerPayload = collectionPayload();
+ newerPayload.collection.name = 'Newest decoded snapshot';
+ newerPayload.documents = [newerPayload.documents[0]];
+ newerPayload.notes = [];
+ let detailsRequests = 0;
+ const safeFetch = vi.fn(url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ detailsRequests += 1;
+ if (detailsRequests === 1) {
+ return Promise.resolve(response(collectionPayload()));
+ }
+ if (detailsRequests === 2) return Promise.resolve(olderResponse);
+ return Promise.resolve(response(newerPayload));
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ window.DeleteManager = { removeFromCollection: vi.fn() };
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ await window.removeDocumentFromCollection('older-document');
+ const olderLoad = window.DeleteManager.removeFromCollection
+ .mock.calls[0][2].onSuccess();
+ await vi.waitFor(() => expect(olderResponse.json).toHaveBeenCalledOnce());
+
+ await window.removeDocumentFromCollection('newer-document');
+ await window.DeleteManager.removeFromCollection
+ .mock.calls[1][2].onSuccess();
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Newest decoded snapshot');
+
+ olderBody.resolve(olderPayload);
+ await olderLoad;
+
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Newest decoded snapshot');
+ expect(document.getElementById('stat-total-docs').textContent).toBe('1');
+});
+
+it('does not surface an error from an older collection reload', async () => {
+ const olderRequest = deferred();
+ const newerPayload = collectionPayload();
+ newerPayload.collection.name = 'Newest successful snapshot';
+ let detailsRequests = 0;
+ const safeFetch = vi.fn(url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ detailsRequests += 1;
+ if (detailsRequests === 1) {
+ return Promise.resolve(response(collectionPayload()));
+ }
+ if (detailsRequests === 2) return olderRequest.promise;
+ return Promise.resolve(response(newerPayload));
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ window.DeleteManager = { removeFromCollection: vi.fn() };
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ await window.removeDocumentFromCollection('older-document');
+ const olderLoad = window.DeleteManager.removeFromCollection
+ .mock.calls[0][2].onSuccess();
+ await vi.waitFor(() => expect(detailsRequests).toBe(2));
+
+ await window.removeDocumentFromCollection('newer-document');
+ await window.DeleteManager.removeFromCollection
+ .mock.calls[1][2].onSuccess();
+ alert.mockClear();
+
+ olderRequest.reject(new Error('late obsolete failure'));
+ await olderLoad;
+
+ expect(alert).not.toHaveBeenCalled();
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Newest successful snapshot');
+});
+
+it('keeps a confirmed toggle authoritative over the older bootstrap payload', async () => {
+ const bootstrapDocuments = deferred();
+ const stalePayload = collectionPayload();
+ stalePayload.collection.is_public = false;
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return bootstrapDocuments.promise;
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ if (url === COLLECTION_DETAILS_URL && options.method === 'PUT') {
+ return Promise.resolve(response({
+ success: true,
+ collection: { is_public: true },
+ }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+
+ const publicToggle = document.getElementById('collection-is-public');
+ publicToggle.click();
+ await vi.waitFor(() => {
+ expect(safeFetch).toHaveBeenCalledWith(COLLECTION_DETAILS_URL, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-direct-details',
+ },
+ body: JSON.stringify({ is_public: true }),
+ });
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection marked public.',
+ );
+ });
+ expect(publicToggle.checked).toBe(true);
+
+ bootstrapDocuments.resolve(response(stalePayload));
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ // The rest of the bootstrap payload still hydrates normally, but its
+ // pre-mutation flag cannot repaint the confirmed user intent.
+ expect(document.getElementById('stat-total-docs').textContent).toBe('4');
+ expect(document.getElementById('collection-agent-enabled').checked)
+ .toBe(false);
+ expect(publicToggle.checked).toBe(true);
+});
+
+it('keeps the latest public intent visible and rolls a failure back to the newest confirmation', async () => {
+ const bootstrapDocuments = deferred();
+ const firstWrite = deferred();
+ const secondWrite = deferred();
+ const stalePayload = collectionPayload();
+ stalePayload.collection.is_public = false;
+ let writeCount = 0;
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return bootstrapDocuments.promise;
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ if (url === COLLECTION_DETAILS_URL && options.method === 'PUT') {
+ writeCount += 1;
+ return writeCount === 1 ? firstWrite.promise : secondWrite.promise;
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+
+ const publicToggle = document.getElementById('collection-is-public');
+ publicToggle.click();
+ publicToggle.click();
+ expect(publicToggle.checked).toBe(false);
+
+ await vi.waitFor(() => {
+ expect(safeFetch.mock.calls.filter(([, options]) =>
+ options?.method === 'PUT'
+ )).toHaveLength(1);
+ });
+ firstWrite.resolve(response({
+ success: true,
+ collection: { is_public: true },
+ }));
+ await vi.waitFor(() => {
+ expect(safeFetch.mock.calls.filter(([, options]) =>
+ options?.method === 'PUT'
+ )).toHaveLength(2);
+ });
+
+ // The older success is now the rollback baseline, but the second intent
+ // still owns the visible checkbox while its serialized PUT is pending.
+ expect(publicToggle.checked).toBe(false);
+ bootstrapDocuments.resolve(response(stalePayload));
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+ expect(publicToggle.checked).toBe(false);
+
+ secondWrite.resolve(response({
+ success: false,
+ error: 'Latest privacy change was rejected',
+ }));
+ await vi.waitFor(() => {
+ expect(alert).toHaveBeenCalledWith(
+ 'Error: Failed to update collection: Latest privacy change was rejected',
+ );
+ });
+ expect(publicToggle.checked).toBe(true);
+});
+
+it('keeps a confirmed agent toggle authoritative over the older bootstrap payload', async () => {
+ const bootstrapDocuments = deferred();
+ const stalePayload = collectionPayload();
+ stalePayload.collection.agent_enabled = false;
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return bootstrapDocuments.promise;
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ if (url === COLLECTION_DETAILS_URL && options.method === 'PUT') {
+ return Promise.resolve(response({
+ success: true,
+ collection: { agent_enabled: true },
+ }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+
+ const agentToggle = document.getElementById('collection-agent-enabled');
+ agentToggle.click();
+ await vi.waitFor(() => {
+ expect(safeFetch).toHaveBeenCalledWith(COLLECTION_DETAILS_URL, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-direct-details',
+ },
+ body: JSON.stringify({ agent_enabled: true }),
+ });
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection available to the research agent.',
+ );
+ });
+ expect(agentToggle.checked).toBe(true);
+
+ bootstrapDocuments.resolve(response(stalePayload));
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+ expect(agentToggle.checked).toBe(true);
+});
+
+it('rolls a failed pending agent intent back to the bootstrap value', async () => {
+ const bootstrapDocuments = deferred();
+ const agentWrite = deferred();
+ const payload = collectionPayload();
+ payload.collection.agent_enabled = true;
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return bootstrapDocuments.promise;
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve(response({ status: 'idle' }));
+ }
+ if (url === COLLECTION_DETAILS_URL && options.method === 'PUT') {
+ return agentWrite.promise;
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+
+ const agentToggle = document.getElementById('collection-agent-enabled');
+ agentToggle.click();
+ await vi.waitFor(() => {
+ expect(safeFetch).toHaveBeenCalledWith(
+ COLLECTION_DETAILS_URL,
+ expect.objectContaining({
+ method: 'PUT',
+ body: JSON.stringify({ agent_enabled: true }),
+ }),
+ );
+ });
+
+ bootstrapDocuments.resolve(response(payload));
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+ expect(agentToggle.checked).toBe(true);
+
+ agentWrite.resolve(response({
+ success: false,
+ error: 'Agent setting was rejected',
+ }));
+ await vi.waitFor(() => {
+ expect(alert).toHaveBeenCalledWith(
+ 'Error: Failed to update collection: Agent setting was rejected',
+ );
+ });
+ expect(agentToggle.checked).toBe(true);
+});
+
+it('starts indexing and refreshes after the terminal polling response', async () => {
+ vi.useFakeTimers();
+ const payload = collectionPayload();
+ let statusRequests = 0;
+ const safeFetch = vi.fn(async (url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);
+ if (url === INDEX_STATUS_URL) {
+ statusRequests += 1;
+ return response(statusRequests === 1
+ ? { status: 'idle' }
+ : {
+ status: 'completed',
+ progress_current: 4,
+ progress_total: 4,
+ progress_message: 'All members indexed',
+ });
+ }
+ if (url.endsWith('/index/start') && options.method === 'POST') {
+ return response({ success: true, task_id: 'task-3299' });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+
+ document.getElementById('reindex-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ const startCall = safeFetch.mock.calls.find(([url]) =>
+ String(url).endsWith('/index/start')
+ );
+ expect(startCall).toEqual([
+ `/library/api/collections/${COLLECTION_ID}/index/start`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-direct-details',
+ },
+ body: JSON.stringify({ force_reindex: true }),
+ },
+ ]);
+ expect(document.getElementById('indexing-progress').style.display)
+ .toBe('block');
+ expect(document.getElementById('progress-log').textContent)
+ .toContain('Indexing started in background');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(2);
+ expect(document.getElementById('progress-fill').style.width).toBe('100%');
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('All members indexed');
+ expect(document.getElementById('progress-log').textContent)
+ .toContain('All members indexed');
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(false);
+ expect(safeFetch.mock.calls.filter(([url]) =>
+ url === COLLECTION_DOCUMENTS_URL
+ )).toHaveLength(2);
+});
+
+it('does not let the bootstrap status probe repaint a newly started index run', async () => {
+ vi.useFakeTimers();
+ const bootstrapStatus = deferred();
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return Promise.resolve(response(collectionPayload()));
+ }
+ if (url === INDEX_STATUS_URL) return bootstrapStatus.promise;
+ if (url.endsWith('/index/start') && options.method === 'POST') {
+ return Promise.resolve(response({
+ success: true,
+ task_id: 'new-index-task-3299',
+ }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+
+ document.getElementById('index-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('progress-text').textContent).not
+ .toContain('Older failed task');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('inline-block');
+
+ bootstrapStatus.resolve(response({
+ status: 'failed',
+ progress_current: 1,
+ progress_total: 4,
+ progress_message: 'Older failed task',
+ error_message: 'Older failed task',
+ result: { errors: ['stale bootstrap failure'] },
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('progress-text').textContent).not
+ .toContain('Older failed task');
+ expect(document.getElementById('progress-log').textContent).not
+ .toContain('stale bootstrap failure');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('inline-block');
+});
+
+it('does not let a deferred bootstrap status body repaint a newly started index run', async () => {
+ vi.useFakeTimers();
+ const bootstrapStatusBody = deferred();
+ const readBootstrapStatus = vi.fn(() => bootstrapStatusBody.promise);
+ const safeFetch = vi.fn((url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return Promise.resolve(response(collectionPayload()));
+ }
+ if (url === INDEX_STATUS_URL) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: readBootstrapStatus,
+ });
+ }
+ if (url.endsWith('/index/start') && options.method === 'POST') {
+ return Promise.resolve(response({
+ success: true,
+ task_id: 'new-index-task-after-headers-3299',
+ }));
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(readBootstrapStatus).toHaveBeenCalledOnce();
+
+ document.getElementById('index-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('index-collection-btn').disabled).toBe(true);
+
+ bootstrapStatusBody.resolve({
+ status: 'failed',
+ progress_current: 1,
+ progress_total: 4,
+ progress_message: 'Older body arrived late',
+ error_message: 'Older body arrived late',
+ result: { errors: ['stale deferred-body failure'] },
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('progress-text').textContent).not
+ .toContain('Older body arrived late');
+ expect(document.getElementById('progress-log').textContent).not
+ .toContain('stale deferred-body failure');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('inline-block');
+});
+
+it('resumes the existing index task after FastAPI returns 409', async () => {
+ vi.useFakeTimers();
+ const payload = collectionPayload();
+ const inFlightStatus = deferred();
+ let statusRequests = 0;
+ const safeFetch = vi.fn(async (url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) return response(payload);
+ if (url === INDEX_STATUS_URL) {
+ statusRequests += 1;
+ if (statusRequests === 1) return response({ status: 'idle' });
+ if (statusRequests === 2) return inFlightStatus.promise;
+ return response({
+ status: 'completed',
+ progress_current: 4,
+ progress_total: 4,
+ progress_message: 'Existing task completed',
+ });
+ }
+ if (url.endsWith('/index/start') && options.method === 'POST') {
+ return response({
+ success: false,
+ error: 'Indexing is already in progress',
+ }, { ok: false, status: 409 });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(statusRequests).toBe(1);
+
+ document.getElementById('index-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(safeFetch).toHaveBeenCalledWith(
+ `/library/api/collections/${COLLECTION_ID}/index/start`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-direct-details',
+ },
+ body: JSON.stringify({ force_reindex: false }),
+ },
+ );
+ expect(alert).toHaveBeenCalledWith(
+ 'Error: Indexing is already in progress',
+ );
+ expect(document.getElementById('indexing-progress').style.display)
+ .toBe('block');
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('inline-block');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(true);
+ expect(document.getElementById('reindex-collection-btn').disabled).toBe(true);
+
+ // The first resumed status request remains in flight across multiple timer
+ // ticks. Only its poll owner may retry after it settles.
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(2);
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(statusRequests).toBe(2);
+
+ inFlightStatus.resolve(response({
+ status: 'processing',
+ progress_current: 2,
+ progress_total: 4,
+ progress_message: 'Continuing existing task',
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('progress-fill').style.width).toBe('50%');
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Continuing existing task');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusRequests).toBe(3);
+ expect(document.getElementById('progress-fill').style.width).toBe('100%');
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Existing task completed');
+ expect(document.getElementById('progress-log').textContent)
+ .toContain('Existing task completed');
+ expect(document.getElementById('cancel-indexing-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('index-collection-btn').disabled).toBe(false);
+ expect(safeFetch.mock.calls.filter(([url]) => (
+ url === COLLECTION_DOCUMENTS_URL
+ ))).toHaveLength(2);
+
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(statusRequests).toBe(3);
+});
+
+it('sends authenticated cancel and delete mutations from the rendered controls', async () => {
+ vi.useFakeTimers();
+ const safeFetch = vi.fn(async (url, options = {}) => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return response(collectionPayload());
+ }
+ if (url === INDEX_STATUS_URL) return response({ status: 'idle' });
+ if (url.endsWith('/index/cancel') && options.method === 'POST') {
+ return response({ success: true });
+ }
+ if (url === COLLECTION_DETAILS_URL && options.method === 'DELETE') {
+ return response({ success: true });
+ }
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.advanceTimersByTimeAsync(0);
+ document.getElementById('cancel-indexing-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(safeFetch).toHaveBeenCalledWith(
+ `/library/api/collections/${COLLECTION_ID}/index/cancel`,
+ {
+ method: 'POST',
+ headers: { 'X-CSRFToken': 'csrf-direct-details' },
+ },
+ );
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Cancelling...');
+ expect(document.getElementById('progress-log').textContent)
+ .toContain('Cancellation requested');
+
+ document.getElementById('delete-collection-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(safeFetch).toHaveBeenCalledWith(COLLECTION_DETAILS_URL, {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': 'csrf-direct-details' },
+ });
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection "Direct collection" deleted successfully',
+ );
+});
+
+it('filters documents and notes together through the template handler', async () => {
+ const safeFetch = vi.fn(async url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return response(collectionPayload());
+ }
+ if (url === INDEX_STATUS_URL) return response({ status: 'idle' });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('stat-total-docs').textContent).toBe('4');
+ });
+
+ const indexedButton = document.getElementById('filter-indexed');
+ vi.stubGlobal('event', { target: indexedButton });
+ window.filterDocuments('indexed');
+ expect(indexedButton.classList.contains('ldr-active')).toBe(true);
+ expect(document.getElementById('documents-list').textContent)
+ .toContain(collectionPayload().documents[0].filename);
+ expect(document.getElementById('documents-list').textContent)
+ .not.toContain('draft.txt');
+ expect(document.getElementById('notes-list').textContent)
+ .toContain('Pinned note');
+ expect(document.getElementById('notes-list').textContent)
+ .not.toContain('Untitled');
+
+ const unindexedButton = document.getElementById('filter-unindexed');
+ vi.stubGlobal('event', { target: unindexedButton });
+ window.filterDocuments('unindexed');
+ expect(unindexedButton.classList.contains('ldr-active')).toBe(true);
+ expect(indexedButton.classList.contains('ldr-active')).toBe(false);
+ expect(document.getElementById('documents-list').textContent)
+ .toContain('draft.txt');
+ expect(document.getElementById('notes-list').textContent)
+ .toContain('Untitled');
+});
+
+it('delegates both document deletion choices and refreshes after success', async () => {
+ const safeFetch = vi.fn(async url => {
+ if (url === COLLECTION_DOCUMENTS_URL) {
+ return response(collectionPayload());
+ }
+ if (url === INDEX_STATUS_URL) return response({ status: 'idle' });
+ throw new Error(`Unexpected URL: ${url}`);
+ });
+ window.DeleteManager = {
+ removeFromCollection: vi.fn(),
+ deleteDocument: vi.fn(),
+ };
+
+ await loadCollectionPage(safeFetch);
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-name').textContent)
+ .toBe('Direct collection');
+ });
+
+ await window.removeDocumentFromCollection('doc/indexed');
+ expect(window.DeleteManager.removeFromCollection).toHaveBeenCalledWith(
+ 'doc/indexed',
+ COLLECTION_ID,
+ expect.objectContaining({ onSuccess: expect.any(Function) }),
+ );
+ window.DeleteManager.removeFromCollection.mock.calls[0][2].onSuccess();
+
+ await window.deleteDocumentCompletely('doc-unindexed');
+ expect(window.DeleteManager.deleteDocument).toHaveBeenCalledWith(
+ 'doc-unindexed',
+ expect.objectContaining({ onSuccess: expect.any(Function) }),
+ );
+ window.DeleteManager.deleteDocument.mock.calls[0][1].onSuccess();
+
+ await vi.waitFor(() => {
+ expect(safeFetch.mock.calls.filter(([url]) =>
+ url === COLLECTION_DOCUMENTS_URL
+ )).toHaveLength(3);
+ });
+});
diff --git a/tests/js/collection-details.test.js b/tests/js/collection-details.test.js
index e7f9048fde..6c1ed12ebb 100644
--- a/tests/js/collection-details.test.js
+++ b/tests/js/collection-details.test.js
@@ -6,16 +6,54 @@
* - renderIndexingFailure (trims trailing period, uses textContent)
* - hideProgressUI (auto-hides after 5s when keepVisible=false,
* stays visible when keepVisible=true)
+ * - serialized ownership for collection boolean settings
+ * - single-flight indexing-status polling and restart ownership
*
* The 5-second auto-hide is pinned because PR #5235 review comment
* 5085604502 flagged that cancellation was leaving the UI visible
* indefinitely; only the failure path should keep it visible.
*/
+import { resolve as resolvePath } from 'node:path';
+
+import { compileTemplateHarness } from './helpers/template-harness.js';
+
+const SOURCE_PATH = resolvePath(
+ __dirname,
+ '../../src/local_deep_research/web/static/js/collection_details.js',
+);
+
+function compileCollectionSearchRuntime({ SafeLogger = { error: vi.fn() } } = {}) {
+ const runtime = compileTemplateHarness({
+ templatePath: SOURCE_PATH,
+ functionNames: ['initCollectionSearch', 'searchCollection'],
+ dependencies: {
+ COLLECTION_ID: 'collection-search-3299',
+ SafeLogger,
+ escapeHtml: value => String(value),
+ initialDocuments: [{ id: 'indexed-document', indexed: true }],
+ initialNotes: [],
+ },
+ preamble: `
+ let documentsData = initialDocuments;
+ let notesData = initialNotes;
+ let searchDebounceTimer = null;
+ let searchListenersAttached = false;
+ let collectionSearchId = 0;
+ `,
+ returnExpression: '({ initCollectionSearch, searchCollection })',
+ });
+ return { runtime, SafeLogger };
+}
+
let getProviderLabel;
let renderIndexingFailure;
+let checkAndResumeIndexing;
+let showProgressUI;
let hideProgressUI;
let startPolling;
+let updateCollectionIsPublic;
+let updateCollectionAgentEnabled;
beforeAll(async () => {
globalThis.fetch = vi.fn(() =>
@@ -43,8 +81,12 @@ beforeAll(async () => {
await import('@js/collection_details.js');
getProviderLabel = window.getProviderLabel;
renderIndexingFailure = window.renderIndexingFailure;
+ checkAndResumeIndexing = window.checkAndResumeIndexing;
+ showProgressUI = window.showProgressUI;
hideProgressUI = window.hideProgressUI;
startPolling = window.startPolling;
+ updateCollectionIsPublic = window.updateCollectionIsPublic;
+ updateCollectionAgentEnabled = window.updateCollectionAgentEnabled;
});
describe('getProviderLabel', () => {
@@ -236,51 +278,520 @@ describe('hideProgressUI', () => {
});
});
-describe('startPolling terminal-status fallback', () => {
- /** Pin the ``else`` branch that hides progress UI for terminal statuses
- * other than completed / failed / cancelled. PR #5235 review comment
- * 5085604502 noted that the previous code only cleared the interval
- * without hiding the UI for status strings that match
- * ``ResearchStates.isTerminal`` but not the explicit branches
- * (e.g. ``error``). The fallback hides the UI without emitting a
- * misleading log entry.
- *
- * Exercising the full ``startPolling`` async chain (interval →
- * safeFetchWithAuth → fetch → .json() → branch selection) requires
- * every DOM element ``updateProgressFromStatus`` and friends touch,
- * which is fragile and out of scope for a defensive one-line
- * fallback. The branch is pinned with a source-text scan that fails
- * the build if a future refactor silently drops the fallback.
- */
- it('source declares the else fallback branch', async () => {
- const { readFile } = await import('fs/promises');
- const { fileURLToPath } = await import('url');
- const path = await import('path');
- const here = path.dirname(fileURLToPath(import.meta.url));
- const jsPath = path.resolve(
- here,
- '../../src/local_deep_research/web/static/js/collection_details.js',
+describe('collection boolean write ownership', () => {
+ function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+ }
+
+ function response(payload) {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+ }
+
+ beforeEach(() => {
+ document.body.innerHTML = `
+ <input type="checkbox" id="collection-is-public">
+ <input type="checkbox" id="collection-agent-enabled" checked>
+ `;
+ vi.stubGlobal('COLLECTION_ID', 'collection-writes-3299');
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ COLLECTION_DETAILS: '/library/api/collections/{id}',
+ },
+ });
+ vi.stubGlobal('URLBuilder', {
+ build: vi.fn((template, id) => template.replace('{id}', id)),
+ });
+ vi.stubGlobal('api', {
+ getCsrfToken: vi.fn(() => 'csrf-collection-write'),
+ });
+ vi.stubGlobal('alert', vi.fn());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ });
+
+ it('sends same-control intents in order and ignores an older failure', async () => {
+ const firstWrite = deferred();
+ const secondWrite = deferred();
+ const safeFetch = vi.fn()
+ .mockReturnValueOnce(firstWrite.promise)
+ .mockReturnValueOnce(secondWrite.promise);
+ vi.stubGlobal('safeFetch', safeFetch);
+ const publicToggle = document.getElementById('collection-is-public');
+
+ publicToggle.checked = true;
+ const olderIntent = updateCollectionIsPublic(true);
+ publicToggle.checked = false;
+ const latestIntent = updateCollectionIsPublic(false);
+
+ await vi.waitFor(() => expect(safeFetch).toHaveBeenCalledTimes(1));
+ expect(JSON.parse(safeFetch.mock.calls[0][1].body)).toEqual({
+ is_public: true,
+ });
+
+ firstWrite.reject(new Error('older write failed'));
+ await vi.waitFor(() => expect(safeFetch).toHaveBeenCalledTimes(2));
+
+ expect(publicToggle.checked).toBe(false);
+ expect(alert).not.toHaveBeenCalled();
+ expect(JSON.parse(safeFetch.mock.calls[1][1].body)).toEqual({
+ is_public: false,
+ });
+
+ secondWrite.resolve(response({
+ success: true,
+ collection: { is_public: false },
+ }));
+ await Promise.all([olderIntent, latestIntent]);
+
+ expect(publicToggle.checked).toBe(false);
+ expect(alert).toHaveBeenCalledOnce();
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection marked private (local-only).',
+ );
+ for (const [url, options] of safeFetch.mock.calls) {
+ expect(url).toBe('/library/api/collections/collection-writes-3299');
+ expect(options).toEqual(expect.objectContaining({
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-collection-write',
+ },
+ }));
+ }
+ });
+
+ it('keeps controls concurrent and suppresses an older success repaint', async () => {
+ const firstPublicWrite = deferred();
+ const secondPublicWrite = deferred();
+ const agentWrite = deferred();
+ let publicCalls = 0;
+ const safeFetch = vi.fn((_url, options) => {
+ const payload = JSON.parse(options.body);
+ if (Object.hasOwn(payload, 'is_public')) {
+ publicCalls += 1;
+ return publicCalls === 1
+ ? firstPublicWrite.promise
+ : secondPublicWrite.promise;
+ }
+ return agentWrite.promise;
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+ const publicToggle = document.getElementById('collection-is-public');
+ const agentToggle = document.getElementById('collection-agent-enabled');
+
+ publicToggle.checked = true;
+ const olderPublicIntent = updateCollectionIsPublic(true);
+ publicToggle.checked = false;
+ const latestPublicIntent = updateCollectionIsPublic(false);
+ agentToggle.checked = false;
+ const agentIntent = updateCollectionAgentEnabled(false);
+
+ await vi.waitFor(() => expect(safeFetch).toHaveBeenCalledTimes(2));
+ expect(safeFetch.mock.calls.map(([, options]) => JSON.parse(options.body)))
+ .toEqual([
+ { is_public: true },
+ { agent_enabled: false },
+ ]);
+
+ firstPublicWrite.resolve(response({
+ success: true,
+ collection: { is_public: true },
+ }));
+ await vi.waitFor(() => expect(safeFetch).toHaveBeenCalledTimes(3));
+
+ expect(publicToggle.checked).toBe(false);
+ expect(agentToggle.checked).toBe(false);
+ expect(alert).not.toHaveBeenCalledWith(
+ 'Success: Collection marked public.',
+ );
+
+ secondPublicWrite.resolve(response({
+ success: true,
+ collection: { is_public: false },
+ }));
+ agentWrite.resolve(response({
+ success: true,
+ collection: { agent_enabled: false },
+ }));
+ await Promise.all([
+ olderPublicIntent,
+ latestPublicIntent,
+ agentIntent,
+ ]);
+
+ expect(publicToggle.checked).toBe(false);
+ expect(agentToggle.checked).toBe(false);
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection marked private (local-only).',
+ );
+ expect(alert).toHaveBeenCalledWith(
+ 'Success: Collection hidden from the research agent.',
+ );
+ });
+});
+
+describe('startPolling request ownership', () => {
+ function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+ }
+
+ function response(payload) {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+ }
+
+ function setupPollingDom() {
+ document.body.innerHTML = `
+ <section id="indexing-progress" style="display:block"></section>
+ <button id="cancel-indexing-btn" style="display:block"></button>
+ <button id="index-collection-btn" disabled></button>
+ <button id="reindex-collection-btn" disabled></button>
+ <div id="indexing-spinner"></div>
+ <div id="progress-fill"></div>
+ <div id="progress-text"></div>
+ <div id="progress-log"></div>
+ `;
+ }
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ setupPollingDom();
+ vi.stubGlobal('COLLECTION_ID', 'collection-poll-3299');
+ // The terminal branch fire-and-forgets the page-detail refresh. This
+ // focused fixture intentionally omits that page's larger DOM surface.
+ vi.stubGlobal('alert', vi.fn());
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ });
+
+ it('keeps at most one status request in flight and resumes after it settles', async () => {
+ const firstStatus = deferred();
+ let statusCalls = 0;
+ const safeFetch = vi.fn(url => {
+ if (!String(url).endsWith('/index/status')) {
+ return new Promise(() => {});
+ }
+ statusCalls += 1;
+ if (statusCalls === 1) return firstStatus.promise;
+ return Promise.resolve(response({
+ status: 'completed',
+ progress_current: 2,
+ progress_total: 2,
+ progress_message: 'Owned terminal status',
+ }));
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+
+ startPolling();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(8000);
+ expect(statusCalls).toBe(1);
+
+ firstStatus.resolve(response({
+ status: 'processing',
+ progress_current: 1,
+ progress_total: 2,
+ progress_message: 'First request settled',
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('First request settled');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(2);
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Owned terminal status');
+ expect(document.getElementById('index-collection-btn').disabled)
+ .toBe(false);
+
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusCalls).toBe(2);
+ });
+
+ it('retries after an HTTP error frame without parsing it as terminal', async () => {
+ const recoveredStatus = deferred();
+ const errorJson = vi.fn().mockResolvedValue({ status: 'error' });
+ let statusCalls = 0;
+ const safeFetch = vi.fn(url => {
+ if (!String(url).endsWith('/index/status')) {
+ return new Promise(() => {});
+ }
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ return Promise.resolve({
+ ok: false,
+ status: 500,
+ json: errorJson,
+ });
+ }
+ return recoveredStatus.promise;
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+ const progressSection = document.getElementById('indexing-progress');
+ const indexButton = document.getElementById('index-collection-btn');
+
+ showProgressUI();
+ startPolling();
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(statusCalls).toBe(1);
+ expect(errorJson).not.toHaveBeenCalled();
+ expect(progressSection.style.display).toBe('block');
+ expect(indexButton.disabled).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(2);
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(statusCalls).toBe(2);
+ expect(indexButton.disabled).toBe(true);
+
+ recoveredStatus.resolve(response({
+ status: 'completed',
+ progress_current: 3,
+ progress_total: 3,
+ progress_message: 'Recovered healthy completion',
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Recovered healthy completion');
+ expect(indexButton.disabled).toBe(false);
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusCalls).toBe(2);
+ });
+
+ it('leaves resume UI untouched for a non-OK status response', async () => {
+ const errorJson = vi.fn().mockResolvedValue({ status: 'error' });
+ const safeFetch = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 503,
+ json: errorJson,
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+ const progressSection = document.getElementById('indexing-progress');
+ const indexButton = document.getElementById('index-collection-btn');
+ progressSection.style.display = 'none';
+ indexButton.disabled = false;
+
+ await checkAndResumeIndexing();
+
+ expect(safeFetch).toHaveBeenCalledWith(
+ '/library/api/collections/collection-poll-3299/index/status',
);
- const src = await readFile(jsPath, 'utf8');
- // The else branch must follow the
- // completed/failed/cancelled branches inside the isTerminal/idle
- // guard and call hideProgressUI() without keepVisible. Loose
- // checks — any future refactor that drops the fallback will
- // fail here. The branch is exercised by inspecting the source
- // text rather than driving the full async polling chain
- // (interval → safeFetchWithAuth → fetch → .json() → branch
- // selection), which requires every DOM element
- // ``updateProgressFromStatus`` and friends touch.
- const pollingBlock = src.match(
- /function startPolling\(\)\s*\{[\s\S]*?\n\}\n/
+ expect(errorJson).not.toHaveBeenCalled();
+ expect(progressSection.style.display).toBe('none');
+ expect(indexButton.disabled).toBe(false);
+ expect(document.getElementById('progress-log').childNodes)
+ .toHaveLength(0);
+ });
+
+ it('does not let a retired poll repaint after the newer poll completes', async () => {
+ const retiredStatus = deferred();
+ let statusCalls = 0;
+ const safeFetch = vi.fn(url => {
+ if (!String(url).endsWith('/index/status')) {
+ return new Promise(() => {});
+ }
+ statusCalls += 1;
+ if (statusCalls === 1) return retiredStatus.promise;
+ return Promise.resolve(response({
+ status: 'completed',
+ progress_current: 4,
+ progress_total: 4,
+ progress_message: 'Newer poll completed',
+ }));
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+
+ startPolling();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(1);
+
+ startPolling();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(2);
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Newer poll completed');
+
+ retiredStatus.resolve(response({
+ status: 'processing',
+ progress_current: 1,
+ progress_total: 4,
+ progress_message: 'Retired stale repaint',
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('progress-text').textContent)
+ .toBe('Newer poll completed');
+ expect(document.getElementById('progress-fill').style.width)
+ .toBe('100%');
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusCalls).toBe(2);
+ });
+
+ it('does not let run A delayed hide conceal newly started run B', async () => {
+ const runBStatus = deferred();
+ let statusCalls = 0;
+ const safeFetch = vi.fn(url => {
+ if (!String(url).endsWith('/index/status')) {
+ return new Promise(() => {});
+ }
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ return Promise.resolve(response({
+ status: 'completed',
+ progress_current: 2,
+ progress_total: 2,
+ progress_message: 'Run A completed',
+ }));
+ }
+ return runBStatus.promise;
+ });
+ vi.stubGlobal('safeFetch', safeFetch);
+ const progressSection = document.getElementById('indexing-progress');
+ const indexButton = document.getElementById('index-collection-btn');
+
+ showProgressUI();
+ startPolling();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(1);
+ expect(progressSection.style.display).toBe('block');
+ expect(indexButton.disabled).toBe(false);
+
+ // Starting B before A's five-second terminal hide expires transfers
+ // ownership of the visible progress section to the new run.
+ showProgressUI();
+ startPolling();
+ expect(indexButton.disabled).toBe(true);
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(statusCalls).toBe(2);
+
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(progressSection.style.display).toBe('block');
+ expect(indexButton.disabled).toBe(true);
+ expect(statusCalls).toBe(2);
+ });
+});
+
+describe('collection search request ownership', () => {
+ function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolveDeferred, rejectDeferred) => {
+ resolvePromise = resolveDeferred;
+ rejectPromise = rejectDeferred;
+ });
+ return {
+ promise,
+ reject: rejectPromise,
+ resolve: resolvePromise,
+ };
+ }
+
+ beforeEach(() => {
+ document.body.innerHTML = `
+ <section id="collection-search-section" style="display:none">
+ <input id="collection-search-input">
+ <button id="collection-search-btn" type="button">Search</button>
+ <div id="collection-search-results"></div>
+ </section>
+ `;
+ });
+
+ afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ delete window.LibrarySearch;
+ delete window.SemanticSearch;
+ document.body.replaceChildren();
+ });
+
+ it('does not let an older rejected search replace newer results', async () => {
+ const olderSearch = deferred();
+ window.LibrarySearch = {
+ performSemanticSearch: vi.fn()
+ .mockReturnValueOnce(olderSearch.promise)
+ .mockResolvedValueOnce({ success: true, results: [] }),
+ };
+ const { runtime, SafeLogger } = compileCollectionSearchRuntime();
+
+ const olderRun = runtime.searchCollection('older query');
+ await runtime.searchCollection('newer query');
+ const results = document.getElementById('collection-search-results');
+ expect(results.textContent).toContain('No matching results found.');
+
+ olderSearch.reject(new Error('late failure'));
+ await olderRun;
+
+ expect(results.textContent).toContain('No matching results found.');
+ expect(results.textContent).not.toContain('Search failed');
+ expect(SafeLogger.error).not.toHaveBeenCalled();
+ });
+
+ it('clearing the input retires a debounced search already in flight', async () => {
+ vi.useFakeTimers();
+ const pendingSearch = deferred();
+ const createCard = vi.fn(() => document.createElement('article'));
+ window.LibrarySearch = {
+ performSemanticSearch: vi.fn(() => pendingSearch.promise),
+ getLibraryCardConfig: vi.fn(() => ({ source: 'collection' })),
+ };
+ window.SemanticSearch = { createSemanticResultCard: createCard };
+ const { runtime } = compileCollectionSearchRuntime();
+ runtime.initCollectionSearch();
+
+ const input = document.getElementById('collection-search-input');
+ const results = document.getElementById('collection-search-results');
+ input.value = 'query to retire';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(500);
+ expect(window.LibrarySearch.performSemanticSearch).toHaveBeenCalledWith(
+ 'collection-search-3299',
+ 'query to retire',
+ 20,
);
- expect(pollingBlock, 'startPolling() not found').toBeTruthy();
- // Must contain a top-level ``else {`` inside the polling
- // callback (after the completed/failed/cancelled chain).
- expect(pollingBlock[0]).toMatch(/else\s*\{/);
- // And that else must call hideProgressUI() (the no-arg
- // default, which schedules the 5-second auto-hide).
- expect(pollingBlock[0]).toMatch(/hideProgressUI\(\)/);
+
+ input.value = '';
+ input.dispatchEvent(new Event('input'));
+ expect(results.innerHTML).toBe('');
+
+ pendingSearch.resolve({
+ success: true,
+ results: [{ id: 'stale-result' }],
+ });
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(results.innerHTML).toBe('');
+ expect(createCard).not.toHaveBeenCalled();
});
});
diff --git a/tests/js/collection-upload-direct-runtime.test.js b/tests/js/collection-upload-direct-runtime.test.js
new file mode 100644
index 0000000000..23828f2b8b
--- /dev/null
+++ b/tests/js/collection-upload-direct-runtime.test.js
@@ -0,0 +1,373 @@
+/** Direct browser-runtime coverage for collection_upload.js. */
+
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+const SUPPORTED_FORMATS_URL = '/library/api/config/supported-formats';
+const UPLOAD_URL = '/library/api/collections/collection-direct-3299/upload';
+const UPLOAD_TEMPLATE = readFileSync(resolvePath(
+ __dirname,
+ '../../src/local_deep_research/web/templates/pages/collection_upload.html',
+), 'utf8');
+
+let documentListeners = [];
+
+function renderUploadPage() {
+ document.body.innerHTML = `
+ <form id="upload-files-form">
+ <div id="drop-zone"><button type="button">Choose</button></div>
+ <input id="files-input" type="file" multiple>
+ <div id="selected-files" style="display:none"><ul id="file-list"></ul></div>
+ <input type="radio" name="pdf_storage" value="none">
+ <input type="radio" name="pdf_storage" value="database" checked>
+ <button type="submit"><i></i>Upload</button>
+ </form>
+ <span id="format-details"></span>
+ <div id="full-format-list"></div>
+ <div id="upload-progress" style="display:none"></div>
+ <div id="upload-results" style="display:none"></div>
+ `;
+ setInputFiles([]);
+}
+
+function renderCheckedInUploadPage() {
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture.
+ document.body.innerHTML = UPLOAD_TEMPLATE;
+ setInputFiles([]);
+}
+
+function setInputFiles(files) {
+ Object.defineProperty(document.getElementById('files-input'), 'files', {
+ configurable: true,
+ value: files,
+ });
+}
+
+function formatsResponse() {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ extensions: ['.pdf', '.md', '.txt'],
+ accept_string: '.pdf,.md,.txt',
+ count: 3,
+ }),
+ };
+}
+
+function installFakeXmlHttpRequest() {
+ const requests = [];
+
+ class FakeXMLHttpRequest {
+ constructor() {
+ this.headers = {};
+ this.openCalls = [];
+ this.upload = {};
+ requests.push(this);
+ }
+
+ open(...args) {
+ this.openCalls.push(args);
+ }
+
+ setRequestHeader(name, value) {
+ this.headers[name] = value;
+ }
+
+ send(body) {
+ this.body = body;
+ }
+
+ respond(status, body) {
+ this.status = status;
+ this.responseText = typeof body === 'string'
+ ? body
+ : JSON.stringify(body);
+ this.onload();
+ }
+
+ failNetwork() {
+ this.onerror();
+ }
+ }
+
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest);
+ return requests;
+}
+
+async function loadUploadPage(safeFetch = vi.fn().mockResolvedValue(formatsResponse())) {
+ vi.stubGlobal('safeFetch', safeFetch);
+ vi.stubGlobal('COLLECTION_ID', 'collection-direct-3299');
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ SUPPORTED_FORMATS: SUPPORTED_FORMATS_URL,
+ COLLECTION_UPLOAD: '/library/api/collections/{id}/upload',
+ },
+ });
+ vi.stubGlobal('URLBuilder', {
+ build: (template, id) => template.replace('{id}', id),
+ });
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-direct-upload') };
+
+ await import('@js/security/xss-protection.js');
+ await import('@js/collection_upload.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => expect(safeFetch).toHaveBeenCalledWith(
+ SUPPORTED_FORMATS_URL,
+ ));
+ return safeFetch;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ documentListeners = [];
+ const addDocumentListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ renderUploadPage();
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.escapeHtml;
+ delete window.escapeHtmlAttribute;
+ delete window.__dropXss;
+ document.body.replaceChildren();
+});
+
+it('hydrates formats and renders an inert selected-file preview', async () => {
+ await loadUploadPage();
+
+ expect(document.getElementById('files-input').accept)
+ .toBe('.pdf,.md,.txt');
+ expect(document.getElementById('format-details').textContent)
+ .toBe('(3 formats supported)');
+ expect(document.getElementById('full-format-list').textContent)
+ .toBe('All supported: PDF, MD, TXT');
+
+ const hostileFile = new File(
+ ['payload'],
+ '<img src=x onerror="window.__uploadXss=true">.txt',
+ );
+ setInputFiles([hostileFile]);
+ document.getElementById('files-input').dispatchEvent(new Event('change'));
+
+ const preview = document.getElementById('selected-files');
+ expect(preview.style.display).toBe('block');
+ expect(preview.textContent).toContain(hostileFile.name);
+ expect(preview.querySelector('img')).toBeNull();
+ expect(window.__uploadXss).toBeUndefined();
+
+ setInputFiles([]);
+ document.getElementById('files-input').dispatchEvent(new Event('change'));
+ expect(preview.style.display).toBe('none');
+});
+
+it('owns Browse once and uploads files dropped on the checked-in surface', async () => {
+ vi.useFakeTimers();
+ renderCheckedInUploadPage();
+ const requests = installFakeXmlHttpRequest();
+ await loadUploadPage();
+
+ const dropZone = document.getElementById('drop-zone');
+ const browseButton = dropZone.querySelector('button[type="button"]');
+ const fileInput = document.getElementById('files-input');
+ const inputClick = vi.spyOn(fileInput, 'click').mockImplementation(() => {});
+
+ expect(browseButton.hasAttribute('onclick')).toBe(false);
+ browseButton.querySelector('i').dispatchEvent(new MouseEvent('click', {
+ bubbles: true,
+ }));
+ expect(inputClick).toHaveBeenCalledOnce();
+ browseButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(inputClick).toHaveBeenCalledTimes(2);
+
+ const dragOver = new Event('dragover', {
+ bubbles: true,
+ cancelable: true,
+ });
+ dropZone.dispatchEvent(dragOver);
+ expect(dragOver.defaultPrevented).toBe(true);
+ expect(dropZone.classList).toContain('ldr-drag-over');
+
+ const droppedFile = new File(
+ ['dropped evidence'],
+ '<img src=x onerror="window.__dropXss=true">.txt',
+ { type: 'text/plain' },
+ );
+ const drop = new Event('drop', { bubbles: true, cancelable: true });
+ Object.defineProperty(drop, 'dataTransfer', {
+ value: { files: [droppedFile], types: ['Files'] },
+ });
+ dropZone.dispatchEvent(drop);
+
+ expect(drop.defaultPrevented).toBe(true);
+ expect(dropZone.classList).not.toContain('ldr-drag-over');
+ const preview = document.getElementById('selected-files');
+ expect(preview.style.display).toBe('block');
+ expect(preview.textContent).toContain(droppedFile.name);
+ expect(preview.querySelector('img')).toBeNull();
+ expect(window.__dropXss).toBeUndefined();
+
+ document.querySelector('input[name="pdf_storage"][value="database"]')
+ .checked = true;
+ document.getElementById('upload-files-form').dispatchEvent(new Event(
+ 'submit',
+ { bubbles: true, cancelable: true },
+ ));
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+ expect(requests[0].openCalls).toEqual([['POST', UPLOAD_URL]]);
+ expect(requests[0].headers).toEqual({
+ 'X-CSRFToken': 'csrf-direct-upload',
+ });
+ expect(requests[0].body.getAll('files')).toEqual([droppedFile]);
+ expect(requests[0].body.get('pdf_storage')).toBe('database');
+
+ requests[0].failNetwork();
+ await vi.waitFor(() => {
+ expect(document.querySelector('button[type="submit"]').disabled)
+ .toBe(false);
+ });
+});
+
+it('degrades the format help when supported-format hydration fails', async () => {
+ const safeFetch = vi.fn().mockResolvedValue({ ok: false, status: 503 });
+ await loadUploadPage(safeFetch);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('full-format-list').textContent)
+ .toBe('Could not load format list');
+ });
+ expect(document.getElementById('format-details').textContent).toBe('');
+ expect(document.getElementById('files-input').accept).toBe('');
+});
+
+it('executes a single XHR upload, progress update, and delayed completion', async () => {
+ vi.useFakeTimers();
+ const requests = installFakeXmlHttpRequest();
+ await loadUploadPage();
+ const file = new File(['direct upload'], 'direct.txt');
+ setInputFiles([file]);
+ document.getElementById('files-input').dispatchEvent(new Event('change'));
+
+ document.getElementById('upload-files-form').dispatchEvent(new Event(
+ 'submit',
+ { bubbles: true, cancelable: true },
+ ));
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+ const [request] = requests;
+ expect(request.openCalls).toEqual([['POST', UPLOAD_URL]]);
+ expect(request.headers).toEqual({ 'X-CSRFToken': 'csrf-direct-upload' });
+ expect(request.timeout).toBe(600000);
+ expect(request.body.getAll('files')).toEqual([file]);
+ expect(request.body.get('pdf_storage')).toBe('database');
+
+ request.upload.onprogress({
+ lengthComputable: true,
+ loaded: 512,
+ total: 1024,
+ });
+ expect(document.getElementById('progress-bar-fill').style.width)
+ .toBe('50%');
+ expect(document.getElementById('progress-summary').textContent)
+ .toContain('50%');
+
+ request.respond(201, {
+ success: true,
+ uploaded: [{ filename: file.name, status: 'uploaded' }],
+ errors: [],
+ });
+ await vi.waitFor(() => {
+ expect(document.querySelector('button[type="submit"]').disabled)
+ .toBe(false);
+ });
+ expect(document.getElementById('progress-summary').textContent)
+ .toContain('1 uploaded');
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(document.getElementById('upload-results').textContent)
+ .toContain('direct.txt');
+ expect(document.getElementById('upload-results').style.display)
+ .toBe('block');
+ expect(document.getElementById('selected-files').style.display)
+ .toBe('none');
+});
+
+it('continues a batched upload after one batch fails', async () => {
+ vi.useFakeTimers();
+ const requests = installFakeXmlHttpRequest();
+ await loadUploadPage();
+ const files = Array.from({ length: 16 }, (_, index) => new File(
+ [`batch-${index}`],
+ `batch-${index}.txt`,
+ ));
+ setInputFiles(files);
+ document.getElementById('files-input').dispatchEvent(new Event('change'));
+
+ document.getElementById('upload-files-form').dispatchEvent(new Event(
+ 'submit',
+ { bubbles: true, cancelable: true },
+ ));
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+ expect(requests[0].body.getAll('files')).toHaveLength(15);
+ requests[0].failNetwork();
+
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
+ expect(requests[1].body.getAll('files')).toEqual([files[15]]);
+ requests[1].respond(200, {
+ uploaded: [{ filename: files[15].name, status: 'uploaded' }],
+ errors: [],
+ });
+ await vi.waitFor(() => {
+ expect(document.querySelector('button[type="submit"]').disabled)
+ .toBe(false);
+ });
+ expect(document.getElementById('progress-summary').textContent)
+ .toContain('1 uploaded, 15 failed');
+
+ await vi.advanceTimersByTimeAsync(500);
+ const results = document.getElementById('upload-results');
+ expect(results.textContent).toContain('New uploads (1)');
+ expect(results.textContent).toContain('Failed (15)');
+ expect(results.textContent).toContain('Network error');
+});
+
+it('renders a non-OK upload response as inert error text and recovers', async () => {
+ const requests = installFakeXmlHttpRequest();
+ await loadUploadPage();
+ const file = new File(['bad'], 'bad.txt');
+ setInputFiles([file]);
+ document.getElementById('files-input').dispatchEvent(new Event('change'));
+ document.getElementById('upload-files-form').dispatchEvent(new Event(
+ 'submit',
+ { bubbles: true, cancelable: true },
+ ));
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+
+ requests[0].respond(
+ 422,
+ '<img src=x onerror="window.__uploadErrorXss=true">',
+ );
+ await vi.waitFor(() => {
+ expect(document.getElementById('upload-results').style.display)
+ .toBe('block');
+ });
+
+ const results = document.getElementById('upload-results');
+ expect(results.querySelector('img')).toBeNull();
+ expect(results.textContent).toContain('Server returned 422');
+ expect(window.__uploadErrorXss).toBeUndefined();
+ expect(document.querySelector('button[type="submit"]').disabled)
+ .toBe(false);
+});
diff --git a/tests/js/collection-upload-migration-contract.test.js b/tests/js/collection-upload-migration-contract.test.js
new file mode 100644
index 0000000000..94afd6954a
--- /dev/null
+++ b/tests/js/collection-upload-migration-contract.test.js
@@ -0,0 +1,486 @@
+/** Live browser contracts for collection-upload FastAPI endpoints. */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from './helpers/template-harness.js';
+
+const SOURCE_PATH = resolve(
+ __dirname,
+ '../../src/local_deep_research/web/static/js/collection_upload.js',
+);
+
+const URLS_FIXTURE = {
+ LIBRARY_API: {
+ SUPPORTED_FORMATS: '/library/api/config/supported-formats',
+ COLLECTION_UPLOAD: '/library/api/collections/{id}/upload',
+ },
+};
+
+function compileFormatLoader(safeFetchWithAuth) {
+ return compileTemplateHarness({
+ templatePath: SOURCE_PATH,
+ functionNames: ['fetchSupportedFormats'],
+ dependencies: {
+ safeFetchWithAuth,
+ URLS: URLS_FIXTURE,
+ },
+ preamble: `let supportedFormats = {
+ extensions: [],
+ accept_string: '',
+ };`,
+ returnExpression: `({
+ fetchSupportedFormats,
+ getSupportedFormats: () => supportedFormats,
+ })`,
+ });
+}
+
+function compileUploadHandler(files, dependencies) {
+ return compileTemplateHarness({
+ templatePath: SOURCE_PATH,
+ functionNames: ['handleUploadFiles'],
+ dependencies: {
+ initialFiles: files,
+ URLBuilder: {
+ build: (template, id) => template.replace('{id}', id),
+ },
+ URLS: URLS_FIXTURE,
+ COLLECTION_ID: 'collection-3299',
+ ...dependencies,
+ },
+ preamble: `
+ let selectedFiles = initialFiles;
+ let fileSelectionGeneration = 0;
+ let uploadGeneration = 0;
+ const BATCH_SIZE = 15;
+ `,
+ returnExpression: 'handleUploadFiles',
+ });
+}
+
+function renderUploadForm() {
+ document.body.innerHTML = `
+ <form id="upload-files-form">
+ <input id="files-input" type="file" multiple>
+ <div id="selected-files" style="display: none">
+ <ul id="file-list"></ul>
+ </div>
+ <input type="radio" name="pdf_storage" value="none">
+ <input type="radio" name="pdf_storage" value="database" checked>
+ <button type="submit"><i></i>Upload</button>
+ </form>
+ `;
+ return document.getElementById('upload-files-form');
+}
+
+function installFakeXmlHttpRequest() {
+ const requests = [];
+
+ class FakeXMLHttpRequest {
+ constructor() {
+ this.headers = {};
+ this.openCalls = [];
+ this.upload = {};
+ requests.push(this);
+ }
+
+ open(...args) {
+ this.openCalls.push(args);
+ }
+
+ setRequestHeader(name, value) {
+ this.headers[name] = value;
+ }
+
+ send(body) {
+ this.body = body;
+ }
+
+ respond(status, body) {
+ this.status = status;
+ this.responseText = typeof body === 'string'
+ ? body
+ : JSON.stringify(body);
+ this.onload();
+ }
+
+ failNetwork() {
+ this.onerror();
+ }
+ }
+
+ vi.stubGlobal('XMLHttpRequest', FakeXMLHttpRequest);
+ return requests;
+}
+
+function compileRealUploadRuntime(files) {
+ const calls = {
+ showError: vi.fn(),
+ showCleanProgress: vi.fn(),
+ showBatchedProgress: vi.fn(),
+ updateUploadProgress: vi.fn(),
+ updateBatchProgress: vi.fn(),
+ updateBatchProgressBytes: vi.fn(),
+ updateProgressComplete: vi.fn(),
+ showUploadResults: vi.fn(),
+ };
+ const SafeLogger = {
+ error: vi.fn(),
+ log: vi.fn(),
+ };
+ const runtime = compileTemplateHarness({
+ templatePath: SOURCE_PATH,
+ functionNames: [
+ 'handleFiles',
+ 'showSelectedFiles',
+ 'hideSelectedFiles',
+ 'handleUploadFiles',
+ 'scheduleUploadCompletion',
+ 'handleBatchedUpload',
+ 'uploadBatch',
+ 'handleSingleUpload',
+ ],
+ dependencies: {
+ initialFiles: files,
+ URLBuilder: {
+ build: (template, id) => template.replace('{id}', id),
+ },
+ URLS: URLS_FIXTURE,
+ COLLECTION_ID: 'collection-3299',
+ SafeLogger,
+ escapeHtml: value => value,
+ ...calls,
+ },
+ preamble: `
+ let selectedFiles = initialFiles;
+ let fileSelectionGeneration = 0;
+ let uploadGeneration = 0;
+ const BATCH_SIZE = 15;
+ `,
+ returnExpression: `({
+ handleFiles,
+ handleUploadFiles,
+ getSelectedFiles: () => selectedFiles,
+ })`,
+ });
+ return { calls, runtime, SafeLogger };
+}
+
+function submitEvent(form) {
+ return {
+ preventDefault: vi.fn(),
+ target: form,
+ };
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ document.body.replaceChildren();
+});
+
+it('hydrates the file picker from the supported-formats envelope', async () => {
+ document.body.innerHTML = `
+ <input id="files-input">
+ <span id="format-details"></span>
+ <div id="full-format-list"></div>
+ `;
+ const payload = {
+ extensions: ['.pdf', '.md', '.txt'],
+ accept_string: '.pdf,.md,.txt',
+ count: 3,
+ };
+ const safeFetchWithAuth = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue(payload),
+ });
+ const runtime = compileFormatLoader(safeFetchWithAuth);
+
+ await runtime.fetchSupportedFormats();
+
+ expect(safeFetchWithAuth).toHaveBeenCalledWith(
+ '/library/api/config/supported-formats',
+ );
+ expect(runtime.getSupportedFormats()).toEqual(payload);
+ expect(document.getElementById('files-input').accept)
+ .toBe('.pdf,.md,.txt');
+ expect(document.getElementById('format-details').textContent)
+ .toBe('(3 formats supported)');
+ expect(document.getElementById('full-format-list').textContent)
+ .toBe('All supported: PDF, MD, TXT');
+});
+
+it('routes a small upload to the collection endpoint with current CSRF and mode', async () => {
+ document.body.innerHTML = `
+ <form id="upload-files-form">
+ <input type="radio" name="pdf_storage" value="none">
+ <input type="radio" name="pdf_storage" value="database" checked>
+ <button type="submit"><i></i>Upload</button>
+ </form>
+ `;
+ const file = new File(['migration'], 'migration.txt', {
+ type: 'text/plain',
+ });
+ const handleSingleUpload = vi.fn().mockResolvedValue(undefined);
+ const handleBatchedUpload = vi.fn();
+ const showError = vi.fn();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-collection-upload') };
+ const handleUploadFiles = compileUploadHandler([file], {
+ handleSingleUpload,
+ handleBatchedUpload,
+ showError,
+ });
+ const form = document.getElementById('upload-files-form');
+ const event = {
+ preventDefault: vi.fn(),
+ target: form,
+ };
+
+ await handleUploadFiles(event);
+
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(handleSingleUpload).toHaveBeenCalledWith(
+ [file],
+ 'database',
+ 'csrf-collection-upload',
+ '/library/api/collections/collection-3299/upload',
+ 1,
+ 0,
+ );
+ expect(handleBatchedUpload).not.toHaveBeenCalled();
+ expect(showError).not.toHaveBeenCalled();
+ const button = form.querySelector('button[type="submit"]');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Upload Files');
+});
+
+it('executes the real XHR upload contract and completes a successful upload', async () => {
+ vi.useFakeTimers();
+ const form = renderUploadForm();
+ const resetSpy = vi.spyOn(form, 'reset');
+ const file = new File(['migration'], 'migration.txt', {
+ type: 'text/plain',
+ });
+ const requests = installFakeXmlHttpRequest();
+ const { calls, runtime } = compileRealUploadRuntime([file]);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-real-upload') };
+
+ const upload = runtime.handleUploadFiles(submitEvent(form));
+
+ expect(requests).toHaveLength(1);
+ const [request] = requests;
+ expect(request.openCalls).toEqual([[
+ 'POST',
+ '/library/api/collections/collection-3299/upload',
+ ]]);
+ expect(request.headers).toEqual({
+ 'X-CSRFToken': 'csrf-real-upload',
+ });
+ expect(request.timeout).toBe(600000);
+ expect(request.body).toBeInstanceOf(FormData);
+ expect(request.body.getAll('files')).toEqual([file]);
+ expect(request.body.get('pdf_storage')).toBe('database');
+
+ request.upload.onprogress({
+ lengthComputable: true,
+ loaded: 512,
+ total: 1024,
+ });
+ expect(calls.updateUploadProgress).toHaveBeenCalledWith(
+ 50,
+ '0.0',
+ '0.0',
+ );
+
+ const response = {
+ success: true,
+ uploaded: [{ filename: file.name, status: 'uploaded' }],
+ errors: [],
+ };
+ request.respond(201, response);
+ await upload;
+
+ const button = form.querySelector('button[type="submit"]');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Upload Files');
+ expect(calls.updateProgressComplete).toHaveBeenCalledWith(response);
+ expect(calls.showError).not.toHaveBeenCalled();
+ expect(calls.showUploadResults).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(calls.showUploadResults).toHaveBeenCalledWith(response);
+ expect(resetSpy).toHaveBeenCalledOnce();
+ expect(runtime.getSelectedFiles()).toEqual([]);
+});
+
+it('recovers the button and reports a non-OK XHR response', async () => {
+ const form = renderUploadForm();
+ const file = new File(['invalid'], 'invalid.txt');
+ const requests = installFakeXmlHttpRequest();
+ const { calls, runtime, SafeLogger } = compileRealUploadRuntime([file]);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-real-upload') };
+
+ const upload = runtime.handleUploadFiles(submitEvent(form));
+ requests[0].respond(422, 'invalid file');
+ await upload;
+
+ expect(calls.showError).toHaveBeenCalledWith(
+ 'Upload failed: Server returned 422: invalid file',
+ );
+ expect(SafeLogger.error).toHaveBeenCalledOnce();
+ expect(calls.updateProgressComplete).not.toHaveBeenCalled();
+ expect(form.querySelector('button[type="submit"]').disabled).toBe(false);
+});
+
+it('recovers the button and reports an XHR network failure', async () => {
+ const form = renderUploadForm();
+ const file = new File(['offline'], 'offline.txt');
+ const requests = installFakeXmlHttpRequest();
+ const { calls, runtime } = compileRealUploadRuntime([file]);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-real-upload') };
+
+ const upload = runtime.handleUploadFiles(submitEvent(form));
+ requests[0].failNetwork();
+ await upload;
+
+ expect(calls.showError).toHaveBeenCalledWith(
+ 'Upload failed: NetworkError: Upload failed',
+ );
+ expect(calls.showUploadResults).not.toHaveBeenCalled();
+ const button = form.querySelector('button[type="submit"]');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Upload Files');
+});
+
+it('does not let an older batched completion reset a newly selected file', async () => {
+ vi.useFakeTimers();
+ const form = renderUploadForm();
+ const resetSpy = vi.spyOn(form, 'reset');
+ const oldFiles = Array.from({ length: 16 }, (_, index) => new File(
+ [`old-${index}`],
+ `old-${index}.txt`,
+ ));
+ const newFile = new File(['new'], 'new-selection.txt');
+ const requests = installFakeXmlHttpRequest();
+ const { calls, runtime } = compileRealUploadRuntime(oldFiles);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-batched-upload') };
+
+ const upload = runtime.handleUploadFiles(submitEvent(form));
+ expect(requests).toHaveLength(1);
+ expect(requests[0].openCalls).toEqual([[
+ 'POST',
+ '/library/api/collections/collection-3299/upload',
+ ]]);
+ expect(requests[0].headers).toEqual({
+ 'X-CSRFToken': 'csrf-batched-upload',
+ });
+ expect(requests[0].body.getAll('files')).toHaveLength(15);
+ expect(requests[0].body.get('pdf_storage')).toBe('database');
+ requests[0].respond(200, {
+ uploaded: oldFiles.slice(0, 15).map(file => ({
+ filename: file.name,
+ status: 'uploaded',
+ })),
+ errors: [],
+ });
+ await vi.waitFor(() => {
+ expect(requests).toHaveLength(2);
+ });
+ expect(requests[1].body.getAll('files')).toEqual([oldFiles[15]]);
+ requests[1].respond(200, {
+ uploaded: [{ filename: oldFiles[15].name, status: 'uploaded' }],
+ errors: [],
+ });
+ await upload;
+
+ expect(form.querySelector('button[type="submit"]').disabled).toBe(false);
+ runtime.handleFiles([newFile]);
+ expect(runtime.getSelectedFiles()).toEqual([newFile]);
+ expect(document.getElementById('file-list').textContent)
+ .toContain('new-selection.txt');
+
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(resetSpy).not.toHaveBeenCalled();
+ expect(runtime.getSelectedFiles()).toEqual([newFile]);
+ expect(document.getElementById('selected-files').style.display)
+ .toBe('block');
+ expect(document.getElementById('file-list').textContent)
+ .toContain('new-selection.txt');
+ expect(calls.showUploadResults).not.toHaveBeenCalled();
+});
+
+it('continues later batches and reports every file from a failed batch', async () => {
+ vi.useFakeTimers();
+ const form = renderUploadForm();
+ const resetSpy = vi.spyOn(form, 'reset');
+ const files = Array.from({ length: 31 }, (_, index) => new File(
+ [`batch-${index}`],
+ `batch-${index}.txt`,
+ ));
+ const requests = installFakeXmlHttpRequest();
+ const { calls, runtime, SafeLogger } = compileRealUploadRuntime(files);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-partial-batch') };
+
+ const upload = runtime.handleUploadFiles(submitEvent(form));
+ expect(requests).toHaveLength(1);
+ requests[0].respond(200, {
+ uploaded: files.slice(0, 15).map(file => ({
+ filename: file.name,
+ status: 'uploaded',
+ })),
+ errors: [],
+ });
+
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
+ requests[1].failNetwork();
+ await vi.waitFor(() => expect(requests).toHaveLength(3));
+ requests[2].respond(200, {
+ uploaded: [{ filename: files[30].name, status: 'uploaded' }],
+ errors: [],
+ });
+ await upload;
+
+ expect(requests.map(request => request.body.getAll('files').length))
+ .toEqual([15, 15, 1]);
+ for (const request of requests) {
+ expect(request.openCalls).toEqual([[
+ 'POST',
+ '/library/api/collections/collection-3299/upload',
+ ]]);
+ expect(request.headers).toEqual({
+ 'X-CSRFToken': 'csrf-partial-batch',
+ });
+ expect(request.timeout).toBe(300000);
+ }
+
+ const combinedResult = {
+ success: true,
+ uploaded: [
+ ...files.slice(0, 15).map(file => ({
+ filename: file.name,
+ status: 'uploaded',
+ })),
+ { filename: files[30].name, status: 'uploaded' },
+ ],
+ errors: files.slice(15, 30).map(file => ({
+ filename: file.name,
+ error: 'Network error',
+ })),
+ summary: { successful: 16, failed: 15 },
+ };
+ expect(calls.updateProgressComplete).toHaveBeenCalledWith(combinedResult);
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Batch 2 failed:',
+ expect.objectContaining({ message: 'Network error' }),
+ );
+ expect(form.querySelector('button[type="submit"]').disabled).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(calls.showUploadResults).toHaveBeenCalledWith(combinedResult);
+ expect(resetSpy).toHaveBeenCalledOnce();
+ expect(runtime.getSelectedFiles()).toEqual([]);
+});
diff --git a/tests/js/collections-manager-bootstrap-runtime.test.js b/tests/js/collections-manager-bootstrap-runtime.test.js
new file mode 100644
index 0000000000..edbb4c8ed1
--- /dev/null
+++ b/tests/js/collections-manager-bootstrap-runtime.test.js
@@ -0,0 +1,162 @@
+/** Browser-shaped bootstrap contract for the checked-in collections page. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../src/local_deep_research/web/templates/pages/collections.html',
+);
+const COLLECTION_ID = 'collection/3299?scope=evidence';
+const ENCODED_COLLECTION_ID = encodeURIComponent(COLLECTION_ID);
+const COLLECTIONS_URL = '/library/api/collections';
+const INDEX_START_URL =
+ `/library/api/collections/${ENCODED_COLLECTION_ID}/index/start`;
+const INDEX_STATUS_URL =
+ `/library/api/collections/${ENCODED_COLLECTION_ID}/index/status`;
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), { status });
+}
+
+it('boots, safely renders collections, and reindexes through the migrated contract', async () => {
+ vi.resetModules();
+ delete window.__collectionsBootstrapXss;
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture.
+ document.body.innerHTML = readFileSync(TEMPLATE_PATH, 'utf8');
+
+ const hostileName =
+ '<img src=x onerror="window.__collectionsBootstrapXss=true"> Evidence';
+ const hostileDescription =
+ '<script>window.__collectionsBootstrapXss=true</script> Sources';
+ const collectionPayload = (indexedDocuments) => ({
+ id: COLLECTION_ID,
+ name: hostileName,
+ description: hostileDescription,
+ document_count: '5.9',
+ indexed_document_count: indexedDocuments,
+ created_at: '2026-09-01T08:00:00Z',
+ embedding: {
+ provider: '<img src=x onerror=alert(1)>',
+ model: '"><img src=x onerror=alert(1)>migration-model',
+ },
+ });
+
+ let collectionsLoads = 0;
+ const safeFetchWithAuth = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === COLLECTIONS_URL) {
+ collectionsLoads += 1;
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [collectionPayload(
+ collectionsLoads === 1 ? '2.9' : '5',
+ )],
+ }));
+ }
+ if (url === '/settings/api/research_library.auto_index_enabled') {
+ return Promise.resolve(jsonResponse({ value: false }));
+ }
+ if (
+ url ===
+ '/settings/api/document_scheduler.sweep_library_collections'
+ ) {
+ return Promise.resolve(jsonResponse({ value: true }));
+ }
+ if (url === '/settings/api/document_scheduler.enabled') {
+ return Promise.resolve(jsonResponse({ value: true }));
+ }
+ if (url === INDEX_START_URL && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({ success: true }, 202));
+ }
+ if (url === INDEX_STATUS_URL && !options.method) {
+ return Promise.resolve(jsonResponse({
+ status: 'completed',
+ result: {
+ indexed_documents: 5,
+ indexed_chunks: 12,
+ },
+ }));
+ }
+ throw new Error(`Unexpected collections request: ${url}`);
+ });
+
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ COLLECTIONS: COLLECTIONS_URL,
+ COLLECTION_INDEX_START:
+ '/library/api/collections/{id}/index/start',
+ COLLECTION_INDEX_STATUS:
+ '/library/api/collections/{id}/index/status',
+ },
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-collections-3299') };
+
+ await import('@js/security/xss-protection.js');
+ await import('@js/collections_manager.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-collection-card-wrapper'))
+ .toHaveLength(1);
+ });
+
+ const container = document.getElementById('collections-container');
+ const wrapper = container.querySelector('.ldr-collection-card-wrapper');
+ const card = wrapper.querySelector('.ldr-collection-card');
+ const viewLink = wrapper.querySelector('.ldr-collection-view-link');
+ expect(container.style.display).toBe('grid');
+ expect(document.getElementById('no-collections-message').style.display)
+ .toBe('none');
+ expect(wrapper.dataset.id).toBe(COLLECTION_ID);
+ expect(wrapper.textContent).toContain(hostileName);
+ expect(wrapper.textContent).toContain(hostileDescription);
+ expect(wrapper.querySelector('img')).toBeNull();
+ expect(wrapper.querySelector('script')).toBeNull();
+ expect(window.__collectionsBootstrapXss).toBeUndefined();
+ expect(card.getAttribute('href'))
+ .toBe(`/library/collections/${ENCODED_COLLECTION_ID}`);
+ expect(viewLink.getAttribute('href'))
+ .toBe(`/library/collections/${ENCODED_COLLECTION_ID}`);
+ expect(wrapper.textContent).toContain('5 documents');
+ expect(wrapper.textContent).toContain('2 of 5 indexed');
+ expect(wrapper.textContent).toContain('3 pending indexing');
+
+ const reindexButton = wrapper.querySelector('.ldr-reindex-btn');
+ expect(reindexButton.closest('a')).toBeNull();
+ reindexButton.querySelector('i').click();
+
+ await vi.waitFor(() => {
+ expect(collectionsLoads).toBe(2);
+ expect(document.querySelector('.ldr-collection-card-wrapper')
+ .textContent).toContain('5 of 5 indexed');
+ });
+ expect(safeFetchWithAuth).toHaveBeenCalledWith(INDEX_START_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-collections-3299',
+ },
+ body: JSON.stringify({ force_reindex: false }),
+ });
+ expect(safeFetchWithAuth).toHaveBeenCalledWith(INDEX_STATUS_URL);
+ expect(safeFetchWithAuth.mock.calls.filter(
+ ([url]) => String(url) === COLLECTIONS_URL,
+ )).toHaveLength(2);
+
+ const refreshedWrapper = document.querySelector(
+ '.ldr-collection-card-wrapper',
+ );
+ expect(refreshedWrapper.textContent).toContain('5 of 5 indexed');
+ expect(refreshedWrapper.querySelector('.ldr-pending-index-badge'))
+ .toBeNull();
+ expect(refreshedWrapper.querySelector('.ldr-reindex-btn').disabled)
+ .toBe(false);
+
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.__collectionsBootstrapXss;
+});
diff --git a/tests/js/collections-manager.test.js b/tests/js/collections-manager.test.js
index 62f31ddea0..502d6ac7fb 100644
--- a/tests/js/collections-manager.test.js
+++ b/tests/js/collections-manager.test.js
@@ -35,15 +35,29 @@ let indexStatusMarkup;
let triggerReindex;
let bindReindexButtons;
let collectionApiUrl;
+let loadAutoIndexSetting;
+let saveAutoIndexSetting;
let loadBackgroundSweepSetting;
let saveBackgroundSweepSetting;
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, reject: rejectPromise, resolve: resolvePromise };
+}
+
beforeAll(async () => {
await import('@js/collections_manager.js');
indexStatusMarkup = window.indexStatusMarkup;
triggerReindex = window.triggerReindex;
bindReindexButtons = window.bindReindexButtons;
collectionApiUrl = window.collectionApiUrl;
+ loadAutoIndexSetting = window.loadAutoIndexSetting;
+ saveAutoIndexSetting = window.saveAutoIndexSetting;
loadBackgroundSweepSetting = window.loadBackgroundSweepSetting;
saveBackgroundSweepSetting = window.saveBackgroundSweepSetting;
});
@@ -52,6 +66,187 @@ beforeEach(() => {
globalThis.safeFetchWithAuth.mockReset();
});
+describe('auto-index toggle ownership', () => {
+ function makeToggle() {
+ document.body.innerHTML =
+ '<input type="checkbox" id="auto-index-toggle">';
+ return document.getElementById('auto-index-toggle');
+ }
+
+ it.each([false, true])('restores confirmed %s after two failed queued writes', async (initial) => {
+ const toggle = makeToggle();
+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ value: initial }),
+ });
+ await loadAutoIndexSetting();
+
+ const first = deferred();
+ const second = deferred();
+ globalThis.safeFetchWithAuth.mockReset()
+ .mockImplementationOnce(() => first.promise)
+ .mockImplementationOnce(() => second.promise);
+ toggle.checked = !initial;
+ const firstSave = saveAutoIndexSetting();
+ toggle.checked = initial;
+ const secondSave = saveAutoIndexSetting();
+ await vi.waitFor(() => expect(globalThis.safeFetchWithAuth).toHaveBeenCalledOnce());
+
+ first.resolve({ ok: false, json: async () => ({ error: 'save rejected' }) });
+ await vi.waitFor(() => expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2));
+ expect(toggle.checked).toBe(initial);
+ second.reject(new Error('save rejected'));
+ await Promise.all([firstSave, secondSave]);
+
+ expect(toggle.checked).toBe(initial);
+ expect(globalThis.safeFetchWithAuth.mock.calls.map(([, options]) => (
+ JSON.parse(options.body).value
+ ))).toEqual([!initial, initial]);
+ });
+
+ it('restores an earlier successful write when the latest write fails', async () => {
+ const toggle = makeToggle();
+ globalThis.safeFetchWithAuth.mockResolvedValueOnce({
+ ok: true,
+ json: async () => ({ value: false }),
+ });
+ await loadAutoIndexSetting();
+ globalThis.safeFetchWithAuth.mockReset()
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ value: true }) })
+ .mockResolvedValueOnce({ ok: false, json: async () => ({ error: 'save rejected' }) });
+ toggle.checked = true;
+ const firstSave = saveAutoIndexSetting();
+ toggle.checked = false;
+ const secondSave = saveAutoIndexSetting();
+ await Promise.all([firstSave, secondSave]);
+ expect(toggle.checked).toBe(true);
+ });
+
+ it('serializes rapid changes back to the older value and ignores the older rejection', async () => {
+ const toggle = makeToggle();
+ const older = deferred();
+ const middle = deferred();
+ const latest = deferred();
+ globalThis.safeFetchWithAuth
+ .mockImplementationOnce(() => older.promise)
+ .mockImplementationOnce(() => middle.promise)
+ .mockImplementationOnce(() => latest.promise);
+
+ toggle.checked = true;
+ const olderSave = saveAutoIndexSetting();
+ toggle.checked = false;
+ const middleSave = saveAutoIndexSetting();
+ toggle.checked = true;
+ const latestSave = saveAutoIndexSetting();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledOnce();
+ });
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[0][1].body))
+ .toEqual({ value: true });
+
+ older.reject(new Error('older write failed'));
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+ expect(toggle.checked).toBe(true);
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[1][1].body))
+ .toEqual({ value: false });
+
+ middle.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(3);
+ });
+ expect(toggle.checked).toBe(true);
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[2][1].body))
+ .toEqual({ value: true });
+
+ latest.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ await Promise.all([olderSave, middleSave, latestSave]);
+
+ expect(toggle.checked).toBe(true);
+ expect(globalThis.safeFetchWithAuth.mock.calls.map(([, options]) => (
+ JSON.parse(options.body).value
+ ))).toEqual([true, false, true]);
+ });
+
+ it('does not let late hydration overwrite a user save', async () => {
+ const toggle = makeToggle();
+ const hydration = deferred();
+ globalThis.safeFetchWithAuth.mockImplementation((url, options = {}) => {
+ if (options.method === 'PUT') {
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ }
+ expect(url).toBe('/settings/api/research_library.auto_index_enabled');
+ return hydration.promise;
+ });
+
+ const load = loadAutoIndexSetting();
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledOnce();
+ });
+
+ toggle.checked = true;
+ const save = saveAutoIndexSetting();
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+ hydration.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+ await Promise.all([load, save]);
+
+ expect(toggle.checked).toBe(true);
+ const [, options] = globalThis.safeFetchWithAuth.mock.calls[1];
+ expect(JSON.parse(options.body)).toEqual({ value: true });
+ });
+
+ it('does not let a late hydration body overwrite a user save', async () => {
+ const toggle = makeToggle();
+ const hydrationBody = deferred();
+ const hydrationJson = vi.fn(() => hydrationBody.promise);
+ globalThis.safeFetchWithAuth.mockImplementation((url, options = {}) => {
+ expect(url).toBe('/settings/api/research_library.auto_index_enabled');
+ if (options.method === 'PUT') {
+ return Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ }
+ return Promise.resolve({
+ ok: true,
+ json: hydrationJson,
+ });
+ });
+
+ const load = loadAutoIndexSetting();
+ await vi.waitFor(() => {
+ expect(hydrationJson).toHaveBeenCalledOnce();
+ });
+
+ toggle.checked = true;
+ await saveAutoIndexSetting();
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+
+ hydrationBody.resolve({ value: false });
+ await load;
+
+ expect(toggle.checked).toBe(true);
+ const [, options] = globalThis.safeFetchWithAuth.mock.calls[1];
+ expect(JSON.parse(options.body)).toEqual({ value: true });
+ });
+});
+
describe('indexStatusMarkup', () => {
it('reports "<indexed> of <total> indexed" and a pending badge when work remains', () => {
const html = indexStatusMarkup({ document_count: 5, indexed_document_count: 2 });
@@ -993,4 +1188,209 @@ describe('background-sweep toggle', () => {
expect(JSON.parse(calls[0][1].body)).toEqual({ value: true });
expect(toggle.checked).toBe(true);
});
+
+ it('serializes rapid changes through the legacy OFF transaction before the latest ON', async () => {
+ const toggle = makeToggle();
+ const olderSweep = deferred();
+ const middleSweep = deferred();
+ const legacyClear = deferred();
+ const latestSweep = deferred();
+ globalThis.safeFetchWithAuth
+ .mockImplementationOnce(() => olderSweep.promise)
+ .mockImplementationOnce(() => middleSweep.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ })
+ .mockImplementationOnce(() => legacyClear.promise)
+ .mockImplementationOnce(() => latestSweep.promise);
+
+ toggle.checked = true;
+ const olderSave = saveBackgroundSweepSetting();
+ toggle.checked = false;
+ const middleSave = saveBackgroundSweepSetting();
+ toggle.checked = true;
+ const latestSave = saveBackgroundSweepSetting();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledOnce();
+ });
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[0][1].body))
+ .toEqual({ value: true });
+
+ olderSweep.reject(new Error('older sweep write failed'));
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+ expect(toggle.checked).toBe(true);
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[1][1].body))
+ .toEqual({ value: false });
+
+ middleSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(4);
+ });
+ const calls = globalThis.safeFetchWithAuth.mock.calls;
+ expect(calls[2]).toEqual([
+ '/settings/api/document_scheduler.generate_rag',
+ ]);
+ expect(calls[3][0])
+ .toBe('/settings/api/document_scheduler.generate_rag');
+ expect(JSON.parse(calls[3][1].body)).toEqual({ value: false });
+ expect(toggle.checked).toBe(true);
+
+ legacyClear.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(5);
+ });
+ expect(globalThis.safeFetchWithAuth.mock.calls[4][0])
+ .toBe('/settings/api/document_scheduler.sweep_library_collections');
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[4][1].body))
+ .toEqual({ value: true });
+
+ latestSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ await Promise.all([olderSave, middleSave, latestSave]);
+
+ expect(toggle.checked).toBe(true);
+ });
+
+ it('does not let an older indeterminate success flip the latest OFF state', async () => {
+ const toggle = makeToggle();
+ const olderSweep = deferred();
+ const middleSweep = deferred();
+ const latestSweep = deferred();
+ globalThis.safeFetchWithAuth
+ .mockImplementationOnce(() => olderSweep.promise)
+ .mockImplementationOnce(() => middleSweep.promise)
+ .mockImplementationOnce(() => latestSweep.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+
+ toggle.checked = false;
+ const olderSave = saveBackgroundSweepSetting();
+ toggle.checked = true;
+ const middleSave = saveBackgroundSweepSetting();
+ toggle.checked = false;
+ const latestSave = saveBackgroundSweepSetting();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledOnce();
+ });
+ olderSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve(null),
+ });
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+ expect(toggle.checked).toBe(false);
+
+ middleSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(3);
+ });
+ expect(toggle.checked).toBe(false);
+ expect(JSON.parse(globalThis.safeFetchWithAuth.mock.calls[2][1].body))
+ .toEqual({ value: false });
+
+ latestSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: false }),
+ });
+ await Promise.all([olderSave, middleSave, latestSave]);
+
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(4);
+ expect(globalThis.safeFetchWithAuth.mock.calls[3]).toEqual([
+ '/settings/api/document_scheduler.generate_rag',
+ ]);
+ expect(toggle.checked).toBe(false);
+ });
+});
+
+describe('toggle save isolation', () => {
+ it.each([
+ [false, 'HTTP'], [true, 'HTTP'], [false, 'network'], [true, 'network'],
+ ])('restores sweep baseline %s after consecutive %s failures', async (initial, failure) => {
+ document.body.innerHTML = '<input type="checkbox" id="background-sweep-toggle">';
+ const toggle = document.getElementById('background-sweep-toggle');
+ globalThis.safeFetchWithAuth.mockImplementation(async () => {
+ if (failure === 'network') throw new Error('save unavailable');
+ return { ok: false, json: async () => ({ error: 'save rejected' }) };
+ });
+ toggle.checked = !initial;
+ const firstSave = saveBackgroundSweepSetting();
+ toggle.checked = initial;
+ const secondSave = saveBackgroundSweepSetting();
+ await Promise.all([firstSave, secondSave]);
+
+ expect(toggle.checked).toBe(initial);
+ expect(globalThis.safeFetchWithAuth.mock.calls.map(([, options]) => (
+ JSON.parse(options.body).value
+ ))).toEqual([!initial, initial]);
+ });
+
+ it('retains a confirmed sweep enable when the queued disable fails', async () => {
+ document.body.innerHTML = '<input type="checkbox" id="background-sweep-toggle">';
+ const toggle = document.getElementById('background-sweep-toggle');
+ globalThis.safeFetchWithAuth
+ .mockResolvedValueOnce({ ok: true, json: async () => ({ value: true }) })
+ .mockResolvedValueOnce({ ok: false, json: async () => ({ error: 'save rejected' }) });
+ toggle.checked = true;
+ const firstSave = saveBackgroundSweepSetting();
+ toggle.checked = false;
+ const secondSave = saveBackgroundSweepSetting();
+ await Promise.all([firstSave, secondSave]);
+
+ expect(toggle.checked).toBe(true);
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not block a background-sweep save behind auto-index', async () => {
+ document.body.innerHTML = `
+ <input type="checkbox" id="auto-index-toggle" checked>
+ <input type="checkbox" id="background-sweep-toggle" checked>
+ `;
+ const autoIndex = deferred();
+ const backgroundSweep = deferred();
+ globalThis.safeFetchWithAuth.mockImplementation(url => {
+ if (url.includes('auto_index_enabled')) return autoIndex.promise;
+ return backgroundSweep.promise;
+ });
+
+ const autoSave = saveAutoIndexSetting();
+ const sweepSave = saveBackgroundSweepSetting();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledTimes(2);
+ });
+ expect(globalThis.safeFetchWithAuth.mock.calls.map(([url]) => url))
+ .toEqual(expect.arrayContaining([
+ '/settings/api/research_library.auto_index_enabled',
+ '/settings/api/document_scheduler.sweep_library_collections',
+ ]));
+
+ autoIndex.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ backgroundSweep.resolve({
+ ok: true,
+ json: () => Promise.resolve({ value: true }),
+ });
+ await Promise.all([autoSave, sweepSave]);
+ });
});
diff --git a/tests/js/components/annotation-surface-mutations.test.js b/tests/js/components/annotation-surface-mutations.test.js
new file mode 100644
index 0000000000..a6161daa17
--- /dev/null
+++ b/tests/js/components/annotation-surface-mutations.test.js
@@ -0,0 +1,274 @@
+/**
+ * Direct mutation contracts for the shared research/document annotation UI.
+ * Existing coverage pins quote anchoring; these cases exercise the browser
+ * selection toolbar and the FastAPI create/delete lifecycles themselves.
+ */
+
+let postJson;
+let toast;
+let onChanged;
+
+const apiResponse = (data, { ok = true, status = 200 } = {}) => ({
+ ok,
+ status,
+ json: () => Promise.resolve(data),
+});
+
+const flush = () => new Promise(resolve => setTimeout(resolve, 0));
+
+function buildSurface(html = '<p>A sufficiently long selected passage lives here.</p>') {
+ const container = document.createElement('article');
+ container.id = 'annotation-content';
+ // eslint-disable-next-line no-unsanitized/property -- static test fixture
+ container.innerHTML = html;
+ document.body.replaceChildren(container);
+ return container;
+}
+
+function initSurface() {
+ onChanged = vi.fn();
+ return window.LDRAnnotationSurface.init({
+ containerId: 'annotation-content',
+ endpoints: {
+ list: '/notes/api/research/run-1/annotations',
+ create: '/notes/api/research/run-1/annotations',
+ deleteFor: noteId =>
+ `/notes/api/research/run-1/annotations/${encodeURIComponent(noteId)}`,
+ },
+ onChanged,
+ });
+}
+
+function installSelection(container, selectedText) {
+ const textNode = container.querySelector('p').firstChild;
+ const range = {
+ commonAncestorContainer: textNode,
+ getBoundingClientRect: () => ({
+ top: 80,
+ bottom: 100,
+ left: 40,
+ width: 180,
+ }),
+ comparePoint: () => 0,
+ };
+ vi.spyOn(window, 'getSelection').mockReturnValue({
+ isCollapsed: false,
+ rangeCount: 1,
+ getRangeAt: () => range,
+ toString: () => selectedText,
+ });
+ return range;
+}
+
+beforeEach(async () => {
+ vi.resetModules();
+ document.body.replaceChildren();
+ window.__VITEST_TEST__ = true;
+ postJson = vi.fn();
+ toast = vi.fn();
+ window.NotesShared = {
+ csrfToken: vi.fn(() => 'csrf-annotation'),
+ postJson,
+ toast,
+ };
+ globalThis.safeFetchWithAuth = vi.fn().mockResolvedValue(apiResponse({
+ success: true,
+ annotations: [],
+ }));
+ window.confirm = vi.fn(() => true);
+ vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+ await import('@js/components/annotation_surface.js');
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.replaceChildren();
+ delete window.__annotationSurfaceTest;
+ delete window.LDRAnnotationSurface;
+ delete window.confirm;
+});
+
+afterAll(() => {
+ delete window.__VITEST_TEST__;
+});
+
+async function openCreatePopover(selectedText) {
+ const container = buildSurface();
+ installSelection(container, selectedText);
+ initSurface();
+ await flush();
+
+ document.dispatchEvent(new Event('mouseup'));
+ await flush();
+ const toolbar = document.querySelector('.ldr-selection-toolbar');
+ expect(toolbar.style.display).toBe('inline-flex');
+ toolbar.querySelector('button').dispatchEvent(new MouseEvent('mousedown', {
+ bubbles: true,
+ cancelable: true,
+ }));
+ return document.querySelector('.ldr-annotation-popover');
+}
+
+it('creates a bounded annotation through the shared FastAPI endpoint', async () => {
+ postJson.mockResolvedValue({ success: true, note_id: 'note-1' });
+ const selectedText = ` ${'x'.repeat(1010)} `;
+ const popover = await openCreatePopover(selectedText);
+ const textarea = popover.querySelector('textarea');
+ textarea.value = 'Migration comment';
+
+ popover.querySelector('.btn-primary').click();
+
+ await vi.waitFor(() => {
+ expect(postJson).toHaveBeenCalledOnce();
+ });
+ const [url, body] = postJson.mock.calls[0];
+ expect(url).toBe('/notes/api/research/run-1/annotations');
+ expect(body.quote).toBe('x'.repeat(1000));
+ expect(body.comment).toBe('Migration comment');
+ expect(body).toEqual(expect.objectContaining({ prefix: '', suffix: '' }));
+ expect(document.querySelector('.ldr-annotation-popover')).toBeNull();
+ expect(toast).toHaveBeenCalledWith('Comment saved as a note', 'success');
+ expect(onChanged).toHaveBeenCalledOnce();
+});
+
+it('keeps the creation popover retryable after a failed mutation', async () => {
+ postJson.mockRejectedValue(new Error('annotation quota reached'));
+ const popover = await openCreatePopover('A sufficiently long selected passage');
+ const textarea = popover.querySelector('textarea');
+ textarea.value = 'Keep this comment';
+ const save = popover.querySelector('.btn-primary');
+
+ save.click();
+
+ await vi.waitFor(() => {
+ expect(toast)
+ .toHaveBeenCalledWith('annotation quota reached', 'error');
+ });
+ expect(save.disabled).toBe(false);
+ expect(document.querySelector('.ldr-annotation-popover')).toBe(popover);
+ expect(onChanged).not.toHaveBeenCalled();
+});
+
+it('does not submit an empty annotation comment', async () => {
+ const popover = await openCreatePopover('A sufficiently long selected passage');
+
+ popover.querySelector('.btn-primary').click();
+
+ expect(postJson).not.toHaveBeenCalled();
+ expect(document.querySelector('.ldr-annotation-popover')).toBe(popover);
+});
+
+it('deletes every segment of an annotation with CSRF ownership', async () => {
+ const container = buildSurface(
+ '<p>cost substantially, but<br>shared ownership matters</p>',
+ );
+ const annotation = {
+ note_id: 'note /?#',
+ quote: 'substantially, but shared ownership',
+ prefix: '',
+ suffix: '',
+ comment_preview: '<img src=x onerror="window.pwned=true">\n> quote',
+ };
+ let deleted = false;
+ globalThis.safeFetchWithAuth.mockImplementation((_url, options) => {
+ if (options?.method === 'DELETE') {
+ deleted = true;
+ return Promise.resolve(apiResponse({ success: true }));
+ }
+ return Promise.resolve(apiResponse({
+ success: true,
+ annotations: deleted ? [] : [annotation],
+ }));
+ });
+ initSurface();
+ await vi.waitFor(() => {
+ expect(container.querySelectorAll('mark')).toHaveLength(2);
+ });
+
+ container.querySelector('mark').click();
+ const popover = document.querySelector('.ldr-annotation-popover');
+ expect(popover.textContent).toContain('<img src=x');
+ expect(popover.querySelector('img')).toBeNull();
+ expect(popover.querySelector('a').getAttribute('href'))
+ .toBe('/notes/note%20%2F%3F%23');
+ popover.querySelector('button').click();
+
+ await vi.waitFor(() => {
+ expect(toast).toHaveBeenCalledWith('Comment deleted', 'success');
+ });
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith(
+ '/notes/api/research/run-1/annotations/note%20%2F%3F%23',
+ {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': 'csrf-annotation' },
+ credentials: 'same-origin',
+ },
+ );
+ expect(container.querySelectorAll('mark')).toHaveLength(0);
+ expect(onChanged).toHaveBeenCalledOnce();
+});
+
+it('surfaces FastAPI detail and keeps a failed deletion retryable', async () => {
+ const container = buildSurface('<p>This annotated passage remains visible.</p>');
+ const annotation = {
+ note_id: 'note-2',
+ quote: 'annotated passage',
+ prefix: '',
+ suffix: '',
+ comment_preview: 'Keep this note',
+ };
+ globalThis.safeFetchWithAuth.mockImplementation((_url, options) => {
+ if (options?.method === 'DELETE') {
+ return Promise.resolve(apiResponse(
+ { detail: 'note is locked' },
+ { ok: false, status: 409 },
+ ));
+ }
+ return Promise.resolve(apiResponse({
+ success: true,
+ annotations: [annotation],
+ }));
+ });
+ initSurface();
+ await vi.waitFor(() => {
+ expect(container.querySelector('mark')).not.toBeNull();
+ });
+
+ container.querySelector('mark').click();
+ const remove = document.querySelector('.ldr-annotation-popover button');
+ remove.click();
+
+ await vi.waitFor(() => {
+ expect(toast).toHaveBeenCalledWith('note is locked', 'error');
+ });
+ expect(remove.disabled).toBe(false);
+ expect(container.querySelector('mark')).not.toBeNull();
+ expect(onChanged).not.toHaveBeenCalled();
+});
+
+it('honors deletion cancellation without calling the API', async () => {
+ const container = buildSurface('<p>This annotated passage remains visible.</p>');
+ const annotation = {
+ note_id: 'note-3',
+ quote: 'annotated passage',
+ prefix: '',
+ suffix: '',
+ note_title: 'A note',
+ };
+ globalThis.safeFetchWithAuth.mockResolvedValue(apiResponse({
+ success: true,
+ annotations: [annotation],
+ }));
+ window.confirm.mockReturnValue(false);
+ initSurface();
+ await vi.waitFor(() => {
+ expect(container.querySelector('mark')).not.toBeNull();
+ });
+ globalThis.safeFetchWithAuth.mockClear();
+
+ container.querySelector('mark').click();
+ document.querySelector('.ldr-annotation-popover button').click();
+
+ expect(globalThis.safeFetchWithAuth).not.toHaveBeenCalled();
+ expect(container.querySelector('mark')).not.toBeNull();
+});
diff --git a/tests/js/components/chat-live-step-detail.test.js b/tests/js/components/chat-live-step-detail.test.js
index d41ae217b0..ecc390d5d0 100644
--- a/tests/js/components/chat-live-step-detail.test.js
+++ b/tests/js/components/chat-live-step-detail.test.js
@@ -73,10 +73,24 @@ function liveSteps() {
describe('chat.js — live step observation detail (data.content)', () => {
let progressCb;
+ let rawSocket;
+ let socketHandlers;
+ let researchStatusPayload;
beforeEach(async () => {
+ vi.useFakeTimers();
vi.resetModules();
progressCb = null;
+ socketHandlers = {};
+ researchStatusPayload = { status: 'in_progress' };
+ rawSocket = {
+ on: vi.fn((event, callback) => {
+ socketHandlers[event] = callback;
+ }),
+ off: vi.fn((event) => {
+ delete socketHandlers[event];
+ }),
+ };
buildChatDom();
window.api = { getCsrfToken: () => '' };
@@ -86,16 +100,16 @@ describe('chat.js — live step observation detail (data.content)', () => {
progressCb = cb;
}),
unsubscribeFromResearch: vi.fn(),
- getSocketInstance: vi.fn(() => ({
- on: vi.fn(),
- off: vi.fn(),
- })),
+ getSocketInstance: vi.fn(() => rawSocket),
};
// Session restore: one prior user message + an in-progress
// research, so loadSession() subscribes to progress events.
globalThis.fetch = vi.fn(async (url) => {
const u = String(url);
+ if (u === `/api/research/${RESEARCH_ID}/status`) {
+ return json(researchStatusPayload);
+ }
if (u.includes(`/api/chat/sessions/${SESSION_ID}/messages`)) {
return json({
success: true,
@@ -132,6 +146,8 @@ describe('chat.js — live step observation detail (data.content)', () => {
});
afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
delete globalThis.fetch;
});
@@ -199,6 +215,70 @@ describe('chat.js — live step observation detail (data.content)', () => {
expect(preview.textContent).toBe('📄 From arXiv: [2] Paper');
expect(preview.textContent).not.toContain('Abstract text');
});
+
+ it('renders final content from the FastAPI response_chunk channel', () => {
+ const eventName = `response_chunk_${RESEARCH_ID}`;
+
+ expect(rawSocket.off).toHaveBeenCalledWith(eventName);
+ expect(rawSocket.on).toHaveBeenCalledWith(
+ eventName,
+ expect.any(Function),
+ );
+ expect(socketHandlers[eventName]).toBeTypeOf('function');
+
+ socketHandlers[eventName]({
+ chunk: 'Streamed migration ',
+ is_streaming: true,
+ is_final: false,
+ });
+ socketHandlers[eventName]({
+ chunk: 'answer',
+ is_streaming: true,
+ is_final: false,
+ });
+ socketHandlers[eventName]({
+ chunk: '',
+ is_streaming: true,
+ is_final: true,
+ });
+
+ const message = document.querySelector(
+ `.ldr-chat-message[data-research-id="${RESEARCH_ID}"]`,
+ );
+ expect(message).not.toBeNull();
+ expect(message.classList).not.toContain('ldr-chat-message-streaming');
+ expect(message.querySelector('.ldr-chat-message-text').textContent)
+ .toBe('Streamed migration answer');
+ });
+
+ it('surfaces the nested FastAPI failure reason from the HTTP polling backup', async () => {
+ researchStatusPayload = {
+ status: 'failed',
+ metadata: {
+ error_info: {
+ message: 'The selected provider rejected this model',
+ },
+ },
+ };
+
+ await vi.advanceTimersByTimeAsync(1000);
+ await flush();
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/research/${RESEARCH_ID}/status`,
+ { headers: { 'X-CSRFToken': '' } },
+ );
+ const assistantMessages = document.querySelectorAll(
+ '.ldr-chat-message-assistant:not(.ldr-chat-message-step)',
+ );
+ expect(assistantMessages).toHaveLength(1);
+ expect(assistantMessages[0].querySelector('.ldr-chat-message-text').textContent)
+ .toBe('The selected provider rejected this model');
+ expect(window.socket.unsubscribeFromResearch)
+ .toHaveBeenCalledWith(RESEARCH_ID);
+ expect(rawSocket.off)
+ .toHaveBeenCalledWith(`response_chunk_${RESEARCH_ID}`);
+ });
});
describe('chat.js — reloaded step icons use the persisted phase', () => {
diff --git a/tests/js/components/chat-migration-runtime.test.js b/tests/js/components/chat-migration-runtime.test.js
new file mode 100644
index 0000000000..4e21f1e726
--- /dev/null
+++ b/tests/js/components/chat-migration-runtime.test.js
@@ -0,0 +1,2796 @@
+/**
+ * Direct FastAPI migration contracts for the core chat lifecycle.
+ * Existing tests focus on copy buttons and live progress; this suite owns
+ * session restore/pagination, send concurrency/errors, attempt mutations,
+ * title persistence, and complete paginated export.
+ */
+
+const SESSION_ID = 'session-1';
+
+const jsonResponse = (payload, status = 200) => ({
+ ok: status >= 200 && status < 300,
+ status,
+ json: () => Promise.resolve(payload),
+});
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function buildChatDom({ sessionMeta = true } = {}) {
+ document.head.innerHTML = `
+ <meta name="csrf-token" content="csrf-meta">
+ `;
+ if (sessionMeta) {
+ const meta = document.createElement('meta');
+ meta.name = 'chat-session-id';
+ meta.content = SESSION_ID;
+ document.head.appendChild(meta);
+ }
+ document.body.innerHTML = `
+ <div id="chat-welcome"></div>
+ <textarea id="chat-input"></textarea>
+ <button id="send-btn"></button>
+ <button id="new-chat-btn"></button>
+ <button id="edit-title-btn"></button>
+ <button id="export-chat-btn"></button>
+ <button id="chat-stop-research-btn"></button>
+ <div id="chat-title"></div>
+ <div id="chat-progress-wrapper"></div>
+ <div id="chat-current-task"></div>
+ <div id="chat-messages" role="log"></div>
+ <template id="thinking-template">
+ <div class="ldr-chat-message ldr-chat-message-assistant ldr-chat-message-thinking">
+ <div class="ldr-chat-message-avatar"><i></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-thinking-text" hidden></div>
+ <div class="ldr-chat-thinking-dots"></div>
+ </div>
+ </div>
+ </template>
+ <template id="message-template">
+ <div class="ldr-chat-message">
+ <div class="ldr-chat-message-avatar"><i></i></div>
+ <div class="ldr-chat-message-content">
+ <div class="ldr-chat-message-text"></div>
+ <div class="ldr-chat-message-meta">
+ <span class="ldr-chat-message-time"></span>
+ </div>
+ </div>
+ </div>
+ </template>
+ `;
+}
+
+function initialMessages(messages = [], hasMore = false, inProgress = null) {
+ return {
+ success: true,
+ messages,
+ has_more: hasMore,
+ in_progress_research_id: inProgress,
+ };
+}
+
+async function loadChat({
+ messages = [],
+ hasMore = false,
+ inProgress = null,
+ sessionMeta = true,
+ fetchRoute,
+} = {}) {
+ buildChatDom({ sessionMeta });
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn().mockResolvedValue({ success: true }),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawHandlers = {};
+ const rawSocket = {
+ on: vi.fn((event, callback) => {
+ rawHandlers[event] = callback;
+ }),
+ off: vi.fn((event) => {
+ delete rawHandlers[event];
+ }),
+ };
+ let progressCallback;
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ window.confirm = vi.fn(() => true);
+ window.alert = vi.fn();
+ globalThis.fetch = vi.fn(async (url, options) => {
+ const routed = await fetchRoute?.(String(url), options);
+ if (routed) return routed;
+ if (String(url) === `/api/chat/sessions/${SESSION_ID}`) {
+ return jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Migration chat' },
+ });
+ }
+ if (String(url) === `/api/chat/sessions/${SESSION_ID}/messages`) {
+ return jsonResponse(initialMessages(messages, hasMore, inProgress));
+ }
+ throw new Error(`Unexpected fetch: ${String(url)}`);
+ });
+
+ await import('@js/components/chat.js');
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+ return {
+ rawSocket,
+ rawHandlers,
+ getProgressCallback: () => progressCallback,
+ };
+}
+
+beforeEach(() => {
+ vi.resetModules();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.ui;
+ delete window.socket;
+ delete window.chatComponent;
+ delete window.confirm;
+ delete window.alert;
+ delete window.prompt;
+ delete window.URLValidator;
+});
+
+it('prepends older messages with the composite FastAPI cursor', async () => {
+ const newest = [{
+ id: 'new /?#',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Newest answer',
+ created_at: '2026-08-31T12:00:00+00:00',
+ }];
+ await loadChat({
+ messages: newest,
+ hasMore: true,
+ fetchRoute: (url) => {
+ if (url.includes('?before_created_at=')) {
+ return jsonResponse(initialMessages([{
+ id: 'old-1',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Oldest question',
+ created_at: '2026-08-30T10:00:00+00:00',
+ }], false));
+ }
+ return null;
+ },
+ });
+
+ document.getElementById('ldr-chat-load-older-btn').click();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Oldest question');
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions/session-1/messages'
+ + '?before_created_at=2026-08-31T12%3A00%3A00%2B00%3A00'
+ + '&before_id=new%20%2F%3F%23',
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ expect(document.getElementById('ldr-chat-load-older-btn')).toBeNull();
+ const bubbles = [...document.querySelectorAll(
+ '#chat-messages > .ldr-chat-message',
+ )].map(element => element.textContent);
+ expect(bubbles[0]).toContain('Oldest question');
+ expect(bubbles[1]).toContain('Newest answer');
+});
+
+it('retires old pagination without releasing the replacement session lock', async () => {
+ const abandonedPage = deferred();
+ const replacementPage = deferred();
+ const replacementPaginationUrls = [];
+ const replacementSessionId = 'replacement-pagination-session';
+ const oldNewest = [{
+ id: 'old-newest',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Newest message in the abandoned session',
+ created_at: '2026-08-31T12:00:00Z',
+ }];
+ const replacementNewest = [{
+ id: 'replacement-newest',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Newest replacement-session message',
+ created_at: '2026-09-01T12:00:00Z',
+ }];
+ await loadChat({
+ messages: oldNewest,
+ hasMore: true,
+ fetchRoute: (url, options = {}) => {
+ if (url.startsWith(
+ `/api/chat/sessions/${SESSION_ID}/messages?`,
+ )) {
+ return abandonedPage.promise;
+ }
+ if (url === '/api/chat/sessions' && options.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'Replacement pagination chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return jsonResponse({ success: true, title: 'Generated replacement' });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options.method === 'POST') {
+ return jsonResponse({ success: true });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}`) {
+ return jsonResponse({
+ success: true,
+ session: {
+ id: replacementSessionId,
+ title: 'Replacement pagination chat',
+ },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && !options.method) {
+ return jsonResponse(initialMessages(
+ replacementNewest,
+ true,
+ ));
+ }
+ if (url.startsWith(
+ `/api/chat/sessions/${replacementSessionId}/messages?`,
+ )) {
+ replacementPaginationUrls.push(url);
+ if (replacementPaginationUrls.length === 1) {
+ return replacementPage.promise;
+ }
+ return jsonResponse(initialMessages([{
+ id: 'replacement-oldest',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Oldest replacement-session message',
+ created_at: '2026-08-30T10:00:00Z',
+ }], false));
+ }
+ return null;
+ },
+ });
+
+ document.getElementById('ldr-chat-load-older-btn').click();
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'Create the replacement session';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.location.pathname)
+ .toBe(`/chat/${replacementSessionId}`);
+ });
+
+ await window.chatComponent.loadSession(replacementSessionId);
+ document.getElementById('ldr-chat-load-older-btn').click();
+ await vi.waitFor(() => {
+ expect(replacementPaginationUrls).toHaveLength(1);
+ });
+
+ abandonedPage.resolve(jsonResponse(initialMessages([{
+ id: 'abandoned-oldest',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Message from the abandoned session',
+ created_at: '2020-01-01T00:00:00Z',
+ }], false)));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // The stale request's finally block must not unlock the live request.
+ const replacementLoadButton = document.getElementById(
+ 'ldr-chat-load-older-btn',
+ );
+ expect(replacementLoadButton.disabled).toBe(true);
+ replacementLoadButton.dispatchEvent(new MouseEvent('click', {
+ bubbles: true,
+ }));
+ expect(replacementPaginationUrls).toHaveLength(1);
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Message from the abandoned session');
+
+ replacementPage.resolve(jsonResponse(initialMessages([{
+ id: 'replacement-older',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Older replacement-session message',
+ created_at: '2026-08-31T09:00:00Z',
+ }], true)));
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Older replacement-session message');
+ });
+
+ document.getElementById('ldr-chat-load-older-btn').click();
+ await vi.waitFor(() => {
+ expect(replacementPaginationUrls).toHaveLength(2);
+ });
+ expect(replacementPaginationUrls[1]).toContain(
+ 'before_created_at=2026-08-31T09%3A00%3A00Z',
+ );
+ expect(replacementPaginationUrls[1]).toContain(
+ 'before_id=replacement-older',
+ );
+ expect(replacementPaginationUrls[1]).not.toContain('2020-01-01');
+});
+
+it('owns one in-flight send and subscribes to the returned research', async () => {
+ let finishSend;
+ let messagePosts = 0;
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ messagePosts += 1;
+ return new Promise(resolve => {
+ finishSend = resolve;
+ });
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'What changed in FastAPI?';
+ input.dispatchEvent(new Event('input'));
+
+ document.getElementById('send-btn').dispatchEvent(new MouseEvent('click'));
+ document.getElementById('send-btn').dispatchEvent(new MouseEvent('click'));
+
+ expect(messagePosts).toBe(1);
+ expect(document.getElementById('send-btn').disabled).toBe(true);
+ finishSend(jsonResponse({
+ success: true,
+ research_id: 'research-3299',
+ }));
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ 'research-3299',
+ expect.any(Function),
+ );
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ body: JSON.stringify({
+ content: 'What changed in FastAPI?',
+ trigger_research: true,
+ }),
+ },
+ );
+});
+
+it('creates the first chat session before posting its owned message', async () => {
+ const routes = [];
+ await loadChat({
+ sessionMeta: false,
+ fetchRoute: (url, options) => {
+ routes.push([url, options]);
+ if (url === '/api/chat/sessions?limit=1') {
+ return jsonResponse({ success: true, sessions: [] });
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: 'created-1',
+ session: { title: 'Fallback title' },
+ });
+ }
+ if (url === '/api/chat/sessions/created-1/generate-title') {
+ return jsonResponse({
+ success: true,
+ title: 'Generated migration title',
+ });
+ }
+ if (url === '/api/chat/sessions/created-1/messages') {
+ return jsonResponse({
+ success: true,
+ research_id: 'created-research',
+ });
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'First migrated question';
+ input.dispatchEvent(new Event('input'));
+
+ document.getElementById('send-btn').click();
+
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ 'created-research',
+ expect.any(Function),
+ );
+ });
+ expect(routes).toContainEqual([
+ '/api/chat/sessions',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ body: JSON.stringify({ initial_query: 'First migrated question' }),
+ },
+ ]);
+ expect(routes).toContainEqual([
+ '/api/chat/sessions/created-1/messages',
+ expect.objectContaining({
+ body: JSON.stringify({
+ content: 'First migrated question',
+ trigger_research: true,
+ }),
+ }),
+ ]);
+ expect(window.location.pathname).toBe('/chat/created-1');
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Generated migration title');
+ });
+});
+
+it('consumes the routed q parameter only after restoring its target session', async () => {
+ const researchId = 'routed-query-research';
+ const routedQuery = 'What changed in the FastAPI migration?';
+ history.replaceState(
+ {},
+ '',
+ `/chat/${SESSION_ID}?q=${encodeURIComponent(routedQuery)}`,
+ );
+ await loadChat({
+ messages: [],
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: researchId,
+ });
+ }
+ return null;
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ researchId,
+ expect.any(Function),
+ );
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/messages`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ body: JSON.stringify({
+ content: routedQuery,
+ trigger_research: true,
+ }),
+ },
+ );
+ expect(document.querySelector('.ldr-chat-message-user').textContent)
+ .toContain(routedQuery);
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
+ expect(window.location.search).toBe('');
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it('creates a fresh session for q when no recent chat exists', async () => {
+ const initialQuery = 'Start a fresh migrated chat';
+ const createdSessionId = 'query-created-session';
+ const researchId = 'query-created-research';
+ history.replaceState(
+ {},
+ '',
+ `/chat/?q=${encodeURIComponent(initialQuery)}`,
+ );
+ await loadChat({
+ sessionMeta: false,
+ fetchRoute: (url, options) => {
+ if (url === '/api/chat/sessions?limit=1') {
+ return jsonResponse({ success: true, sessions: [] });
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: createdSessionId,
+ session: { title: 'Fresh routed query' },
+ });
+ }
+ if (url === `/api/chat/sessions/${createdSessionId}/generate-title`) {
+ return jsonResponse({ success: false });
+ }
+ if (url === `/api/chat/sessions/${createdSessionId}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({ success: true, research_id: researchId });
+ }
+ return null;
+ },
+ });
+
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ researchId,
+ expect.any(Function),
+ );
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ initial_query: initialQuery }),
+ }),
+ );
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${createdSessionId}/messages`,
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({
+ content: initialQuery,
+ trigger_research: true,
+ }),
+ }),
+ );
+ expect(window.location.pathname).toBe(`/chat/${createdSessionId}`);
+ expect(window.location.search).toBe('');
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it('consumes q without replaying it after a manual Send during hydration', async () => {
+ const queuedQuery = 'Do not replay this queued query';
+ const manualQuery = 'Manual question owns the composer';
+ const delayedSession = deferred();
+ history.replaceState(
+ {},
+ '',
+ `/chat/${SESSION_ID}?q=${encodeURIComponent(queuedQuery)}`,
+ );
+ buildChatDom();
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn(),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawSocket = { on: vi.fn(), off: vi.fn() };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ globalThis.fetch = vi.fn((url, options = {}) => {
+ const requestUrl = String(url);
+ if (requestUrl === `/api/chat/sessions/${SESSION_ID}`
+ && !options.method) {
+ return delayedSession.promise;
+ }
+ if (requestUrl === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ detail: 'Manual send failed before hydration settled',
+ }, 500));
+ }
+ throw new Error(`Unexpected fetch: ${requestUrl}`);
+ });
+
+ await import('@js/components/chat.js');
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}`,
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ });
+
+ const input = document.getElementById('chat-input');
+ input.value = manualQuery;
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Manual send failed before hydration settled');
+ });
+
+ delayedSession.resolve(jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Delayed routed session' },
+ }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+
+ const messagePosts = globalThis.fetch.mock.calls.filter(
+ ([url, options]) => (
+ url === `/api/chat/sessions/${SESSION_ID}/messages` &&
+ options?.method === 'POST'
+ ),
+ );
+ expect(messagePosts).toHaveLength(1);
+ expect(messagePosts[0][1].body).toBe(JSON.stringify({
+ content: manualQuery,
+ trigger_research: true,
+ }));
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain(queuedQuery);
+ expect(window.location.search).toBe('');
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it('hydrates a non-empty most-recent-session bootstrap through the current page runtime', async () => {
+ const recentMessage = [{
+ id: 'recent-message-3299',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Most recent migrated conversation',
+ created_at: '2026-08-31T12:00:00Z',
+ }];
+ await loadChat({
+ sessionMeta: false,
+ messages: recentMessage,
+ fetchRoute: (url) => {
+ if (url === '/api/chat/sessions?limit=1') {
+ return jsonResponse({
+ success: true,
+ sessions: [{ id: SESSION_ID, title: 'Recent chat' }],
+ });
+ }
+ return null;
+ },
+ });
+
+ expect(window.location.pathname).toBe(`/chat/${SESSION_ID}`);
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Migration chat');
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Most recent migrated conversation');
+ expect(document.getElementById('chat-welcome').style.display).toBe('none');
+ history.replaceState({}, '', '/');
+});
+
+it('keeps a first user-created session authoritative over delayed recent-session bootstrap', async () => {
+ const abandonedRecentSessionId = 'abandoned-recent-session';
+ const replacementSessionId = 'first-user-session';
+ const replacementResearchId = 'first-user-research';
+ const recentSessions = deferred();
+ const sessionCreation = deferred();
+ let abandonedSessionLoads = 0;
+
+ buildChatDom({ sessionMeta: false });
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn(),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawSocket = { on: vi.fn(), off: vi.fn() };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ globalThis.fetch = vi.fn((url, options = {}) => {
+ const requestUrl = String(url);
+ if (requestUrl === '/api/chat/sessions?limit=1') {
+ return recentSessions.promise;
+ }
+ if (requestUrl === '/api/chat/sessions' && options.method === 'POST') {
+ return sessionCreation.promise;
+ }
+ if (requestUrl === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return Promise.resolve(jsonResponse({ success: false }));
+ }
+ if (requestUrl === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ }));
+ }
+ if (requestUrl === `/api/chat/sessions/${abandonedRecentSessionId}`) {
+ abandonedSessionLoads += 1;
+ return Promise.resolve(jsonResponse({
+ success: true,
+ session: {
+ id: abandonedRecentSessionId,
+ title: 'Abandoned recent chat',
+ },
+ }));
+ }
+ if (requestUrl === `/api/chat/sessions/${abandonedRecentSessionId}/messages`) {
+ return Promise.resolve(jsonResponse(initialMessages([], false)));
+ }
+ throw new Error(`Unexpected fetch: ${requestUrl}`);
+ });
+
+ await import('@js/components/chat.js');
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions?limit=1',
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ });
+
+ const input = document.getElementById('chat-input');
+ input.value = 'Create a new chat while recent history is loading';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ recentSessions.resolve(jsonResponse({
+ success: true,
+ sessions: [{
+ id: abandonedRecentSessionId,
+ title: 'Abandoned recent chat',
+ }],
+ }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+ expect(abandonedSessionLoads).toBe(0);
+
+ sessionCreation.resolve(jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'First user-owned chat' },
+ }));
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+
+ expect(abandonedSessionLoads).toBe(0);
+ expect(window.location.pathname).toBe(`/chat/${replacementSessionId}`);
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('First user-owned chat');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(replacementResearchId);
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it.each([
+ [
+ 'an empty session list',
+ recentSessions => recentSessions.resolve(jsonResponse({
+ success: true,
+ sessions: [],
+ })),
+ ],
+ [
+ 'a request failure',
+ recentSessions => recentSessions.reject(new Error('recent sessions unavailable')),
+ ],
+])('does not let delayed recent bootstrap %s restore welcome over a replacement', async (_case, settleRecentSessions) => {
+ const replacementSessionId = 'bootstrap-branch-replacement';
+ const replacementResearchId = 'bootstrap-branch-research';
+ const recentSessions = deferred();
+
+ buildChatDom({ sessionMeta: false });
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn(),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawSocket = { on: vi.fn(), off: vi.fn() };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ globalThis.fetch = vi.fn((url, options = {}) => {
+ const requestUrl = String(url);
+ if (requestUrl === '/api/chat/sessions?limit=1') {
+ return recentSessions.promise;
+ }
+ if (requestUrl === '/api/chat/sessions' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'Bootstrap branch replacement' },
+ }));
+ }
+ if (requestUrl === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return Promise.resolve(jsonResponse({ success: true }));
+ }
+ if (requestUrl === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ }));
+ }
+ throw new Error(`Unexpected fetch: ${requestUrl}`);
+ });
+
+ await import('@js/components/chat.js');
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions?limit=1',
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ });
+
+ const input = document.getElementById('chat-input');
+ input.value = 'Own the blank chat before bootstrap settles';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+ expect(document.getElementById('chat-welcome').style.display).toBe('none');
+
+ settleRecentSessions(recentSessions);
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+
+ expect(document.getElementById('chat-welcome').style.display).toBe('none');
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Bootstrap branch replacement');
+ expect(window.location.pathname).toBe(`/chat/${replacementSessionId}`);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(replacementResearchId);
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it.each([
+ { label: 'metadata response', stage: 'metadata', rejects: false },
+ { label: 'metadata failure', stage: 'metadata', rejects: true },
+ { label: 'messages response', stage: 'messages', rejects: false },
+])('keeps an early Send authoritative over delayed recent-session $label', async ({
+ stage,
+ rejects,
+}) => {
+ const researchId = `early-current-session-${stage}-${rejects}`;
+ const delayedHydration = deferred();
+ let messagesReads = 0;
+
+ buildChatDom({ sessionMeta: false });
+ document.getElementById('chat-title').textContent = 'User-owned current title';
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn(),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawSocket = { on: vi.fn(), off: vi.fn() };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ globalThis.fetch = vi.fn((url, options = {}) => {
+ const requestUrl = String(url);
+ if (requestUrl === '/api/chat/sessions?limit=1') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ sessions: [{ id: SESSION_ID, title: 'Recent current chat' }],
+ }));
+ }
+ if (requestUrl === `/api/chat/sessions/${SESSION_ID}`) {
+ if (stage === 'metadata') return delayedHydration.promise;
+ return Promise.resolve(jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Recent current chat' },
+ }));
+ }
+ if (requestUrl === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options.method) {
+ messagesReads += 1;
+ if (stage === 'messages') return delayedHydration.promise;
+ return Promise.resolve(jsonResponse(initialMessages([], false)));
+ }
+ if (requestUrl === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ research_id: researchId,
+ }));
+ }
+ throw new Error(`Unexpected fetch: ${requestUrl}`);
+ });
+
+ await import('@js/components/chat.js');
+ const delayedUrl = stage === 'metadata'
+ ? `/api/chat/sessions/${SESSION_ID}`
+ : `/api/chat/sessions/${SESSION_ID}/messages`;
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ delayedUrl,
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ });
+
+ const input = document.getElementById('chat-input');
+ input.value = `Send while recent ${stage} is still loading`;
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ researchId,
+ expect.any(Function),
+ );
+ });
+ expect(document.getElementById('chat-welcome').style.display).toBe('none');
+
+ if (rejects) {
+ delayedHydration.reject(new Error('stale hydration failed'));
+ } else if (stage === 'metadata') {
+ delayedHydration.resolve(jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Stale delayed recent title' },
+ }));
+ } else {
+ delayedHydration.resolve(jsonResponse(initialMessages([], false)));
+ }
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+
+ expect(document.getElementById('chat-welcome').style.display).toBe('none');
+ expect(document.getElementById('chat-title').textContent).toBe(
+ stage === 'metadata' ? 'User-owned current title' : 'Recent current chat',
+ );
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain(`Send while recent ${stage} is still loading`);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(researchId);
+ if (stage === 'metadata') expect(messagesReads).toBe(0);
+
+ window.chatComponent.startNewChat();
+ history.replaceState({}, '', '/');
+});
+
+it('keeps New Chat authoritative over a deferred first-session creation', async () => {
+ const creation = deferred();
+ await loadChat({
+ sessionMeta: false,
+ fetchRoute: (url, options) => {
+ if (url === '/api/chat/sessions?limit=1') {
+ return jsonResponse({ success: true, sessions: [] });
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return creation.promise;
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'Question whose session will be abandoned';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ window.chatComponent.startNewChat();
+ creation.resolve(jsonResponse({
+ success: true,
+ session_id: 'abandoned-created-session',
+ session: { title: 'Must not reclaim the page' },
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.location.pathname).toBe('/chat/');
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(document.getElementById('chat-welcome').style.display).toBe('flex');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Question whose session will be abandoned');
+ expect(globalThis.fetch).not.toHaveBeenCalledWith(
+ '/api/chat/sessions/abandoned-created-session/messages',
+ expect.anything(),
+ );
+ expect(globalThis.fetch).not.toHaveBeenCalledWith(
+ '/api/chat/sessions/abandoned-created-session/generate-title',
+ expect.anything(),
+ );
+});
+
+it('does not let a deferred old-session send claim the replacement research', async () => {
+ const oldSend = deferred();
+ const replacementSessionId = 'replacement-send-session';
+ const replacementResearchId = 'replacement-send-research';
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ return oldSend.promise;
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'Replacement send chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return jsonResponse({ success: true, title: 'Replacement title' });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ });
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'Slow question in the old session';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/messages`,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ window.chatComponent.startNewChat();
+ input.value = 'Question owned by the replacement session';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+
+ oldSend.resolve(jsonResponse({
+ success: true,
+ research_id: 'abandoned-send-research',
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.socket.subscribeToResearch).not.toHaveBeenCalledWith(
+ 'abandoned-send-research',
+ expect.any(Function),
+ );
+ expect(window.location.pathname).toBe(`/chat/${replacementSessionId}`);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Slow question in the old session');
+});
+
+it('surfaces FastAPI detail when sending is rejected', async () => {
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({ detail: 'Too many concurrent researches' }, 429);
+ }
+ return null;
+ },
+ });
+ const input = document.getElementById('chat-input');
+ input.value = 'Start another run';
+ input.dispatchEvent(new Event('input'));
+
+ document.getElementById('send-btn').click();
+
+ await vi.waitFor(() => {
+ const messages = document.querySelectorAll(
+ '.ldr-chat-message-assistant:not(.ldr-chat-message-thinking)',
+ );
+ expect(messages[messages.length - 1].textContent)
+ .toContain('Too many concurrent researches');
+ });
+ expect(document.getElementById('send-btn').disabled).toBe(false);
+});
+
+it('stops the active research and preserves one partial streamed answer', async () => {
+ const priorMessage = {
+ id: 'question-1',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Explain the migration',
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ const { rawHandlers, getProgressCallback } = await loadChat({
+ messages: [priorMessage],
+ inProgress: 'active-3299',
+ });
+ const chunkHandler = rawHandlers['response_chunk_active-3299'];
+ expect(chunkHandler).toBeTypeOf('function');
+ chunkHandler({
+ chunk: 'Partial but useful answer',
+ is_streaming: true,
+ is_final: false,
+ });
+ await vi.waitFor(() => {
+ expect(document.querySelector('.ldr-chat-message-streaming'))
+ .not.toBeNull();
+ });
+
+ document.getElementById('chat-stop-research-btn').click();
+
+ await vi.waitFor(() => {
+ expect(window.api.terminateResearch)
+ .toHaveBeenCalledWith('active-3299');
+ });
+ expect(document.getElementById('chat-stop-research-btn').style.display)
+ .toBe('none');
+ getProgressCallback()({
+ status: 'suspended',
+ });
+ getProgressCallback()({
+ status: 'suspended',
+ });
+ // A cleanup completion can race the suspension emitted by Stop. The first
+ // terminal owner must remain authoritative and must not fetch/render a
+ // completed answer over the preserved partial bubble.
+ getProgressCallback()({ status: 'completed', progress: 100 });
+
+ const footer = document.querySelector('.ldr-chat-stopped-footer');
+ expect(footer).not.toBeNull();
+ const streamed = footer.closest('.ldr-chat-message-assistant');
+ expect(streamed.textContent).toContain('Partial but useful answer');
+ expect(streamed.querySelectorAll('.ldr-chat-stopped-footer'))
+ .toHaveLength(1);
+ expect(streamed.textContent).toContain('Stopped by user');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('none');
+ expect(window.socket.unsubscribeFromResearch)
+ .toHaveBeenCalledWith('active-3299');
+});
+
+it('restores the stop control when termination fails', async () => {
+ const { getProgressCallback } = await loadChat({
+ messages: [{
+ id: 'question-2',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Keep researching',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: 'active-failure',
+ });
+ window.api.terminateResearch.mockRejectedValue(new Error('worker unavailable'));
+ const stop = document.getElementById('chat-stop-research-btn');
+
+ stop.click();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-current-task').textContent)
+ .toBe('Failed to stop — please try again.');
+ });
+ expect(stop.disabled).toBe(false);
+ expect(stop.textContent).toContain('Stop');
+ expect(getProgressCallback()).toBeTypeOf('function');
+});
+
+it('replaces streamed output with the persisted formatted answer on completion', async () => {
+ let messageReads = 0;
+ const researchId = 'complete-3299';
+ const { rawHandlers, getProgressCallback } = await loadChat({
+ messages: [{
+ id: 'question-complete',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Give me the final report',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ messageReads += 1;
+ if (messageReads > 1) {
+ return jsonResponse(initialMessages([{
+ id: 'persisted-step',
+ role: 'assistant',
+ message_type: 'step',
+ research_id: researchId,
+ content: 'Starting research process',
+ created_at: '2026-08-31T12:01:00Z',
+ }, {
+ id: 'persisted-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: researchId,
+ content: '**Formatted report** with citations',
+ created_at: '2026-08-31T12:02:00Z',
+ }], false));
+ }
+ }
+ return null;
+ },
+ });
+ const chunkHandler = rawHandlers[`response_chunk_${researchId}`];
+ chunkHandler({
+ chunk: 'Raw streamed answer',
+ is_streaming: true,
+ is_final: false,
+ });
+ chunkHandler({ chunk: '', is_streaming: true, is_final: true });
+ expect(document.querySelector('.ldr-chat-message-assistant').textContent)
+ .toContain('Raw streamed answer');
+
+ getProgressCallback()({
+ research_id: researchId,
+ status: 'completed',
+ progress: 100,
+ });
+ // Competing terminal packets can be queued on the socket at the same time.
+ // Once completion owns the attempt, neither error nor suspension may tear
+ // down the formatted-answer swap in progress.
+ getProgressCallback()({ status: 'failed', error: 'late failure' });
+ getProgressCallback()({ status: 'suspended' });
+
+ await vi.waitFor(() => {
+ const answer = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ );
+ expect(answer.textContent).toContain('**Formatted report** with citations');
+ expect(answer.textContent).not.toContain('Starting research process');
+ expect(answer.querySelector('a').getAttribute('href'))
+ .toBe(`/results/${researchId}`);
+ });
+ expect(window.socket.unsubscribeFromResearch).toHaveBeenCalledWith(researchId);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('none');
+ expect(document.getElementById('edit-title-btn').style.display)
+ .toBe('inline-block');
+});
+
+it('recovers the persisted answer when completion arrives without any chunks', async () => {
+ const researchId = 'chunkless-completion-3299';
+ let messageReads = 0;
+ const { getProgressCallback } = await loadChat({
+ messages: [{
+ id: 'chunkless-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Recover this answer from storage',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ messageReads += 1;
+ if (messageReads > 1) {
+ return jsonResponse(initialMessages([{
+ id: 'chunkless-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: researchId,
+ content: 'DB-authoritative answer after the chunk channel was lost',
+ created_at: '2026-08-31T12:01:00Z',
+ }], false));
+ }
+ }
+ return null;
+ },
+ });
+
+ expect(document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ )).toBeNull();
+ getProgressCallback()({
+ research_id: researchId,
+ status: 'completed',
+ progress: 100,
+ });
+
+ await vi.waitFor(() => {
+ const answer = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ );
+ expect(answer?.textContent).toContain(
+ 'DB-authoritative answer after the chunk channel was lost',
+ );
+ expect(answer?.querySelector('a')?.getAttribute('href'))
+ .toBe(`/results/${researchId}`);
+ });
+ expect(window.socket.unsubscribeFromResearch).toHaveBeenCalledWith(researchId);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('none');
+});
+
+it('preserves partial streamed content while reconnecting the same research', async () => {
+ const researchId = 'reconnect-stream-3299';
+ const { rawHandlers } = await loadChat({
+ messages: [{
+ id: 'reconnect-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Keep the partial answer on reconnect',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ });
+ const eventName = `response_chunk_${researchId}`;
+ const firstProgressConsumer = window.socket.subscribeToResearch.mock.calls
+ .find(([id]) => id === researchId)[1];
+
+ rawHandlers[eventName]({
+ chunk: 'Content received before reconnect',
+ is_streaming: true,
+ is_final: false,
+ });
+ rawHandlers.connect();
+
+ const researchSubscriptions = window.socket.subscribeToResearch.mock.calls
+ .filter(([id]) => id === researchId);
+ expect(researchSubscriptions).toHaveLength(2);
+ expect(researchSubscriptions[1][1]).toBe(firstProgressConsumer);
+
+ rawHandlers[eventName]({
+ chunk: '',
+ is_streaming: true,
+ is_final: true,
+ });
+ const answer = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ );
+ expect(answer?.textContent).toContain('Content received before reconnect');
+ expect(answer?.classList).not.toContain('ldr-chat-message-streaming');
+
+ window.chatComponent.startNewChat();
+});
+
+it('keeps an anomalously short final chunk from replacing streamed content', async () => {
+ const researchId = 'short-final-3299';
+ const { rawHandlers } = await loadChat({
+ messages: [{
+ id: 'short-final-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Keep the complete streamed content',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ });
+ const chunk = rawHandlers[`response_chunk_${researchId}`];
+ const completeStream = 'This is the complete answer accumulated before final delivery.';
+
+ chunk({ chunk: completeStream, is_streaming: true, is_final: false });
+ chunk({ chunk: 'x', is_streaming: true, is_final: true });
+
+ const answer = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ );
+ expect(answer?.textContent).toContain(completeStream);
+ expect(answer?.textContent).not.toBe('x');
+
+ window.chatComponent.startNewChat();
+});
+
+it.each([128, 180, 256])('does not double-count a %i KiB final answer snapshot', async (sizeKiB) => {
+ const researchId = 'final-snapshot-3299';
+ const { rawHandlers } = await loadChat({
+ inProgress: researchId,
+ messages: [{ id: 'snapshot-question', role: 'user', content: 'Keep the complete answer' }],
+ });
+ const chunk = rawHandlers[`response_chunk_${researchId}`];
+ const answer = 'a'.repeat(sizeKiB * 1024 - 7) + 'THE END';
+
+ chunk({ chunk: answer, is_streaming: true, is_final: false });
+ chunk({ chunk: answer, is_streaming: true, is_final: true });
+
+ const text = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`
+ + ' .ldr-chat-message-text',
+ )?.textContent;
+ expect(text).toBe(answer);
+ window.chatComponent.startNewChat();
+});
+
+it('bounds an oversized final snapshot even without incremental delivery', async () => {
+ const researchId = 'oversized-final-3299';
+ const { rawHandlers } = await loadChat({
+ inProgress: researchId,
+ messages: [{ id: 'oversized-question', role: 'user', content: 'Bound the final answer' }],
+ });
+ const limit = 256 * 1024;
+ rawHandlers[`response_chunk_${researchId}`]({
+ chunk: 'x'.repeat(limit + 4096),
+ is_streaming: true,
+ is_final: true,
+ });
+
+ expect(document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`
+ + ' .ldr-chat-message-text',
+ )?.textContent).toBe(
+ 'x'.repeat(limit) + '\n\n_(Response truncated — exceeded display limit.)_',
+ );
+ window.chatComponent.startNewChat();
+});
+
+it('bounds one oversized stream chunk and shows one truncation notice', async () => {
+ const researchId = 'bounded-stream-3299';
+ const { rawHandlers } = await loadChat({
+ messages: [{
+ id: 'bounded-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Bound a runaway provider response',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ });
+ const chunk = rawHandlers[`response_chunk_${researchId}`];
+ const displayLimit = 256 * 1024;
+ const notice = '_(Response truncated — exceeded display limit.)_';
+
+ chunk({
+ chunk: 'x'.repeat(displayLimit + 4096),
+ is_streaming: true,
+ is_final: false,
+ });
+ chunk({
+ chunk: 'This later chunk must be ignored',
+ is_streaming: true,
+ is_final: true,
+ });
+
+ const text = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`
+ + ' .ldr-chat-message-text',
+ )?.textContent;
+ expect(text.startsWith('x'.repeat(64))).toBe(true);
+ expect(text).not.toContain('This later chunk must be ignored');
+ expect(text.split(notice)).toHaveLength(2);
+ expect(text.length).toBe(displayLimit + notice.length + 2);
+
+ window.chatComponent.startNewChat();
+});
+
+it('starts a clean retryable chat and retires the prior research ownership', async () => {
+ const researchId = 'abandoned-3299';
+ const { rawSocket } = await loadChat({
+ messages: [{
+ id: 'prior-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: researchId,
+ content: 'Old session answer',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ });
+ history.replaceState({}, '', `/chat/${SESSION_ID}`);
+ const input = document.getElementById('chat-input');
+ input.value = '';
+ const focusSpy = vi.spyOn(input, 'focus');
+
+ window.chatComponent.startNewChat();
+
+ expect(window.location.pathname).toBe('/chat/');
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(document.querySelectorAll('#chat-messages > *')).toHaveLength(0);
+ expect(document.getElementById('chat-welcome').style.display).toBe('flex');
+ expect(document.getElementById('send-btn').disabled).toBe(true);
+ expect(document.getElementById('edit-title-btn').style.display).toBe('none');
+ expect(document.getElementById('export-chat-btn').style.display).toBe('none');
+ expect(focusSpy).toHaveBeenCalledOnce();
+ expect(window.socket.unsubscribeFromResearch).toHaveBeenCalledWith(researchId);
+ expect(rawSocket.off).toHaveBeenCalledWith(`response_chunk_${researchId}`);
+ history.replaceState({}, '', '/');
+});
+
+it('does not let an older completion reclaim controls after starting a new chat', async () => {
+ const researchId = 'late-completion-3299';
+ let messageReads = 0;
+ let finishFormattedFetch;
+ const { rawHandlers, getProgressCallback } = await loadChat({
+ messages: [{
+ id: 'late-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Old session question',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: researchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ messageReads += 1;
+ if (messageReads > 1) {
+ return new Promise(resolve => {
+ finishFormattedFetch = resolve;
+ });
+ }
+ }
+ return null;
+ },
+ });
+ const chunkHandler = rawHandlers[`response_chunk_${researchId}`];
+ chunkHandler({
+ chunk: 'Old streamed answer',
+ is_streaming: true,
+ is_final: true,
+ });
+ getProgressCallback()({
+ research_id: researchId,
+ status: 'completed',
+ progress: 100,
+ });
+ await vi.waitFor(() => expect(finishFormattedFetch).toBeTypeOf('function'));
+
+ window.chatComponent.startNewChat();
+ finishFormattedFetch(jsonResponse(initialMessages([{
+ id: 'late-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: researchId,
+ content: 'Late persisted answer',
+ }], false)));
+ await vi.waitFor(() => {
+ expect(window.socket.unsubscribeFromResearch)
+ .toHaveBeenCalledTimes(2);
+ });
+
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(document.querySelectorAll('#chat-messages > *')).toHaveLength(0);
+ expect(document.getElementById('edit-title-btn').style.display).toBe('none');
+ expect(document.getElementById('export-chat-btn').style.display).toBe('none');
+});
+
+it('refreshes the owned session and reloads its persisted answer when the bubble is missing', async () => {
+ const researchId = 'owned-final-refresh-3299';
+ const persistedAnswer = [{
+ id: 'owned-final-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: researchId,
+ content: 'Persisted answer restored by the final refresh',
+ created_at: '2026-08-31T12:00:00Z',
+ }];
+ const finalSessionRefresh = deferred();
+ let sessionReads = 0;
+ let messageReads = 0;
+ const { rawHandlers, getProgressCallback } = await loadChat({
+ messages: persistedAnswer,
+ inProgress: researchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}` && !options?.method) {
+ sessionReads += 1;
+ if (sessionReads === 2) return finalSessionRefresh.promise;
+ if (sessionReads === 3) {
+ return jsonResponse({
+ success: true,
+ session: {
+ id: SESSION_ID,
+ title: 'Refreshed current chat',
+ },
+ });
+ }
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ messageReads += 1;
+ return jsonResponse(initialMessages(
+ persistedAnswer,
+ false,
+ messageReads === 1 ? researchId : null,
+ ));
+ }
+ return null;
+ },
+ });
+
+ rawHandlers[`response_chunk_${researchId}`]({
+ chunk: 'Streamed answer before persistence refresh',
+ is_streaming: true,
+ is_final: true,
+ });
+ getProgressCallback()({
+ research_id: researchId,
+ status: 'completed',
+ progress: 100,
+ });
+ await vi.waitFor(() => expect(sessionReads).toBe(2));
+
+ document.querySelectorAll(
+ `.ldr-chat-message-assistant[data-research-id="${researchId}"]`,
+ ).forEach(element => element.remove());
+ finalSessionRefresh.resolve(jsonResponse({
+ success: true,
+ session: {
+ id: SESSION_ID,
+ title: 'Refreshed current chat',
+ },
+ }));
+
+ await vi.waitFor(() => {
+ expect(sessionReads).toBe(3);
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Persisted answer restored by the final refresh');
+ });
+ expect(messageReads).toBe(3);
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Refreshed current chat');
+});
+
+it.each([
+ { label: 'ownership changes before response headers settle', bodyStarted: false },
+ { label: 'ownership changes after response body parsing starts', bodyStarted: true },
+])('does not let a stale final refresh rename or reload a replacement session when $label', async ({
+ bodyStarted,
+}) => {
+ const oldResearchId = 'stale-final-refresh-3299';
+ const replacementSessionId = 'replacement-final-refresh-session';
+ const replacementResearchId = 'replacement-final-refresh-research';
+ const persistedOldAnswer = [{
+ id: 'stale-final-answer',
+ role: 'assistant',
+ message_type: 'chat',
+ research_id: oldResearchId,
+ content: 'Persisted answer from the abandoned chat',
+ created_at: '2026-08-31T12:00:00Z',
+ }];
+ const finalSessionRefresh = deferred();
+ const finalSessionBody = deferred();
+ const staleBody = vi.fn(() => finalSessionBody.promise);
+ const stalePayload = {
+ success: true,
+ session: { id: SESSION_ID, title: 'Stale completed chat' },
+ };
+ let oldSessionReads = 0;
+ let oldMessageReads = 0;
+ let replacementSessionReloads = 0;
+ const { rawHandlers, getProgressCallback } = await loadChat({
+ messages: persistedOldAnswer,
+ inProgress: oldResearchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}` && !options?.method) {
+ oldSessionReads += 1;
+ if (oldSessionReads === 2) return finalSessionRefresh.promise;
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ oldMessageReads += 1;
+ return jsonResponse(initialMessages(
+ persistedOldAnswer,
+ false,
+ oldMessageReads === 1 ? oldResearchId : null,
+ ));
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'Replacement current chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return jsonResponse({ success: false });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}`
+ && !options?.method) {
+ replacementSessionReloads += 1;
+ return jsonResponse({
+ success: true,
+ session: {
+ id: replacementSessionId,
+ title: 'Replacement reloaded after stale completion',
+ },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && !options?.method) {
+ return jsonResponse(initialMessages([], false, replacementResearchId));
+ }
+ return null;
+ },
+ });
+ const oldProgressCallback = getProgressCallback();
+
+ rawHandlers[`response_chunk_${oldResearchId}`]({
+ chunk: 'Final answer from the old chat',
+ is_streaming: true,
+ is_final: true,
+ });
+ oldProgressCallback({
+ research_id: oldResearchId,
+ status: 'completed',
+ progress: 100,
+ });
+ await vi.waitFor(() => expect(oldSessionReads).toBe(2));
+
+ if (bodyStarted) {
+ finalSessionRefresh.resolve({ ok: true, status: 200, json: staleBody });
+ await vi.waitFor(() => expect(staleBody).toHaveBeenCalledOnce());
+ }
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'Question owned by the replacement chat';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Replacement current chat');
+
+ if (bodyStarted) {
+ finalSessionBody.resolve(stalePayload);
+ } else {
+ finalSessionRefresh.resolve({ ok: true, status: 200, json: staleBody });
+ }
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(staleBody).toHaveBeenCalledTimes(bodyStarted ? 1 : 0);
+ expect(replacementSessionReloads).toBe(0);
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Replacement current chat');
+ expect(window.location.pathname).toBe(`/chat/${replacementSessionId}`);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(replacementResearchId);
+
+ window.chatComponent.startNewChat();
+});
+
+it('ignores an already-queued response chunk after a newer research owns the chat', async () => {
+ const oldResearchId = 'old-stream-3299';
+ const newResearchId = 'new-stream-3299';
+ const { rawHandlers } = await loadChat({
+ messages: [{
+ id: 'old-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Old session question',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: oldResearchId,
+ sessionMeta: true,
+ fetchRoute: (url, options) => {
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: 'replacement-session',
+ session: { title: 'Replacement session' },
+ });
+ }
+ if (url === '/api/chat/sessions/replacement-session/generate-title') {
+ return jsonResponse({ success: true, title: 'Replacement title' });
+ }
+ if (url === '/api/chat/sessions/replacement-session/messages'
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: newResearchId,
+ });
+ }
+ return null;
+ },
+ });
+ const queuedOldChunk = rawHandlers[`response_chunk_${oldResearchId}`];
+ expect(queuedOldChunk).toBeTypeOf('function');
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'Replacement question';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ newResearchId,
+ expect.any(Function),
+ );
+ });
+
+ // socket.off() has already run, but Socket.IO/browser task ordering can
+ // leave a callback that was queued before the unsubscribe runnable.
+ queuedOldChunk({
+ chunk: 'Stale answer from the abandoned research',
+ is_streaming: true,
+ is_final: false,
+ });
+ rawHandlers[`response_chunk_${newResearchId}`]({
+ chunk: 'Fresh answer for the replacement research',
+ is_streaming: true,
+ is_final: true,
+ });
+
+ const streamed = document.querySelector(
+ `.ldr-chat-message-assistant[data-research-id="${newResearchId}"]`,
+ );
+ expect(streamed).not.toBeNull();
+ expect(streamed.textContent).toContain(
+ 'Fresh answer for the replacement research',
+ );
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Stale answer from the abandoned research');
+
+ window.chatComponent.startNewChat();
+});
+
+it('ignores an in-flight terminal poll after a newer research owns the chat', async () => {
+ vi.useFakeTimers();
+ const oldResearchId = 'old-poll-3299';
+ const newResearchId = 'new-poll-3299';
+ let resolveOldStatus;
+ const oldStatus = new Promise(resolve => {
+ resolveOldStatus = resolve;
+ });
+ await loadChat({
+ messages: [{
+ id: 'polled-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Old polled question',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: oldResearchId,
+ fetchRoute: (url, options) => {
+ if (url === `/api/research/${oldResearchId}/status`) {
+ return oldStatus;
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: 'poll-replacement-session',
+ session: { title: 'Poll replacement' },
+ });
+ }
+ if (url === '/api/chat/sessions/poll-replacement-session/generate-title') {
+ return jsonResponse({ success: true, title: 'Poll replacement' });
+ }
+ if (url === '/api/chat/sessions/poll-replacement-session/messages'
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: newResearchId,
+ });
+ }
+ return null;
+ },
+ });
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(resolveOldStatus).toBeTypeOf('function');
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'New research while the old poll is pending';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ newResearchId,
+ expect.any(Function),
+ );
+ });
+
+ resolveOldStatus(jsonResponse({
+ status: 'failed',
+ metadata: {
+ error_info: { message: 'Failure from the abandoned research' },
+ },
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Failure from the abandoned research');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(document.getElementById('chat-stop-research-btn').style.display)
+ .toBe('inline-flex');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(newResearchId);
+
+ window.chatComponent.startNewChat();
+});
+
+it('does not let a deferred stop response mutate a newer research', async () => {
+ const oldResearchId = 'old-stop-3299';
+ const newResearchId = 'new-stop-3299';
+ let resolveStop;
+ await loadChat({
+ messages: [{
+ id: 'old-stop-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Stop the old research',
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ inProgress: oldResearchId,
+ fetchRoute: (url, options) => {
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: 'stop-replacement-session',
+ session: { title: 'Stop replacement' },
+ });
+ }
+ if (url === '/api/chat/sessions/stop-replacement-session/generate-title') {
+ return jsonResponse({ success: true, title: 'Stop replacement' });
+ }
+ if (url === '/api/chat/sessions/stop-replacement-session/messages'
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: newResearchId,
+ });
+ }
+ return null;
+ },
+ });
+ window.api.terminateResearch.mockImplementationOnce(() => (
+ new Promise(resolve => {
+ resolveStop = resolve;
+ })
+ ));
+
+ document.getElementById('chat-stop-research-btn').click();
+ await vi.waitFor(() => expect(resolveStop).toBeTypeOf('function'));
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'Research owned by the replacement chat';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ newResearchId,
+ expect.any(Function),
+ );
+ });
+ expect(document.getElementById('chat-current-task').textContent)
+ .toBe('Starting research...');
+
+ resolveStop({ success: true });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(document.getElementById('chat-current-task').textContent)
+ .toBe('Starting research...');
+ expect(document.getElementById('chat-stop-research-btn').style.display)
+ .toBe('inline-flex');
+ expect(document.getElementById('chat-stop-research-btn').disabled)
+ .toBe(false);
+
+ window.chatComponent.startNewChat();
+});
+
+it('keeps New Chat authoritative over a slow initial session restore', async () => {
+ buildChatDom();
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-chat'),
+ terminateResearch: vi.fn(),
+ };
+ window.ui = { renderMarkdown: vi.fn(value => value) };
+ const rawSocket = { on: vi.fn(), off: vi.fn() };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ unsubscribeFromResearch: vi.fn(),
+ getSocketInstance: vi.fn(() => rawSocket),
+ };
+ let resolveSession;
+ const slowSession = new Promise(resolve => {
+ resolveSession = resolve;
+ });
+ globalThis.fetch = vi.fn((url) => {
+ if (String(url) === `/api/chat/sessions/${SESSION_ID}`) {
+ return slowSession;
+ }
+ if (String(url) === `/api/chat/sessions/${SESSION_ID}/messages`) {
+ return Promise.resolve(jsonResponse(initialMessages([{
+ id: 'stale-restored-message',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Message from the abandoned restore',
+ created_at: '2026-08-31T12:00:00Z',
+ }], false, 'stale-restored-research')));
+ }
+ throw new Error(`Unexpected fetch: ${String(url)}`);
+ });
+
+ await import('@js/components/chat.js');
+ await vi.waitFor(() => expect(resolveSession).toBeTypeOf('function'));
+
+ // Listeners are intentionally bound before the awaited restore, so this
+ // is a real interaction users can perform on a slow connection.
+ document.getElementById('new-chat-btn').click();
+ resolveSession(jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Abandoned session' },
+ }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-input').dataset.initComplete)
+ .toBe('true');
+ });
+
+ expect(window.location.pathname).toBe('/chat/');
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(document.getElementById('chat-welcome').style.display).toBe('flex');
+ expect(document.getElementById('chat-messages').textContent)
+ .not.toContain('Message from the abandoned restore');
+ expect(window.socket.subscribeToResearch)
+ .not.toHaveBeenCalledWith('stale-restored-research', expect.any(Function));
+});
+
+it('does not let a deferred same-session delete reload over a newer Send', async () => {
+ const deletedResearchId = 'delete-before-new-send';
+ const newResearchId = 'same-session-new-research';
+ const deletion = deferred();
+ let sessionReads = 0;
+ await loadChat({
+ messages: [{
+ id: 'answer-awaiting-delete',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Prior answer awaiting deletion',
+ research_id: deletedResearchId,
+ created_at: '2026-08-31T12:00:00Z',
+ }],
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`
+ && !options?.method) {
+ sessionReads += 1;
+ return jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Same-session delete chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/attempts/${deletedResearchId}`
+ && options?.method === 'DELETE') {
+ return deletion.promise;
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: newResearchId,
+ });
+ }
+ return null;
+ },
+ });
+
+ document.querySelector('[data-action="delete"]').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/attempts/${deletedResearchId}`,
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+
+ const input = document.getElementById('chat-input');
+ input.value = 'New turn owns this same session';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ newResearchId,
+ expect.any(Function),
+ );
+ });
+
+ deletion.resolve(jsonResponse({ success: true }));
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(sessionReads).toBe(1);
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('New turn owns this same session');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(newResearchId);
+
+ window.chatComponent.startNewChat();
+});
+
+it('keeps a newer same-session Retry authoritative over a deferred delete', async () => {
+ const oldResearchId = 'delete-before-retry';
+ const replacementResearchId = 'retry-after-delete-research';
+ const deletion = deferred();
+ const retry = deferred();
+ let retrySettled = false;
+ let sessionReads = 0;
+ let messageReads = 0;
+ const priorAnswer = {
+ id: 'answer-before-delete-retry-race',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Prior answer with competing actions',
+ research_id: oldResearchId,
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ await loadChat({
+ messages: [priorAnswer],
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`
+ && !options?.method) {
+ sessionReads += 1;
+ return jsonResponse({
+ success: true,
+ session: { id: SESSION_ID, title: 'Attempt ownership chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ messageReads += 1;
+ if (retrySettled) {
+ return jsonResponse(initialMessages([{
+ id: 'replacement-retry-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Retried question owns the session',
+ research_id: replacementResearchId,
+ created_at: '2026-08-31T12:01:00Z',
+ }], false, replacementResearchId));
+ }
+ return jsonResponse(initialMessages([priorAnswer], false));
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}`
+ && options?.method === 'DELETE') {
+ return deletion.promise;
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}/retry`
+ && options?.method === 'POST') {
+ return retry.promise;
+ }
+ return null;
+ },
+ });
+
+ document.querySelector('[data-action="delete"]').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}`,
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ });
+ document.querySelector('[data-action="retry"]').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}/retry`,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+
+ deletion.resolve(jsonResponse({ success: true }));
+ await new Promise(resolve => setTimeout(resolve, 0));
+ expect(sessionReads).toBe(1);
+ expect(messageReads).toBe(1);
+
+ retrySettled = true;
+ retry.resolve(jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ }));
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+ expect(sessionReads).toBe(2);
+ expect(messageReads).toBe(2);
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Retried question owns the session');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+
+ window.chatComponent.startNewChat();
+});
+
+it('blocks Delete while a same-session Retry owns processing', async () => {
+ const oldResearchId = 'retry-before-delete';
+ const replacementResearchId = 'retry-blocks-delete-research';
+ const retry = deferred();
+ let retrySettled = false;
+ let deleteCalls = 0;
+ const priorAnswer = {
+ id: 'answer-before-retry-delete-race',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Prior answer being retried',
+ research_id: oldResearchId,
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ await loadChat({
+ messages: [priorAnswer],
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}/retry`
+ && options?.method === 'POST') {
+ return retry.promise;
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}`
+ && options?.method === 'DELETE') {
+ deleteCalls += 1;
+ return jsonResponse({ success: true });
+ }
+ if (retrySettled
+ && url === `/api/chat/sessions/${SESSION_ID}/messages`
+ && !options?.method) {
+ return jsonResponse(initialMessages([{
+ id: 'question-after-blocked-delete',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Retry remains authoritative',
+ research_id: replacementResearchId,
+ created_at: '2026-08-31T12:01:00Z',
+ }], false, replacementResearchId));
+ }
+ return null;
+ },
+ });
+
+ document.querySelector('[data-action="retry"]').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/attempts/${oldResearchId}/retry`,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+ document.querySelector('[data-action="delete"]').click();
+ await Promise.resolve();
+
+ expect(deleteCalls).toBe(0);
+ expect(window.confirm).toHaveBeenCalledOnce();
+
+ retrySettled = true;
+ retry.resolve(jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ }));
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Retry remains authoritative');
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+
+ window.chatComponent.startNewChat();
+});
+
+it.each([
+ {
+ label: 'delete',
+ action: 'delete',
+ method: 'DELETE',
+ suffix: '/attempts/abandoned-attempt',
+ response: { success: true },
+ },
+ {
+ label: 'retry',
+ action: 'retry',
+ method: 'POST',
+ suffix: '/attempts/abandoned-attempt/retry',
+ response: {
+ success: true,
+ research_id: 'abandoned-retry-replacement',
+ },
+ },
+])('ignores a deferred old-session $label after a replacement send', async ({
+ action,
+ method,
+ suffix,
+ response,
+}) => {
+ const attemptMutation = deferred();
+ const replacementSessionId = `replacement-${action}-session`;
+ const replacementResearchId = `replacement-${action}-research`;
+ const prior = {
+ id: `assistant-${action}-race`,
+ role: 'assistant',
+ message_type: 'chat',
+ content: `Prior answer awaiting ${action}`,
+ research_id: 'abandoned-attempt',
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ await loadChat({
+ messages: [prior],
+ fetchRoute: (url, options) => {
+ if (url.endsWith(suffix) && options?.method === method) {
+ return attemptMutation.promise;
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: `Replacement ${action} chat` },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return jsonResponse({
+ success: true,
+ title: `Generated replacement ${action}`,
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ });
+ }
+ return null;
+ },
+ });
+
+ document.querySelector(`[data-action="${action}"]`).click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ expect.stringContaining(suffix),
+ expect.objectContaining({ method }),
+ );
+ });
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = `Question owned after stale ${action}`;
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+
+ attemptMutation.resolve(jsonResponse(response));
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ const replacementHydrations = globalThis.fetch.mock.calls.filter(
+ ([url, options]) => (
+ url === `/api/chat/sessions/${replacementSessionId}` &&
+ !options?.method
+ ),
+ );
+ expect(replacementHydrations).toHaveLength(0);
+ expect(window.socket.unsubscribeFromResearch)
+ .not.toHaveBeenCalledWith(replacementResearchId);
+ expect(window.socket.subscribeToResearch).not.toHaveBeenCalledWith(
+ 'abandoned-retry-replacement',
+ expect.any(Function),
+ );
+ expect(window.location.pathname).toBe(`/chat/${replacementSessionId}`);
+ expect(document.getElementById('chat-progress-wrapper').style.display)
+ .toBe('block');
+});
+
+it('deletes an encoded attempt without sending a JSON body and reloads', async () => {
+ let deleted = false;
+ const attempt = {
+ id: 'assistant-1',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Prior answer',
+ research_id: 'research /?#',
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ await loadChat({
+ messages: [attempt],
+ fetchRoute: (url, options) => {
+ if (url.endsWith('/attempts/research%20%2F%3F%23')
+ && options?.method === 'DELETE') {
+ deleted = true;
+ return jsonResponse({ success: true });
+ }
+ if (deleted && url === `/api/chat/sessions/${SESSION_ID}/messages`) {
+ return jsonResponse(initialMessages([], false));
+ }
+ return null;
+ },
+ });
+
+ document.querySelector('[data-action="delete"]').click();
+
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions/session-1/attempts/research%20%2F%3F%23',
+ {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ },
+ );
+ });
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-welcome').style.display)
+ .toBe('flex');
+ });
+});
+
+it('retries an encoded attempt and adopts the backend-owned replacement', async () => {
+ let retried = false;
+ const prior = {
+ id: 'assistant-retry',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Prior failed answer',
+ research_id: 'old /?#',
+ created_at: '2026-08-31T12:00:00Z',
+ };
+ await loadChat({
+ messages: [prior],
+ fetchRoute: (url, options) => {
+ if (url.endsWith('/attempts/old%20%2F%3F%23/retry')
+ && options?.method === 'POST') {
+ retried = true;
+ return jsonResponse({
+ success: true,
+ research_id: 'replacement-1',
+ });
+ }
+ if (retried && url === `/api/chat/sessions/${SESSION_ID}/messages`) {
+ return jsonResponse(initialMessages([{
+ id: 'replacement-question',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Retry this question',
+ research_id: 'replacement-1',
+ created_at: '2026-08-31T12:01:00Z',
+ }], false, 'replacement-1'));
+ }
+ return null;
+ },
+ });
+
+ document.querySelector('[data-action="retry"]').click();
+
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ 'replacement-1',
+ expect.any(Function),
+ );
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions/session-1/attempts/old%20%2F%3F%23/retry',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ body: '{}',
+ },
+ );
+ expect(document.getElementById('chat-messages').textContent)
+ .toContain('Retry this question');
+});
+
+it('persists a manually edited title with CSRF and updates document state', async () => {
+ window.prompt = vi.fn(() => 'Renamed migration chat');
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`
+ && options?.method === 'PATCH') {
+ return jsonResponse({ success: true });
+ }
+ return null;
+ },
+ });
+
+ document.getElementById('edit-title-btn').click();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('chat-title').textContent)
+ .toBe('Renamed migration chat');
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}`,
+ {
+ method: 'PATCH',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-chat',
+ },
+ body: JSON.stringify({ title: 'Renamed migration chat' }),
+ },
+ );
+ expect(document.title).toBe('Renamed migration chat - Chat Research');
+ delete window.prompt;
+});
+
+it.each([
+ { label: 'before response headers settle', bodyStarted: false },
+ { label: 'after response body parsing starts', bodyStarted: true },
+])('does not let a deferred title edit rename a replacement chat $label', async ({
+ bodyStarted,
+}) => {
+ const titleUpdate = deferred();
+ const deferredTitleBody = deferred();
+ const titleBody = vi.fn(() => deferredTitleBody.promise);
+ window.prompt = vi.fn(() => 'Renamed abandoned chat');
+ await loadChat({
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}`
+ && options?.method === 'PATCH') {
+ return titleUpdate.promise;
+ }
+ return null;
+ },
+ });
+
+ document.getElementById('edit-title-btn').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}`,
+ expect.objectContaining({ method: 'PATCH' }),
+ );
+ });
+
+ if (bodyStarted) {
+ titleUpdate.resolve({ ok: true, status: 200, json: titleBody });
+ await vi.waitFor(() => expect(titleBody).toHaveBeenCalledOnce());
+ }
+
+ window.chatComponent.startNewChat();
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ if (bodyStarted) {
+ deferredTitleBody.resolve({ success: true });
+ } else {
+ titleUpdate.resolve({ ok: true, status: 200, json: titleBody });
+ }
+ await new Promise(resolve => setTimeout(resolve, 0));
+
+ expect(titleBody).toHaveBeenCalledTimes(bodyStarted ? 1 : 0);
+ expect(document.getElementById('chat-title').textContent).toBe('New Chat');
+ expect(document.title).toBe('New Chat - Chat Research');
+ delete window.prompt;
+});
+
+it('exports every cursor page while omitting progress-step rows', async () => {
+ const pages = [
+ initialMessages([
+ {
+ id: 'new-1',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Newest answer',
+ created_at: '2026-08-31T12:00:00Z',
+ },
+ {
+ id: 'step-1',
+ role: 'assistant',
+ message_type: 'step',
+ content: 'Internal progress',
+ created_at: '2026-08-31T11:59:59Z',
+ },
+ ], true),
+ initialMessages([{
+ id: 'old-1',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Oldest question',
+ created_at: '2026-08-30T10:00:00Z',
+ }], false),
+ ];
+ let exportPage = 0;
+ const objectUrl = vi.spyOn(URL, 'createObjectURL')
+ .mockReturnValue('blob:chat-export');
+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ window.URLValidator = { safeAssign: vi.fn((element, property, value) => {
+ element[property] = value;
+ }) };
+ const click = vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ await loadChat({
+ messages: [],
+ fetchRoute: (url) => {
+ if (url.includes('/messages?limit=100')) {
+ const page = pages[exportPage];
+ exportPage += 1;
+ return jsonResponse(page);
+ }
+ return null;
+ },
+ });
+ document.getElementById('chat-title').textContent = 'Title # one';
+
+ document.getElementById('export-chat-btn').click();
+
+ await vi.waitFor(() => {
+ expect(objectUrl).toHaveBeenCalledOnce();
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/chat/sessions/session-1/messages?limit=100'
+ + '&before_created_at=2026-08-31T12%3A00%3A00Z'
+ + '&before_id=new-1',
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ const exportedBlob = objectUrl.mock.calls[0][0];
+ const markdown = await exportedBlob.text();
+ expect(markdown).toContain('# Title \\# one');
+ expect(markdown.indexOf('Oldest question'))
+ .toBeLessThan(markdown.indexOf('Newest answer'));
+ expect(markdown).not.toContain('Internal progress');
+ expect(click).toHaveBeenCalledOnce();
+ expect(revoke).toHaveBeenCalledWith('blob:chat-export');
+});
+
+it('keeps every export page and archive title owned by the clicked session', async () => {
+ const firstExportPage = deferred();
+ const replacementSessionId = 'replacement-export-session';
+ const replacementResearchId = 'replacement-export-research';
+ let replacementExportReads = 0;
+ const objectUrl = vi.spyOn(URL, 'createObjectURL')
+ .mockReturnValue('blob:owned-chat-export');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ window.URLValidator = { safeAssign: vi.fn((element, property, value) => {
+ element[property] = value;
+ }) };
+ let downloadedFilename;
+ const click = vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(function captureDownload() {
+ downloadedFilename = this.download;
+ });
+ await loadChat({
+ messages: [],
+ fetchRoute: (url, options) => {
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages?limit=100`) {
+ return firstExportPage.promise;
+ }
+ if (url === `/api/chat/sessions/${SESSION_ID}/messages?limit=100`
+ + '&before_created_at=2026-08-31T12%3A00%3A00Z'
+ + '&before_id=new-old-session') {
+ return jsonResponse(initialMessages([{
+ id: 'old-old-session',
+ role: 'user',
+ message_type: 'chat',
+ content: 'Oldest message from the exported session',
+ created_at: '2026-08-30T10:00:00Z',
+ }], false));
+ }
+ if (url === '/api/chat/sessions' && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ session_id: replacementSessionId,
+ session: { title: 'Replacement export chat' },
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/generate-title`) {
+ return jsonResponse({ success: true });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages`
+ && options?.method === 'POST') {
+ return jsonResponse({
+ success: true,
+ research_id: replacementResearchId,
+ });
+ }
+ if (url === `/api/chat/sessions/${replacementSessionId}/messages?limit=100`) {
+ replacementExportReads += 1;
+ return jsonResponse(initialMessages([{
+ id: 'replacement-message',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Message from the replacement chat',
+ created_at: '2026-08-29T10:00:00Z',
+ }], false));
+ }
+ return null;
+ },
+ });
+
+ document.getElementById('export-chat-btn').click();
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ `/api/chat/sessions/${SESSION_ID}/messages?limit=100`,
+ { headers: { 'X-CSRFToken': 'csrf-chat' } },
+ );
+ });
+
+ window.chatComponent.startNewChat();
+ const input = document.getElementById('chat-input');
+ input.value = 'Create a replacement while export is paging';
+ input.dispatchEvent(new Event('input'));
+ document.getElementById('send-btn').click();
+ await vi.waitFor(() => {
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ replacementResearchId,
+ expect.any(Function),
+ );
+ });
+
+ firstExportPage.resolve(jsonResponse(initialMessages([{
+ id: 'new-old-session',
+ role: 'assistant',
+ message_type: 'chat',
+ content: 'Newest message from the exported session',
+ created_at: '2026-08-31T12:00:00Z',
+ }], true)));
+
+ await vi.waitFor(() => expect(objectUrl).toHaveBeenCalledOnce());
+ expect(replacementExportReads).toBe(0);
+ const exportedBlob = objectUrl.mock.calls[0][0];
+ const markdown = await exportedBlob.text();
+ expect(markdown).toContain('# Migration chat');
+ expect(markdown).toContain('Oldest message from the exported session');
+ expect(markdown).toContain('Newest message from the exported session');
+ expect(markdown).not.toContain('Message from the replacement chat');
+ expect(click).toHaveBeenCalledOnce();
+ expect(downloadedFilename).toBe(
+ `Migration_chat_${SESSION_ID.slice(0, 8)}.md`,
+ );
+
+ window.chatComponent.startNewChat();
+});
diff --git a/tests/js/components/checkbox-handler.test.js b/tests/js/components/checkbox-handler.test.js
index 5039e210e5..8356ccf476 100644
--- a/tests/js/components/checkbox-handler.test.js
+++ b/tests/js/components/checkbox-handler.test.js
@@ -126,5 +126,47 @@ describe('CheckboxHandler', () => {
handler.prepareFormSubmission(form);
expect(hidden.disabled).toBe(true);
});
+
+ it('syncs through the real bubbling form-submit listener', () => {
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ checkbox.checked = true;
+ checkbox.setAttribute('data-hidden-fallback', 'hidden-submit');
+
+ const hidden = document.createElement('input');
+ hidden.type = 'hidden';
+ hidden.id = 'hidden-submit';
+ hidden.disabled = false;
+ form.append(checkbox, hidden);
+
+ form.dispatchEvent(new Event('submit', {
+ bubbles: true,
+ cancelable: true,
+ }));
+
+ expect(hidden.disabled).toBe(true);
+ });
+ });
+
+ describe('dynamic controls', () => {
+ it('initializes checkbox pairs inserted inside a rendered wrapper', async () => {
+ const wrapper = document.createElement('div');
+ const checkbox = document.createElement('input');
+ checkbox.type = 'checkbox';
+ checkbox.checked = true;
+ checkbox.setAttribute('data-hidden-fallback', 'hidden-dynamic');
+ const hidden = document.createElement('input');
+ hidden.type = 'hidden';
+ hidden.id = 'hidden-dynamic';
+ hidden.disabled = false;
+ wrapper.append(checkbox, hidden);
+
+ form.appendChild(wrapper);
+
+ await vi.waitFor(() => expect(hidden.disabled).toBe(true));
+ checkbox.checked = false;
+ checkbox.dispatchEvent(new Event('change'));
+ expect(hidden.disabled).toBe(false);
+ });
});
});
diff --git a/tests/js/components/context-overflow-details-caller.test.js b/tests/js/components/context-overflow-details-caller.test.js
new file mode 100644
index 0000000000..c6b4066ec5
--- /dev/null
+++ b/tests/js/components/context-overflow-details-caller.test.js
@@ -0,0 +1,115 @@
+/**
+ * Regression coverage for the details page's per-research context-overflow
+ * request. The page initializes through its production DOMContentLoaded path.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'details-overflow-42';
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+
+function response({ ok, status, body }) {
+ return {
+ ok,
+ status,
+ url: '',
+ json: vi.fn().mockResolvedValue(body),
+ text: vi.fn().mockResolvedValue(''),
+ };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <div id="loading"></div>
+ <div id="error"></div>
+ <div id="details-content"></div>
+ <div id="total-tokens"></div>
+ <div id="prompt-tokens"></div>
+ <div id="completion-tokens"></div>
+ <div id="llm-calls"></div>
+ <div id="avg-response-time"></div>
+ <div id="model-used"></div>
+ <div id="research-query"></div>
+ <div id="research-mode"></div>
+ <div id="research-date"></div>
+ <div id="research-strategy"></div>
+ <div id="total-cost"></div>
+ <div id="phase-breakdown"></div>
+ <div id="search-engine-breakdown"></div>
+ <canvas id="timeline-chart"></canvas>
+ <canvas id="search-chart"></canvas>
+
+ <section id="context-overflow-section" style="display: none">
+ <div id="co-total-tokens"></div>
+ <div id="co-context-limit"></div>
+ <div id="co-max-tokens"></div>
+ <div id="co-truncation-status"></div>
+ <div id="co-phase-breakdown"></div>
+ <table><tbody id="co-requests-table"></tbody></table>
+ <div id="co-performance-warning" style="display: none"></div>
+ </section>
+ `;
+
+ window.contextOverflowShared = {
+ renderTruncationBadge: vi.fn(count => `<span>${count} truncations</span>`),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.contextOverflowShared;
+ document.body.replaceChildren();
+});
+
+it('loads the canonical per-research endpoint and reveals successful overflow metrics', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern').mockReturnValue(RESEARCH_ID);
+
+ const fetchMock = vi.fn(url => {
+ if (url === CONTEXT_URL) {
+ return Promise.resolve(response({
+ ok: true,
+ status: 200,
+ body: {
+ status: 'success',
+ data: {
+ overview: {
+ total_tokens: 12345,
+ context_limit: 8192,
+ max_tokens_used: 9000,
+ truncation_occurred: true,
+ truncated_count: 2,
+ },
+ phase_stats: {},
+ requests: [],
+ model: 'test-model',
+ provider: 'test-provider',
+ },
+ },
+ }));
+ }
+
+ // The details initializer also starts its independent metrics and link
+ // requests. They are outside this contract and may fail without
+ // preventing context-overflow data from rendering.
+ return Promise.resolve(response({ ok: false, status: 503, body: {} }));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/details.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('context-overflow-section').style.display)
+ .toBe('block');
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(CONTEXT_URL);
+ expect(document.getElementById('co-total-tokens').textContent).toBe('12,345');
+ expect(document.getElementById('co-context-limit').textContent).toBe('8,192');
+ expect(document.getElementById('co-max-tokens').textContent).toBe('9,000');
+ expect(window.contextOverflowShared.renderTruncationBadge).toHaveBeenCalledWith(2);
+ expect(document.getElementById('co-performance-warning').style.display).toBe('flex');
+});
diff --git a/tests/js/components/context-overflow-progress-caller.test.js b/tests/js/components/context-overflow-progress-caller.test.js
new file mode 100644
index 0000000000..40fc899b07
--- /dev/null
+++ b/tests/js/components/context-overflow-progress-caller.test.js
@@ -0,0 +1,136 @@
+/**
+ * Regression coverage for the progress page's completion-triggered
+ * per-research context-overflow request.
+ */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+
+const RESEARCH_ID = 'progress-overflow-17';
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+let progressCallback;
+
+beforeEach(() => {
+ progressCallback = null;
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ `;
+
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => ['completed', 'failed', 'error', 'cancelled'].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('consumes live progress before checking overflow on completion', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern').mockReturnValue(RESEARCH_ID);
+ const statusMock = vi.spyOn(window.api, 'getResearchStatus').mockResolvedValue({
+ status: 'in_progress',
+ progress: 40,
+ current_task: 'Gathering sources',
+ });
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ data: {
+ overview: {
+ truncation_occurred: true,
+ truncated_count: 3,
+ tokens_lost: 2500,
+ },
+ },
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ // Keep browser-notification permission out of the behavior under test;
+ // the in-page alert is the observable fallback available to every user.
+ vi.stubGlobal('Notification', { permission: 'denied' });
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => expect(statusMock.mock.calls.length).toBeGreaterThanOrEqual(2));
+
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledWith(
+ RESEARCH_ID,
+ expect.any(Function),
+ );
+ expect(progressCallback).toBeTypeOf('function');
+
+ progressCallback({
+ research_id: RESEARCH_ID,
+ status: 'in_progress',
+ progress: 73,
+ current_task: 'Synthesizing migrated results',
+ });
+
+ expect(document.getElementById('progress-bar').style.width).toBe('73%');
+ expect(document.getElementById('progress-percentage').textContent)
+ .toBe('73%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Synthesizing migrated results');
+ expect(document.title).toBe('Research (73%) - Local Deep Research');
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ statusMock.mockResolvedValue({ status: 'completed', progress: 100 });
+ await window.progressComponent.checkProgress();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('notification-container')?.textContent)
+ .toContain('Context Overflow Warning');
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(CONTEXT_URL);
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ const toast = document.getElementById('notification-container');
+ expect(toast.textContent).toContain('Context truncated 3 time(s) during research.');
+ expect(toast.textContent).toContain('~2,500 tokens lost.');
+ expect(toast.querySelector('button.btn-primary').textContent)
+ .toBe('View overflow details');
+
+ // Poll and socket terminal events may race. The completion guard must keep
+ // that duplicate signal from issuing another overflow request/toast.
+ await window.progressComponent.checkProgress();
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(toast.querySelectorAll('.ldr-alert-warning')).toHaveLength(1);
+});
diff --git a/tests/js/components/context-overflow-results-caller.test.js b/tests/js/components/context-overflow-results-caller.test.js
new file mode 100644
index 0000000000..50a5eeba7b
--- /dev/null
+++ b/tests/js/components/context-overflow-results-caller.test.js
@@ -0,0 +1,90 @@
+/**
+ * Regression coverage for the results page's per-research context-overflow
+ * request after a report loads successfully.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'results-overflow-8';
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <main id="results-content"></main>
+ <button id="export-markdown-btn" disabled></button>
+ <button id="download-pdf-btn" disabled></button>
+ <button id="view-metrics-btn">View metrics</button>
+ <div id="context-overflow-warning" style="display: none">
+ <span id="context-overflow-message"></span>
+ <a id="context-overflow-action">View details</a>
+ </div>
+ `;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('uses the canonical endpoint and decorates the page when truncation occurred', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern').mockReturnValue(RESEARCH_ID);
+ const safeAssign = vi.fn((target, attribute, value) => {
+ target.setAttribute(attribute, value);
+ });
+ vi.stubGlobal('URLValidator', { safeAssign });
+
+ const fetchMock = vi.fn(url => {
+ if (url === `/api/report/${RESEARCH_ID}`) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Finished report',
+ metadata: { query: 'Migration coverage' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ data: {
+ overview: {
+ truncation_occurred: true,
+ truncated_count: 1,
+ tokens_lost: 4096,
+ context_limit: 32768,
+ },
+ },
+ }),
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/results.js');
+ if (!fetchMock.mock.calls.some(([url]) => url === `/api/report/${RESEARCH_ID}`)) {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('context-overflow-warning').style.display)
+ .toBe('flex');
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(CONTEXT_URL);
+ expect(document.getElementById('context-overflow-message').textContent)
+ .toContain('Research was truncated 1 time(s) due to context limits.');
+ expect(document.getElementById('context-overflow-message').textContent)
+ .toContain('~4,096 tokens lost.');
+ expect(document.getElementById('context-overflow-action').getAttribute('href'))
+ .toBe(`/details/${RESEARCH_ID}#context-overflow-section`);
+ expect(document.getElementById('view-metrics-btn').classList)
+ .toContain('ldr-metrics-btn-overflow');
+ expect(document.querySelector('#view-metrics-btn .ldr-badge-overflow').textContent)
+ .toBe('OVERFLOW');
+});
diff --git a/tests/js/components/context-overflow-runtime.test.js b/tests/js/components/context-overflow-runtime.test.js
new file mode 100644
index 0000000000..fdaa2383df
--- /dev/null
+++ b/tests/js/components/context-overflow-runtime.test.js
@@ -0,0 +1,445 @@
+/**
+ * Direct runtime contracts for the context-overflow analytics page.
+ *
+ * The smaller context-overflow.test.js suite pins request ownership and the
+ * headline chart data. These tests exercise the production bootstrap and the
+ * user-facing controls, rendering, empty-state transitions, and chart
+ * callbacks that are otherwise easy to break during the FastAPI migration.
+ */
+
+const originalReadyState = Object.getOwnPropertyDescriptor(
+ document,
+ 'readyState'
+);
+
+class ChartStub {
+ static instances = [];
+
+ constructor(ctx, config) {
+ this.ctx = ctx;
+ this.config = config;
+ this.data = config.data;
+ this.destroy = vi.fn();
+ ChartStub.instances.push(this);
+ }
+}
+
+function buildPageDom() {
+ document.body.innerHTML = `
+ <button class="ldr-time-range-btn active" data-period="30d">30D</button>
+ <button class="ldr-time-range-btn" data-period="7d">7D</button>
+ <div id="loading"></div>
+ <div id="content" style="display: none">
+ <div id="empty-no-data" style="display: none"></div>
+ <div id="empty-no-context-data" style="display: none"></div>
+ <div id="empty-no-truncation" style="display: none"></div>
+ <div id="warning-banner" style="display: none">
+ <span id="warning-rate"></span>
+ </div>
+ <div id="context-overflow-section"></div>
+ <input id="requests-search">
+ <table>
+ <thead>
+ <tr>
+ <th class="ldr-sortable" data-sort="model">Model</th>
+ <th class="ldr-sortable" data-sort="total_tokens">Tokens</th>
+ </tr>
+ </thead>
+ <tbody id="requests-tbody"></tbody>
+ </table>
+ <button id="pagination-prev"></button>
+ <span id="pagination-info"></span>
+ <button id="pagination-next"></button>
+ </div>
+ `;
+}
+
+function payload(overrides = {}) {
+ const overview = {
+ truncation_rate: 0,
+ truncated_requests: 0,
+ requests_with_context_data: 0,
+ total_requests: 1,
+ avg_tokens_truncated: 0,
+ ...overrides.overview,
+ };
+ const tokenSummary = {
+ total_requests: 1,
+ ...overrides.token_summary,
+ };
+ return {
+ status: 'success',
+ model_stats: [],
+ model_token_stats: [],
+ recent_truncated: [],
+ chart_data: [],
+ context_limits: [],
+ phase_breakdown: [],
+ current_context_window: null,
+ all_requests: [],
+ pagination: { page: 1, total_pages: 1 },
+ ...overrides,
+ overview,
+ token_summary: tokenSummary,
+ };
+}
+
+function request(overrides = {}) {
+ return {
+ timestamp: '2026-08-01T12:00:00.000Z',
+ research_id: 'research-1',
+ model: 'openai/gpt-4o',
+ provider: 'openai',
+ research_phase: 'search',
+ prompt_tokens: 80,
+ completion_tokens: 20,
+ total_tokens: 100,
+ context_limit: 8192,
+ context_truncated: false,
+ tokens_truncated: 0,
+ research_query: 'Alpha question',
+ ...overrides,
+ };
+}
+
+function response(body, ok = true) {
+ return Promise.resolve({
+ ok,
+ json: vi.fn().mockResolvedValue(body),
+ });
+}
+
+async function importController(fetchMock) {
+ globalThis.fetch = fetchMock;
+ await import('@js/components/context-overflow.js');
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalled());
+ await vi.waitFor(() => {
+ expect(document.getElementById('content').style.display).toBe('block');
+ });
+ return window.contextOverflowController;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.restoreAllMocks();
+ delete window.__VITEST_TEST__;
+ delete window.contextOverflowController;
+ buildPageDom();
+ ChartStub.instances = [];
+ globalThis.Chart = ChartStub;
+ globalThis.URLValidator = { safeAssign: vi.fn() };
+ vi.spyOn(window.HTMLCanvasElement.prototype, 'getContext')
+ .mockReturnValue({});
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ value: 'complete',
+ });
+});
+
+afterAll(() => {
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+});
+
+it('boots the canonical endpoint and wires filtering, sorting, paging, and periods', async () => {
+ const alpha = request();
+ const beta = request({
+ research_id: 'research-2',
+ model: 'anthropic/claude-3',
+ provider: 'anthropic',
+ total_tokens: 900,
+ research_query: 'Beta question',
+ });
+ const fetchMock = vi.fn(url => {
+ const params = new URL(url, 'https://local.test').searchParams;
+ const page = Number(params.get('page'));
+ return response(payload({
+ all_requests: [alpha, beta],
+ pagination: { page, total_pages: 3 },
+ }));
+ });
+
+ await importController(fetchMock);
+
+ expect(fetchMock.mock.calls[0][0])
+ .toBe('/api/context-overflow?period=30d&page=1&per_page=50');
+ expect(document.querySelectorAll('#requests-tbody tr')).toHaveLength(2);
+
+ const search = document.getElementById('requests-search');
+ search.value = 'beta';
+ search.dispatchEvent(new Event('input'));
+ expect(document.querySelectorAll('#requests-tbody tr')).toHaveLength(1);
+ expect(document.getElementById('requests-tbody').textContent)
+ .toContain('Beta question');
+
+ search.value = '';
+ search.dispatchEvent(new Event('input'));
+ const tokenHeader = document.querySelector('[data-sort="total_tokens"]');
+ tokenHeader.click();
+ expect(document.querySelector('#requests-tbody tr').textContent)
+ .toContain('Beta question');
+ expect(tokenHeader.classList.contains('ldr-sort-desc')).toBe(true);
+ tokenHeader.click();
+ expect(document.querySelector('#requests-tbody tr').textContent)
+ .toContain('Alpha question');
+ expect(tokenHeader.classList.contains('ldr-sort-asc')).toBe(true);
+
+ document.getElementById('pagination-next').click();
+ await vi.waitFor(() => expect(fetchMock.mock.calls[1][0]).toContain('page=2'));
+ await vi.waitFor(() => {
+ expect(document.getElementById('pagination-info').textContent)
+ .toBe('Page 2 of 3');
+ });
+ document.getElementById('pagination-prev').click();
+ await vi.waitFor(() => expect(fetchMock.mock.calls[2][0]).toContain('page=1'));
+
+ document.querySelector('[data-period="7d"]').click();
+ await vi.waitFor(() => {
+ expect(fetchMock.mock.calls[3][0])
+ .toBe('/api/context-overflow?period=7d&page=1&per_page=50');
+ });
+ expect(document.querySelector('[data-period="7d"]')
+ .classList.contains('active')).toBe(true);
+ expect(document.querySelector('[data-period="30d"]')
+ .classList.contains('active')).toBe(false);
+});
+
+it('clears old rows, pagination, and provider banners when a period has no data', async () => {
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => response(payload({
+ all_requests: [request()],
+ pagination: { page: 2, total_pages: 4 },
+ })))
+ .mockImplementationOnce(() => response(payload({
+ token_summary: { total_requests: 0 },
+ overview: { total_requests: 0 },
+ pagination: { page: 1, total_pages: 1 },
+ })));
+ const controller = await importController(fetchMock);
+
+ expect(document.getElementById('empty-no-context-data').style.display)
+ .toBe('block');
+ expect(document.querySelectorAll('#requests-tbody tr')).toHaveLength(1);
+
+ await controller.loadContextData('7d', 1);
+
+ expect(document.getElementById('empty-no-data').style.display).toBe('block');
+ expect(document.getElementById('empty-no-context-data').style.display)
+ .toBe('none');
+ expect(document.getElementById('empty-no-truncation').style.display)
+ .toBe('none');
+ expect(document.getElementById('requests-tbody').textContent)
+ .toContain('No request data available');
+ expect(document.getElementById('pagination-info').textContent)
+ .toBe('Page 1 of 1');
+ expect(document.getElementById('pagination-prev').disabled).toBe(true);
+ expect(document.getElementById('pagination-next').disabled).toBe(true);
+});
+
+it('renders user-controlled request fields without creating injected attributes', async () => {
+ const hostile = '" onmouseover="globalThis.__contextOverflowXss = true';
+ const hostileRequest = request({
+ research_id: `id/${hostile}`,
+ model: hostile,
+ provider: hostile,
+ research_phase: hostile,
+ research_query: hostile,
+ });
+ const fetchMock = vi.fn(() => response(payload({
+ all_requests: [hostileRequest],
+ })));
+
+ await importController(fetchMock);
+
+ expect(document.querySelector('[onmouseover]')).toBeNull();
+ expect(document.getElementById('requests-tbody').textContent)
+ .toContain(hostile);
+ const detailsLink = document.querySelector('#requests-tbody a');
+ expect(detailsLink.getAttribute('href'))
+ .toBe(`/details/${encodeURIComponent(hostileRequest.research_id)}`);
+});
+
+it('keeps chart tooltips and drill-down navigation bound to the selected point', async () => {
+ const chartData = [
+ {
+ timestamp: '2026-08-01T12:00:00.000Z',
+ research_id: 'safe/id',
+ original_prompt_tokens: 1000,
+ prompt_tokens: 900,
+ context_limit: 8192,
+ model: 'openai/gpt-4o',
+ provider: 'openai',
+ research_phase: 'search',
+ response_time_ms: 900,
+ truncated: false,
+ },
+ {
+ timestamp: '2026-08-02T12:00:00.000Z',
+ research_id: 'critical/id',
+ original_prompt_tokens: 7000,
+ prompt_tokens: 7000,
+ context_limit: 8192,
+ model: 'anthropic/claude-3',
+ provider: 'anthropic',
+ research_phase: 'synthesis',
+ response_time_ms: 1500,
+ tokens_truncated: 100,
+ truncated: true,
+ },
+ {
+ timestamp: '2026-08-03T12:00:00.000Z',
+ research_id: 'unknown',
+ prompt_tokens: null,
+ context_limit: 4096,
+ research_phase: null,
+ response_time_ms: null,
+ },
+ ];
+ const fetchMock = vi.fn(() => response(payload({
+ overview: {
+ requests_with_context_data: 3,
+ total_requests: 3,
+ truncated_requests: 1,
+ truncation_rate: 33.3,
+ avg_tokens_truncated: 100,
+ },
+ token_summary: { total_requests: 3 },
+ model_stats: [{
+ model: 'anthropic/claude-3',
+ provider: 'anthropic',
+ total_requests: 2,
+ truncated_count: 1,
+ truncation_rate: 50,
+ avg_context_limit: 8192,
+ }],
+ model_token_stats: [{
+ model: 'anthropic/claude-3',
+ provider: 'anthropic',
+ min_prompt: 1000,
+ avg_prompt: 7000,
+ max_prompt: 7000,
+ avg_response_time_ms: 1500,
+ }],
+ recent_truncated: [{
+ ...request({ research_id: 'critical/id' }),
+ tokens_truncated: 100,
+ }],
+ chart_data: chartData,
+ phase_breakdown: [
+ { phase: 'search', count: 1, total_tokens: 1000, avg_tokens: 1000 },
+ { phase: 'synthesis', count: 1, total_tokens: 7000, avg_tokens: 7000 },
+ ],
+ current_context_window: 16384,
+ })));
+
+ await importController(fetchMock);
+
+ const context = ChartStub.instances.find(chart =>
+ chart.config.type === 'scatter'
+ && chart.config.options.scales.x.type === 'time'
+ );
+ const critical = context.data.datasets.find(dataset =>
+ dataset.label.startsWith('Critical')
+ ).data[0];
+ const contextLabel = context.config.options.plugins.tooltip.callbacks.label;
+ expect(contextLabel({ raw: critical }))
+ .toContain('7,000 prompt tokens / 8,192 limit (85%)');
+ expect(contextLabel({ raw: critical }))
+ .toContain('lost 100');
+ const unknown = context.data.datasets.find(dataset =>
+ dataset.label.startsWith('Caution')
+ ).data[0];
+ expect(contextLabel({ raw: unknown })).toContain('prompt tokens unknown');
+
+ context.config.options.onClick(null, [{ datasetIndex: 2, index: 0 }]);
+ expect(URLValidator.safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ '/details/critical%2Fid'
+ );
+
+ const latency = ChartStub.instances.find(chart =>
+ chart.config.type === 'scatter'
+ && chart.config.options.scales.x.title?.text === 'Prompt Tokens (input size)'
+ );
+ const latencyPoint = latency.data.datasets
+ .find(dataset => dataset.label.startsWith('Claude')).data[0];
+ expect(latency.config.options.plugins.tooltip.callbacks.label({
+ raw: latencyPoint,
+ })).toContain('7,000 tokens → 1.5s (85% of limit) [truncated]');
+ expect(latency.config.options.scales.y.ticks.callback(1500)).toBe('1.5s');
+ expect(latency.config.options.scales.y.ticks.callback(900)).toBe('900ms');
+ const criticalDatasetIndex = latency.data.datasets.findIndex(dataset =>
+ dataset.label.startsWith('Claude')
+ );
+ latency.config.options.onClick(null, [{
+ datasetIndex: criticalDatasetIndex,
+ index: 0,
+ }]);
+ expect(URLValidator.safeAssign).toHaveBeenLastCalledWith(
+ window.location,
+ 'href',
+ '/details/critical%2Fid'
+ );
+
+ const phase = ChartStub.instances.find(chart => chart.config.type === 'bar');
+ const drawContext = {
+ save: vi.fn(),
+ restore: vi.fn(),
+ beginPath: vi.fn(),
+ moveTo: vi.fn(),
+ lineTo: vi.fn(),
+ stroke: vi.fn(),
+ fillRect: vi.fn(),
+ strokeRect: vi.fn(),
+ };
+ phase.config.plugins[0].afterDatasetsDraw({
+ ctx: drawContext,
+ getDatasetMeta: () => ({ data: [{ x: 20 }, { x: 100 }] }),
+ scales: { y: { getPixelForValue: value => 300 - value / 50 } },
+ });
+ expect(drawContext.fillRect).toHaveBeenCalledTimes(2);
+ expect(phase.config.options.plugins.tooltip.callbacks.label({
+ raw: { y: 7000, phase: 'synthesis' },
+ })).toBe('7,000 prompt tokens · synthesis');
+});
+
+it('shows useful no-series states and handles a non-success API payload', async () => {
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => response(payload({
+ overview: {
+ requests_with_context_data: 1,
+ total_requests: 1,
+ truncated_requests: 0,
+ },
+ model_stats: [],
+ chart_data: [],
+ })))
+ .mockImplementationOnce(() => response({
+ status: 'error',
+ message: 'backend unavailable',
+ }));
+ const controller = await importController(fetchMock);
+
+ expect(document.getElementById('empty-no-truncation').style.display)
+ .toBe('block');
+ expect(document.getElementById('model-stats').textContent)
+ .toContain('No model data available');
+ expect(document.getElementById('truncated-list').textContent)
+ .toContain('No truncated requests found');
+ expect(document.getElementById('phase-breakdown-container').textContent)
+ .toContain('No phase data available yet');
+ expect(ChartStub.instances.some(chart =>
+ chart.config.options.plugins.title?.text === 'No context data available yet'
+ )).toBe(true);
+ expect(ChartStub.instances.some(chart =>
+ chart.config.options.plugins.title?.text === 'No latency data available yet'
+ )).toBe(true);
+
+ await controller.loadContextData('all', 1);
+ expect(document.getElementById('content').textContent)
+ .toContain('Error loading token usage data');
+});
diff --git a/tests/js/components/context-overflow.test.js b/tests/js/components/context-overflow.test.js
index 6e73e23a6a..19a76f4e56 100644
--- a/tests/js/components/context-overflow.test.js
+++ b/tests/js/components/context-overflow.test.js
@@ -94,7 +94,7 @@ describe('loadContextData — abort-on-supersede', () => {
expect(fetchMock.mock.calls[1][1]).toHaveProperty('signal');
});
- it('passes the period through to the request URL', async () => {
+ it('uses the canonical FastAPI endpoint with period and pagination', async () => {
const fetchMock = vi.fn(() => Promise.resolve({
ok: true,
json: () => Promise.resolve({
@@ -120,8 +120,114 @@ describe('loadContextData — abort-on-supersede', () => {
await window.contextOverflowController.loadContextData('1y', 3);
const url = fetchMock.mock.calls[0][0];
- expect(url).toContain('period=1y');
- expect(url).toContain('page=3');
+ expect(url).toBe(
+ '/api/context-overflow?period=1y&page=3&per_page=50'
+ );
+ });
+
+ it('replaces the loading state with retry guidance when the endpoint fails', async () => {
+ document.body.innerHTML = `
+ <div id="loading" style="display: block"></div>
+ <div id="content" style="display: none"></div>
+ <div id="empty-no-data"></div>
+ <div id="warning-banner"></div>
+ <div id="context-overflow-section"></div>
+ `;
+ const jsonMock = vi.fn().mockResolvedValue({
+ status: 'success',
+ overview: {},
+ token_summary: { total_requests: 0 },
+ });
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 503,
+ json: jsonMock,
+ });
+ global.fetch = fetchMock;
+
+ await window.contextOverflowController.loadContextData('30d', 2);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/context-overflow?period=30d&page=2&per_page=50',
+ { signal: expect.objectContaining({ aborted: false }) }
+ );
+ expect(jsonMock).not.toHaveBeenCalled();
+ expect(document.getElementById('loading').style.display).toBe('none');
+ expect(document.getElementById('content').style.display).toBe('block');
+ expect(document.getElementById('content').textContent)
+ .toContain('Error loading token usage data');
+ expect(document.getElementById('content').textContent)
+ .toContain('Please try refreshing the page');
+ });
+
+ it('drops a stale response that finishes parsing after its request was aborted', async () => {
+ document.body.innerHTML = `
+ <div id="loading"></div>
+ <div id="content"></div>
+ <div id="empty-no-data"></div>
+ <div id="empty-no-truncation"></div>
+ <div id="empty-no-context-data"></div>
+ <div id="warning-banner"></div>
+ <span id="warning-rate"></span>
+ <div id="context-overflow-section"></div>
+ <tbody id="requests-tbody"></tbody>
+ <span id="pagination-info"></span>
+ <button id="pagination-prev"></button>
+ <button id="pagination-next"></button>
+ `;
+
+ let resolveStaleJson;
+ const staleJson = vi.fn(() => new Promise(resolve => {
+ resolveStaleJson = resolve;
+ }));
+ const newestPayload = {
+ status: 'success',
+ overview: {},
+ token_summary: { total_requests: 0 },
+ };
+ const stalePayload = {
+ status: 'success',
+ overview: {
+ truncation_rate: 99,
+ truncated_requests: 1,
+ requests_with_context_data: 0,
+ total_requests: 1,
+ avg_tokens_truncated: 100,
+ },
+ token_summary: { total_requests: 1 },
+ model_stats: [],
+ model_token_stats: [],
+ recent_truncated: [],
+ chart_data: [],
+ context_limits: [],
+ phase_breakdown: [],
+ all_requests: [],
+ pagination: { page: 1, total_pages: 1 },
+ };
+
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({ ok: true, json: staleJson })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue(newestPayload),
+ });
+ global.fetch = fetchMock;
+
+ const controller = window.contextOverflowController;
+ const staleLoad = controller.loadContextData('1y');
+ await vi.waitFor(() => expect(staleJson).toHaveBeenCalledOnce());
+
+ await controller.loadContextData('7d');
+ expect(document.getElementById('empty-no-data').style.display).toBe('block');
+
+ resolveStaleJson(stalePayload);
+ await staleLoad;
+
+ // The late payload would hide this empty state and reveal a 99%
+ // warning if the post-await AbortSignal guard were removed.
+ expect(document.getElementById('empty-no-data').style.display).toBe('block');
+ expect(document.getElementById('warning-banner').style.display).toBe('none');
+ expect(document.getElementById('warning-rate').textContent).toBe('');
});
});
diff --git a/tests/js/components/details-metrics-runtime.test.js b/tests/js/components/details-metrics-runtime.test.js
new file mode 100644
index 0000000000..5391800cd5
--- /dev/null
+++ b/tests/js/components/details-metrics-runtime.test.js
@@ -0,0 +1,112 @@
+/**
+ * Runtime contract for the migrated research-details metrics loader.
+ *
+ * The optional timeline/search/link/context endpoints are deliberately
+ * unavailable here: the primary FastAPI responses must still populate and
+ * reveal the page rather than turn optional telemetry into a fatal error.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'metrics-runtime-42';
+
+function response(body, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ url: '',
+ json: vi.fn().mockResolvedValue(body),
+ text: vi.fn().mockResolvedValue(''),
+ };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <div id="loading"></div>
+ <div id="error" style="display: none"></div>
+ <main id="details-content" style="display: none"></main>
+ <section id="token-metrics-section" style="display: none"></section>
+ <section id="search-metrics-section" style="display: none"></section>
+ <div id="token-usage-top-chart" style="display: none"></div>
+ <div id="total-tokens"></div>
+ <div id="prompt-tokens"></div>
+ <div id="completion-tokens"></div>
+ <div id="llm-calls"></div>
+ <div id="avg-response-time"></div>
+ <div id="model-used"></div>
+ <div id="research-query"></div>
+ <div id="research-mode"></div>
+ <div id="research-date"></div>
+ <div id="research-strategy"></div>
+ <div id="total-cost"></div>
+ <div id="phase-breakdown"></div>
+ <div id="search-engine-breakdown"></div>
+ <canvas id="timeline-chart"></canvas>
+ <canvas id="search-chart"></canvas>
+ `;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('renders primary metrics through canonical routes when optional metrics are unavailable', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern').mockReturnValue(RESEARCH_ID);
+
+ const fetchMock = vi.fn(url => {
+ if (url === `/history/details/${RESEARCH_ID}`) {
+ return Promise.resolve(response({
+ query: 'FastAPI migration evidence',
+ mode: 'detailed',
+ strategy: 'source-based',
+ progress: 100,
+ }));
+ }
+ if (url === `/metrics/api/metrics/research/${RESEARCH_ID}`) {
+ return Promise.resolve(response({
+ status: 'success',
+ metrics: {
+ total_tokens: 12345,
+ total_calls: 3,
+ model_usage: [{
+ model: 'test-model',
+ prompt_tokens: 8000,
+ completion_tokens: 4345,
+ calls: 3,
+ }],
+ },
+ }));
+ }
+ return Promise.resolve(response({}, 503));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/details.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('details-content').style.display).toBe('block');
+ });
+
+ const requestedUrls = fetchMock.mock.calls.map(([url]) => String(url));
+ expect(requestedUrls).toEqual(expect.arrayContaining([
+ `/history/details/${RESEARCH_ID}`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/timeline`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/search`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/links`,
+ ]));
+ expect(document.getElementById('total-tokens').textContent).toBe('12,345');
+ expect(document.getElementById('prompt-tokens').textContent).toBe('8,000');
+ expect(document.getElementById('completion-tokens').textContent).toBe('4,345');
+ expect(document.getElementById('llm-calls').textContent).toBe('3');
+ expect(document.getElementById('model-used').textContent).toBe('test-model');
+ expect(document.getElementById('research-query').textContent)
+ .toBe('FastAPI migration evidence');
+ expect(document.getElementById('token-metrics-section').style.display).toBe('block');
+ expect(document.getElementById('error').style.display).toBe('none');
+});
diff --git a/tests/js/components/details-rich-metrics-runtime.test.js b/tests/js/components/details-rich-metrics-runtime.test.js
new file mode 100644
index 0000000000..a352020238
--- /dev/null
+++ b/tests/js/components/details-rich-metrics-runtime.test.js
@@ -0,0 +1,344 @@
+/**
+ * Rich runtime coverage for the migrated research-details page.
+ *
+ * This drives every optional FastAPI metrics response through the real page
+ * initializer. It also verifies the local escaping fallback used when the
+ * shared XSS helper has not loaded, a state the production component claims
+ * to support.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'rich-metrics-3299';
+
+function response(body, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ url: '',
+ json: vi.fn().mockResolvedValue(body),
+ text: vi.fn().mockResolvedValue(''),
+ };
+}
+
+function installDetailsDom() {
+ document.body.innerHTML = `
+ <div id="loading"></div>
+ <div id="error" style="display: none"></div>
+ <main id="details-content" style="display: none"></main>
+ <section id="token-metrics-section" style="display: none"></section>
+ <section id="search-metrics-section" style="display: none"></section>
+ <div id="token-usage-top-chart" style="display: none"></div>
+
+ <div id="total-tokens"></div>
+ <div id="prompt-tokens"></div>
+ <div id="completion-tokens"></div>
+ <div id="llm-calls"></div>
+ <div id="avg-response-time"></div>
+ <div id="model-used"></div>
+ <div id="research-query"></div>
+ <div id="research-mode"></div>
+ <div id="research-date"></div>
+ <div id="research-strategy"></div>
+ <div id="total-cost"></div>
+ <div id="phase-breakdown"></div>
+ <div id="search-engine-breakdown"></div>
+ <div id="search-engine-performance"></div>
+ <div id="search-timeline"></div>
+ <div id="total-searches"></div>
+ <div id="total-search-results"></div>
+ <div id="avg-search-response-time"></div>
+ <div id="search-success-rate"></div>
+ <section id="call-stack-card" style="display: none">
+ <div id="call-stack-traces"></div>
+ </section>
+ <canvas id="timeline-chart"></canvas>
+ <canvas id="search-chart"></canvas>
+ <button id="chart-view-bars" type="button"></button>
+ <button id="chart-view-line" type="button"></button>
+ <button id="view-results-btn" type="button"></button>
+ <button id="view-journals-btn" type="button"></button>
+ <button id="back-to-history" type="button"></button>
+
+ <section id="source-distribution-section" style="display: none">
+ <div class="ldr-card-content"><div><canvas id="source-type-chart"></canvas></div></div>
+ </section>
+ <section id="link-analytics-section" style="display: none"></section>
+ <div id="total-links"></div>
+ <div id="unique-domains"></div>
+ <div><span>Category one</span><span id="academic-sources"></span></div>
+ <div><span>Category two</span><span id="news-sources"></span></div>
+ <div id="domain-list"></div>
+ <div id="resource-sample"></div>
+
+ <section id="context-overflow-section" style="display: none">
+ <div id="co-total-tokens"></div>
+ <div id="co-context-limit"></div>
+ <div id="co-max-tokens"></div>
+ <div id="co-truncation-status"></div>
+ <div id="co-phase-breakdown"></div>
+ <table><tbody id="co-requests-table"></tbody></table>
+ <canvas id="co-usage-chart"></canvas>
+ <div id="co-performance-warning" style="display: none"></div>
+ </section>
+ `;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.contextOverflowShared;
+ document.body.replaceChildren();
+});
+
+it('renders rich optional metrics, safe untrusted text, and both timeline views', async () => {
+ installDetailsDom();
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern').mockReturnValue(RESEARCH_ID);
+ const resultsPage = vi.spyOn(window.URLBuilder, 'resultsPage')
+ .mockReturnValue('#results-route');
+ const journalQualityPage = vi.spyOn(window.URLBuilder, 'journalQualityPage')
+ .mockReturnValue('#journals-route');
+
+ // Exercise the component's documented defense-in-depth fallback rather
+ // than relying on xss-protection.js being present.
+ delete window.escapeHtml;
+ delete window.escapeHtmlAttribute;
+ delete window.sanitizeHtml;
+ delete window.safeSetInnerHTML;
+
+ const chartInstances = [];
+ class ChartMock {
+ constructor(context, config) {
+ this.context = context;
+ this.config = config;
+ this.destroy = vi.fn();
+ chartInstances.push(this);
+ }
+ }
+ vi.stubGlobal('Chart', ChartMock);
+ window.contextOverflowShared = {
+ renderTruncationBadge: vi.fn(count => `<span>${count} truncations</span>`),
+ };
+
+ const hostile = '<img src=x onerror="globalThis.__detailsXss = true">';
+ const timelineMetrics = {
+ research_details: {
+ query: 'Timeline query',
+ mode: 'detailed',
+ created_at: '2026-08-30T10:00:00Z',
+ },
+ summary: { avg_response_time: 1250 },
+ phase_stats: {
+ [hostile]: { tokens: 900, count: 2 },
+ },
+ timeline: [{
+ research_phase: 'analysis',
+ model_name: 'safe-model',
+ prompt_tokens: 600,
+ completion_tokens: 300,
+ tokens: 900,
+ cumulative_tokens: 900,
+ cumulative_prompt_tokens: 600,
+ cumulative_completion_tokens: 300,
+ response_time_ms: 1250,
+ timestamp: '2026-08-30T10:00:01Z',
+ search_engine_selected: 'searxng',
+ success_status: 'success',
+ calling_function: hostile,
+ calling_file: '/tmp/worker.py',
+ call_stack: hostile,
+ }],
+ };
+ const searchMetrics = {
+ total_searches: 2,
+ total_results: 17,
+ avg_response_time: 750,
+ success_rate: 50,
+ engine_stats: [{
+ engine: hostile,
+ call_count: 2,
+ success_rate: 50,
+ avg_response_time: 750,
+ total_results: 17,
+ }],
+ search_calls: [{
+ engine: hostile,
+ query: hostile,
+ results_count: 17,
+ response_time_ms: 750,
+ timestamp: '2026-08-30T10:00:02Z',
+ success_status: 'success',
+ }],
+ };
+
+ const fetchMock = vi.fn(url => {
+ const routes = {
+ [`/history/details/${RESEARCH_ID}`]: {
+ query: 'FastAPI details',
+ mode: 'detailed',
+ strategy: 'source-based',
+ progress: 100,
+ },
+ [`/metrics/api/metrics/research/${RESEARCH_ID}`]: {
+ status: 'success',
+ metrics: {
+ total_tokens: 900,
+ total_calls: 2,
+ model_usage: [{
+ model: 'safe-model',
+ prompt_tokens: 600,
+ completion_tokens: 300,
+ calls: 2,
+ }],
+ },
+ },
+ [`/metrics/api/metrics/research/${RESEARCH_ID}/timeline`]: {
+ status: 'success', metrics: timelineMetrics,
+ },
+ [`/metrics/api/metrics/research/${RESEARCH_ID}/search`]: {
+ status: 'success', metrics: searchMetrics,
+ },
+ [`/metrics/api/metrics/research/${RESEARCH_ID}/links`]: {
+ status: 'success',
+ data: {
+ total_links: 3,
+ unique_domains: 1,
+ domain_categories: { Academic: 3 },
+ domains: [{
+ domain: hostile,
+ count: '3',
+ percentage: '100',
+ }],
+ resources: [{
+ title: hostile,
+ url: `https://example.test/?q=${hostile}`,
+ preview: hostile,
+ }],
+ },
+ },
+ [`/api/research/${RESEARCH_ID}/context-overflow`]: {
+ status: 'success',
+ data: {
+ overview: {
+ total_tokens: 900,
+ context_limit: 4096,
+ max_tokens_used: 900,
+ truncation_occurred: false,
+ truncated_count: 0,
+ },
+ phase_stats: {
+ analysis: {
+ count: 1,
+ prompt_tokens: 600,
+ completion_tokens: 300,
+ total_tokens: 900,
+ truncated_count: 0,
+ },
+ },
+ requests: [{
+ timestamp: '2026-08-30T10:00:01Z',
+ phase: 'analysis',
+ calling_function: 'run',
+ prompt_tokens: 600,
+ completion_tokens: 300,
+ total_tokens: 900,
+ context_limit: 4096,
+ context_truncated: false,
+ response_time_ms: 1250,
+ }],
+ },
+ },
+ };
+ if (!(url in routes)) throw new Error(`Unexpected request: ${url}`);
+ return Promise.resolve(response(routes[url]));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/details.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('details-content').style.display).toBe('block');
+ expect(document.getElementById('link-analytics-section').style.display).toBe('block');
+ expect(document.getElementById('context-overflow-section').style.display).toBe('block');
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(expect.arrayContaining([
+ `/history/details/${RESEARCH_ID}`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/timeline`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/search`,
+ `/metrics/api/metrics/research/${RESEARCH_ID}/links`,
+ `/api/research/${RESEARCH_ID}/context-overflow`,
+ ]));
+ expect(document.getElementById('avg-response-time').textContent).toBe('1.3s');
+ expect(document.getElementById('search-success-rate').textContent).toBe('50.0%');
+ expect(document.getElementById('call-stack-card').style.display).toBe('block');
+ expect(document.getElementById('total-links').textContent).toBe('3');
+ expect(document.getElementById('domain-list').textContent).toContain(hostile);
+ expect(document.getElementById('resource-sample').textContent).toContain(hostile);
+ expect(document.querySelectorAll('img')).toHaveLength(0);
+ expect(globalThis.__detailsXss).not.toBe(true);
+
+ const chartTypes = chartInstances.map(instance => instance.config.type);
+ expect(chartTypes).toEqual(expect.arrayContaining(['pie', 'bar', 'line']));
+ const barChart = chartInstances.find(instance => instance.config.type === 'bar');
+ expect(barChart.config.data.datasets.map(dataset => dataset.data)).toEqual([
+ [600],
+ [300],
+ ]);
+ const barTooltips = barChart.config.options.plugins.tooltip.callbacks;
+ expect(barTooltips.title([{ dataIndex: 0 }])).toBe('analysis - safe-model');
+ expect(barTooltips.beforeBody([{ dataIndex: 0 }])).toEqual([
+ 'Total: 900 tokens',
+ ]);
+ expect(barTooltips.afterBody([{ dataIndex: 0 }])).toEqual(expect.arrayContaining([
+ 'Engine: searxng',
+ 'Status: success',
+ 'Response time: 1.3s',
+ ]));
+ expect(barChart.config.options.scales.y.ticks.callback(12345)).toBe('12,345');
+
+ const searchChart = chartInstances.find(instance => (
+ instance.config.type === 'line'
+ && instance.config.data.datasets[0].label === 'Results Found'
+ ));
+ const searchTooltips = searchChart.config.options.plugins.tooltip.callbacks;
+ expect(searchTooltips.title([{ dataIndex: 0 }])).toContain('<img src=x');
+ expect(searchTooltips.beforeBody([{ dataIndex: 0 }])).toEqual([
+ `Engine: ${hostile}`,
+ ]);
+ expect(searchTooltips.afterBody([{ dataIndex: 0 }])).toEqual([
+ 'Response time: 0.8s',
+ ]);
+ expect(searchChart.config.options.scales.y.ticks.callback(12345)).toBe('12,345');
+
+ document.getElementById('chart-view-line').click();
+ expect(barChart.destroy).toHaveBeenCalledOnce();
+ const cumulativeChart = chartInstances.at(-1);
+ expect(cumulativeChart.config.type).toBe('line');
+ expect(cumulativeChart.config.data.datasets[0].data).toEqual([900]);
+ expect(cumulativeChart.config.options.plugins.tooltip.callbacks.label({
+ dataset: { label: 'Cumulative Total Tokens' },
+ parsed: { y: 900 },
+ })).toBe('Cumulative Total Tokens: 900');
+ expect(document.getElementById('chart-view-line').classList).toContain('active');
+
+ document.getElementById('chart-view-bars').click();
+ expect(cumulativeChart.destroy).toHaveBeenCalledOnce();
+ expect(chartInstances.at(-1).config.type).toBe('bar');
+ expect(document.getElementById('chart-view-bars').classList).toContain('active');
+
+ document.getElementById('view-results-btn').click();
+ expect(resultsPage).toHaveBeenCalledWith(RESEARCH_ID);
+ expect(window.location.hash).toBe('#results-route');
+ document.getElementById('view-journals-btn').click();
+ expect(journalQualityPage).toHaveBeenCalledWith(RESEARCH_ID);
+ expect(window.location.hash).toBe('#journals-route');
+ document.getElementById('back-to-history').click();
+ expect(window.location.pathname).toBe(URLS.PAGES.HISTORY);
+ document.getElementById('classify-domains-btn').click();
+ expect(window.location.pathname).toBe('/metrics/links');
+});
diff --git a/tests/js/components/document-notes-runtime.test.js b/tests/js/components/document-notes-runtime.test.js
new file mode 100644
index 0000000000..01ebf28545
--- /dev/null
+++ b/tests/js/components/document-notes-runtime.test.js
@@ -0,0 +1,200 @@
+/**
+ * Direct browser contracts for the library document-notes panel.
+ *
+ * These tests load the real component so its document ownership, encoded
+ * FastAPI routes, annotation bridge, rendering, and mutation recovery remain
+ * pinned through the migration.
+ */
+
+let originalLocation;
+
+function setLocation(pathname = '/library/document/doc-1') {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: {
+ pathname,
+ search: '',
+ hash: '',
+ href: pathname,
+ host: 'localhost',
+ protocol: 'http:',
+ },
+ });
+}
+
+function response(data) {
+ return { json: () => Promise.resolve(data) };
+}
+
+function buildDocumentNotesDom(documentId = 'doc-1') {
+ document.body.innerHTML = `
+ <section id="document-notes-section">
+ <button id="document-add-note-btn">Add note</button>
+ <div id="document-notes-list"></div>
+ <p id="document-notes-empty">No document notes.</p>
+ </section>
+ <article id="ldr-document-text-content"></article>
+ `;
+ document.getElementById('document-notes-section').dataset.documentId =
+ documentId;
+ document.getElementById('ldr-document-text-content').dataset.documentId =
+ documentId;
+}
+
+async function loadComponent() {
+ await import('@js/components/document_notes.js');
+ return window.__documentNotesTest;
+}
+
+beforeAll(() => {
+ originalLocation = window.location;
+});
+
+beforeEach(() => {
+ vi.resetModules();
+ setLocation();
+ buildDocumentNotesDom();
+ window.__VITEST_TEST__ = true;
+ window.NotesShared = {
+ toast: vi.fn(),
+ postJson: vi.fn(),
+ renderNoteRow: vi.fn((note) => {
+ const row = document.createElement('article');
+ row.dataset.noteId = note.id;
+ row.textContent = note.title;
+ return row;
+ }),
+ };
+ window.LDRAnnotationSurface = { init: vi.fn() };
+ globalThis.safeFetchWithAuth = vi.fn().mockResolvedValue(response({
+ success: true,
+ notes: [],
+ }));
+ vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.__documentNotesTest;
+ document.body.replaceChildren();
+});
+
+afterAll(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ delete window.__VITEST_TEST__;
+});
+
+it('initializes encoded note and annotation routes for the owned document', async () => {
+ buildDocumentNotesDom('doc /?#');
+
+ const notes = await loadComponent();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith(
+ '/notes/api/documents/doc%20%2F%3F%23/notes',
+ { credentials: 'same-origin' },
+ );
+ });
+ const config = window.LDRAnnotationSurface.init.mock.calls[0][0];
+ expect(config.containerId).toBe('ldr-document-text-content');
+ expect(config.endpoints.list)
+ .toBe('/notes/api/documents/doc%20%2F%3F%23/annotations');
+ expect(config.endpoints.create)
+ .toBe('/notes/api/documents/doc%20%2F%3F%23/annotations');
+ expect(config.endpoints.deleteFor('note /?#'))
+ .toBe('/notes/api/documents/doc%20%2F%3F%23/annotations/note%20%2F%3F%23');
+ expect(config.onChanged).toBe(notes.loadDocumentNotes);
+});
+
+it('renders the FastAPI notes envelope and owns the empty state', async () => {
+ globalThis.safeFetchWithAuth.mockResolvedValue(response({
+ success: true,
+ notes: [
+ { id: 'note-1', title: 'Migration note' },
+ { id: 'note-2', title: 'Follow-up' },
+ ],
+ }));
+
+ await loadComponent();
+
+ await vi.waitFor(() => {
+ expect([...document.getElementById('document-notes-list').children]
+ .map((row) => row.dataset.noteId)).toEqual(['note-1', 'note-2']);
+ });
+ expect(document.getElementById('document-notes-empty').style.display)
+ .toBe('none');
+});
+
+it('renders a fixed load failure without injecting the server message', async () => {
+ globalThis.safeFetchWithAuth.mockResolvedValue(response({
+ success: false,
+ error: '<img src=x onerror="window.pwned=true">',
+ }));
+
+ await loadComponent();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('document-notes-empty').textContent)
+ .toBe("Couldn't load notes for this document.");
+ });
+ expect(document.getElementById('document-notes-empty').querySelector('img'))
+ .toBeNull();
+ expect(window.pwned).toBeUndefined();
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error loading document notes:',
+ expect.objectContaining({
+ message: '<img src=x onerror="window.pwned=true">',
+ }),
+ );
+});
+
+it('creates a linked note once and encodes the returned navigation ID', async () => {
+ window.NotesShared.postJson.mockResolvedValue({ note_id: 'note /?#' });
+ await loadComponent();
+
+ document.getElementById('document-add-note-btn').click();
+
+ await vi.waitFor(() => {
+ expect(window.NotesShared.postJson).toHaveBeenCalledWith(
+ '/notes/api/documents/doc-1/notes',
+ {},
+ );
+ });
+ expect(document.getElementById('document-add-note-btn').disabled).toBe(true);
+ expect(window.location.href).toBe('/notes/note%20%2F%3F%23');
+});
+
+it('re-enables note creation and surfaces a failed mutation', async () => {
+ window.NotesShared.postJson.mockRejectedValue(new Error('quota reached'));
+ await loadComponent();
+
+ document.getElementById('document-add-note-btn').click();
+
+ await vi.waitFor(() => {
+ expect(window.NotesShared.toast)
+ .toHaveBeenCalledWith('quota reached', 'error');
+ });
+ expect(document.getElementById('document-add-note-btn').disabled)
+ .toBe(false);
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error creating note for document:',
+ expect.objectContaining({ message: 'quota reached' }),
+ );
+});
+
+it('does nothing when neither document surface owns an ID', async () => {
+ document.body.innerHTML = `
+ <section id="document-notes-section"></section>
+ <article id="ldr-document-text-content"></article>
+ `;
+
+ await loadComponent();
+
+ expect(globalThis.safeFetchWithAuth).not.toHaveBeenCalled();
+ expect(window.LDRAnnotationSurface.init).not.toHaveBeenCalled();
+});
diff --git a/tests/js/components/fallback-ui-runtime.test.js b/tests/js/components/fallback-ui-runtime.test.js
new file mode 100644
index 0000000000..411d0930e1
--- /dev/null
+++ b/tests/js/components/fallback-ui-runtime.test.js
@@ -0,0 +1,149 @@
+/**
+ * Direct resilience contracts for the standalone UI fallback bundle.
+ * It is loaded precisely when the main UI service is unavailable, so its XSS
+ * and interaction behavior must be exercised independently of services/ui.js.
+ */
+
+async function loadFallback() {
+ vi.resetModules();
+ await import('@js/components/fallback/ui.js');
+ return window.ui;
+}
+
+beforeEach(() => {
+ delete window.ui;
+ delete window.escapeHtml;
+ delete window.URLValidator;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.ui;
+ delete window.escapeHtml;
+ delete window.URLValidator;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('does not replace the primary UI service when it is already loaded', async () => {
+ const primary = { showMessage: vi.fn() };
+ window.ui = primary;
+
+ await loadFallback();
+
+ expect(window.ui).toBe(primary);
+});
+
+it('renders and removes an escaped loading indicator', async () => {
+ const ui = await loadFallback();
+ const container = document.createElement('div');
+ document.body.appendChild(container);
+
+ ui.showSpinner(container, '<img src=x onerror="window.pwned=true">');
+
+ expect(container.textContent)
+ .toContain('<img src=x onerror="window.pwned=true">');
+ expect(container.querySelector('img')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ ui.hideSpinner(container);
+ expect(container.querySelector('.ldr-loading-spinner')).toBeNull();
+});
+
+it('owns safe notification dismissal and expiry without the main UI', async () => {
+ vi.useFakeTimers();
+ const ui = await loadFallback();
+ const notifications = document.createElement('div');
+ notifications.className = 'ldr-notifications-container';
+ document.body.appendChild(notifications);
+ const payload = '<svg onload="window.pwned=true">';
+
+ ui.showError(payload);
+ ui.showMessage('Saved safely');
+
+ expect(notifications.children).toHaveLength(2);
+ expect(notifications.textContent).toContain(payload);
+ expect(notifications.querySelector('svg')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ notifications.querySelector('.ldr-error .ldr-close-notification').click();
+ vi.advanceTimersByTime(500);
+ expect(notifications.querySelector('.ldr-error')).toBeNull();
+
+ vi.advanceTimersByTime(4499);
+ expect(notifications.querySelector('.ldr-success').classList)
+ .not.toContain('ldr-removing');
+ vi.advanceTimersByTime(1);
+ expect(notifications.querySelector('.ldr-success').classList)
+ .toContain('ldr-removing');
+ vi.advanceTimersByTime(500);
+ expect(notifications.children).toHaveLength(0);
+});
+
+it('falls back to alert when no notification host exists', async () => {
+ const alert = vi.fn();
+ vi.stubGlobal('alert', alert);
+ const ui = await loadFallback();
+
+ ui.showError('Offline');
+ ui.showMessage('Recovered');
+
+ expect(alert.mock.calls).toEqual([['Offline'], ['Recovered']]);
+});
+
+it('returns escaped plaintext Markdown with an explicit warning', async () => {
+ const ui = await loadFallback();
+
+ const rendered = ui.renderMarkdown('# Heading <img src=x>');
+
+ expect(rendered).toContain('Markdown rendering unavailable');
+ expect(rendered).toContain('&lt;img src=x&gt;');
+ expect(rendered).not.toContain('<img src=x>');
+ expect(ui.renderMarkdown('')).toBe('');
+});
+
+it('builds a dismissible inline error entirely with DOM nodes', async () => {
+ const ui = await loadFallback();
+ const container = document.createElement('div');
+ container.id = 'fallback-errors';
+ document.body.appendChild(container);
+ const payload = '<img src=x onerror="window.pwned=true">';
+
+ const first = ui.showInlineError('fallback-errors', payload);
+ const replacement = ui.showInlineError(container, 'Replacement', {
+ dismissible: false,
+ });
+
+ expect(first.isConnected).toBe(false);
+ expect(replacement.textContent).toContain('Replacement');
+ expect(replacement.querySelector('button')).toBeNull();
+ expect(container.querySelector('img')).toBeNull();
+ ui.clearInlineError('fallback-errors');
+ expect(container.children).toHaveLength(0);
+ expect(ui.showInlineError('missing', 'No host')).toBeNull();
+});
+
+it.each([
+ ['active', '/static/img/favicon-active.ico'],
+ ['complete', '/static/img/favicon-complete.ico'],
+ ['error', '/static/img/favicon-error.ico'],
+ ['unknown', '/static/img/favicon.ico'],
+])('maps %s to the fallback favicon asset', async (status, expectedPath) => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-01T12:00:00Z'));
+ const ui = await loadFallback();
+ const favicon = document.createElement('link');
+ favicon.rel = 'icon';
+ document.head.appendChild(favicon);
+ window.URLValidator = { safeAssign: vi.fn() };
+
+ ui.updateFavicon(status);
+
+ expect(window.URLValidator.safeAssign).toHaveBeenCalledWith(
+ favicon,
+ 'href',
+ `${expectedPath}?v=${Date.now()}`,
+ );
+});
diff --git a/tests/js/components/history-migration-contract.test.js b/tests/js/components/history-migration-contract.test.js
new file mode 100644
index 0000000000..fa5b53497f
--- /dev/null
+++ b/tests/js/components/history-migration-contract.test.js
@@ -0,0 +1,1188 @@
+/**
+ * Browser-side contract for the history endpoints migrated in #3299.
+ *
+ * This drives history.js through its production bootstrap and consumes the
+ * real response envelopes. Route-table tests already prove that the URLs
+ * exist; this test proves the unchanged page still understands what the new
+ * FastAPI handlers return.
+ */
+
+const RESEARCH_ID = 'migration-3299-history';
+const CHAT_SESSION_ID = 'migration-3299-chat';
+
+function buildHistoryDom() {
+ document.body.innerHTML = `
+ <input id="history-search" value="">
+ <button id="search-mode-btn"></button>
+ <div id="search-mode-menu">
+ <button class="dropdown-item active" data-mode="hybrid">Hybrid</button>
+ <button class="dropdown-item" data-mode="text">Text</button>
+ <button class="dropdown-item" data-mode="semantic">Semantic</button>
+ </div>
+ <button id="clear-history-btn" style="display: none"></button>
+ <div id="history-items"></div>
+ <div id="history-empty-message" style="display: none"></div>
+ `;
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+async function installHistoryGlobals() {
+ await import('@js/config/urls.js');
+ await import('@js/services/api.js');
+
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('ResearchStates', {
+ formatStatus: status => (
+ status === 'completed' ? 'Completed' : status
+ ),
+ isCompleted: status => status === 'completed',
+ isTerminal: status => ['completed', 'failed', 'cancelled'].includes(status),
+ });
+
+ const safeAssign = vi.fn();
+ vi.stubGlobal('URLValidator', { safeAssign });
+ window.safeUpdateButton = vi.fn();
+ return safeAssign;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ buildHistoryDom();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.ui;
+ delete window.safeUpdateButton;
+ delete window.HistorySearch;
+ delete window.__historySemanticXss;
+ sessionStorage.clear();
+ document.body.replaceChildren();
+});
+
+it('renders and routes both migrated history feeds', async () => {
+ const safeAssign = await installHistoryGlobals();
+
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: RESEARCH_ID,
+ title: 'FastAPI migration audit',
+ query: 'Which browser contracts changed?',
+ mode: 'detailed',
+ status: 'completed',
+ created_at: '2026-08-31T10:00:00Z',
+ completed_at: '2026-08-31T10:05:00Z',
+ document_count: 0,
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [{
+ id: CHAT_SESSION_ID,
+ title: 'Migration follow-up',
+ status: 'active',
+ created_at: '2026-08-31T11:00:00Z',
+ }],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+
+ await vi.waitFor(() => {
+ expect(document.querySelector(
+ `.ldr-history-item[data-id="${RESEARCH_ID}"]`,
+ )).not.toBeNull();
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => String(url))).toEqual([
+ '/history/api',
+ '/api/chat/sessions?status=all&limit=100&offset=0',
+ ]);
+
+ const item = document.querySelector(
+ `.ldr-history-item[data-id="${RESEARCH_ID}"]`,
+ );
+ const chatItem = document.querySelector(
+ `.ldr-history-item[data-id="${CHAT_SESSION_ID}"][data-type="chat"]`,
+ );
+ expect(item.querySelector('.ldr-history-item-title').textContent)
+ .toBe('FastAPI migration audit');
+ expect(item.querySelector('.ldr-view-btn')).not.toBeNull();
+ expect(chatItem.querySelector('.ldr-history-item-title').textContent)
+ .toBe('Migration follow-up');
+ expect(chatItem.textContent).toContain('Open Chat');
+
+ item.querySelector('.ldr-view-btn').click();
+ chatItem.querySelector('.ldr-view-btn').click();
+
+ expect(safeAssign.mock.calls).toEqual([
+ [
+ window.location,
+ 'href',
+ `/results/${encodeURIComponent(RESEARCH_ID)}`,
+ ],
+ [
+ window.location,
+ 'href',
+ `/chat/${encodeURIComponent(CHAT_SESSION_ID)}`,
+ ],
+ ]);
+});
+
+it('groups migrated research rows under their chat and routes children back to the conversation', async () => {
+ const safeAssign = await installHistoryGlobals();
+ const childResearchId = 'migration-3299-chat-child';
+
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: childResearchId,
+ title: 'Research from a chat turn',
+ query: 'Follow this source',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-08-31T11:01:00Z',
+ metadata: { chat_session_id: CHAT_SESSION_ID },
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [{
+ id: CHAT_SESSION_ID,
+ title: 'Migration follow-up',
+ status: 'active',
+ created_at: '2026-08-31T11:00:00Z',
+ }],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+
+ await vi.waitFor(() => {
+ expect(document.querySelector(
+ `.ldr-history-group[data-id="${CHAT_SESSION_ID}"]`,
+ )).not.toBeNull();
+ });
+
+ const group = document.querySelector(
+ `.ldr-history-group[data-id="${CHAT_SESSION_ID}"]`,
+ );
+ const child = group.querySelector(
+ `.ldr-history-child-item[data-id="${childResearchId}"]`,
+ );
+ expect(group.querySelector('.ldr-history-child-count').textContent)
+ .toContain('1 research');
+ expect(child).not.toBeNull();
+
+ group.querySelector('.ldr-group-toggle').click();
+ expect(group.querySelector('.ldr-group-toggle').getAttribute('aria-expanded'))
+ .toBe('true');
+ expect(group.querySelector('.ldr-history-group-children').classList)
+ .toContain('ldr-history-group-children--open');
+
+ child.querySelector('.ldr-view-btn').click();
+ expect(safeAssign).toHaveBeenCalledOnce();
+ expect(safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ `/chat/${encodeURIComponent(CHAT_SESSION_ID)}`,
+ );
+});
+
+it('paginates the migrated chat feed before Clear All deletes every session', async () => {
+ await installHistoryGlobals();
+ const showMessage = vi.fn();
+ window.ui = { showMessage };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+
+ const firstPage = Array.from({ length: 100 }, (_, index) => ({
+ id: `chat-page-1-${index}`,
+ title: `Chat ${index}`,
+ status: 'active',
+ created_at: '2026-08-31T11:00:00Z',
+ }));
+ const finalSession = {
+ id: 'chat-page-2-final',
+ title: 'Final chat',
+ status: 'active',
+ created_at: '2026-08-31T10:00:00Z',
+ };
+ let initialChatLoadComplete = false;
+
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: RESEARCH_ID,
+ title: 'A research to clear',
+ query: 'Clear me',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-08-31T09:00:00Z',
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ if (!initialChatLoadComplete) {
+ initialChatLoadComplete = true;
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: firstPage,
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=100') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [finalSession],
+ }), { status: 200 }));
+ }
+ if (url === '/api/clear_history' && options.method === 'POST') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ if (url.startsWith('/api/chat/sessions/') && options.method === 'DELETE') {
+ return Promise.resolve(new Response(null, { status: 204 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${RESEARCH_ID}"]`))
+ .not.toBeNull();
+ });
+
+ document.getElementById('clear-history-btn').click();
+
+ await vi.waitFor(() => {
+ const deleteCalls = fetchMock.mock.calls.filter(
+ ([url, options = {}]) => (
+ String(url).startsWith('/api/chat/sessions/')
+ && options.method === 'DELETE'
+ ),
+ );
+ expect(deleteCalls).toHaveLength(101);
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => String(url))).toContain(
+ '/api/chat/sessions?status=all&limit=100&offset=100',
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ `/api/chat/sessions/${finalSession.id}`,
+ expect.objectContaining({ method: 'DELETE' }),
+ );
+ expect(showMessage).toHaveBeenCalledWith(
+ 'Research history cleared successfully',
+ );
+ expect(document.getElementById('history-empty-message').style.display)
+ .toBe('block');
+});
+
+it('does not claim Clear All succeeded when a chat deletion fails', async () => {
+ await installHistoryGlobals();
+ const showMessage = vi.fn();
+ window.ui = { showMessage };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const chatId = 'chat-that-survives-3299';
+ let historyLoads = 0;
+ let chatListLoads = 0;
+
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ historyLoads += 1;
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: historyLoads === 1 ? [{
+ id: RESEARCH_ID,
+ title: 'Research cleared before chat failure',
+ query: 'Clear this research',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }] : [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ chatListLoads += 1;
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [{
+ id: chatId,
+ title: 'Chat still on the server',
+ status: 'active',
+ created_at: '2026-09-01T10:00:00Z',
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/clear_history' && options.method === 'POST') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ if (url === `/api/chat/sessions/${chatId}`
+ && options.method === 'DELETE') {
+ return Promise.resolve(new Response(JSON.stringify({
+ detail: 'Chat is busy',
+ }), { status: 500, statusText: 'Server Error' }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${RESEARCH_ID}"]`))
+ .not.toBeNull();
+ });
+
+ document.getElementById('clear-history-btn').click();
+
+ await vi.waitFor(() => {
+ expect(showMessage).toHaveBeenCalledWith(
+ expect.stringContaining('chat sessions could not all be cleared'),
+ 'error',
+ );
+ });
+ expect(showMessage).not.toHaveBeenCalledWith(
+ 'Research history cleared successfully',
+ );
+ expect(historyLoads).toBe(2);
+ expect(chatListLoads).toBe(3);
+ expect(document.querySelector(`[data-id="${RESEARCH_ID}"]`)).toBeNull();
+ expect(document.querySelector(`[data-id="${chatId}"]`)).not.toBeNull();
+});
+
+it('does not claim Clear All succeeded when chat pagination fails', async () => {
+ await installHistoryGlobals();
+ const showMessage = vi.fn();
+ window.ui = { showMessage };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ let historyLoads = 0;
+ let chatListLoads = 0;
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ historyLoads += 1;
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: historyLoads === 1 ? [{
+ id: RESEARCH_ID,
+ title: 'Research cleared before list failure',
+ query: 'Clear this research',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }] : [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ chatListLoads += 1;
+ if (chatListLoads === 2) {
+ return Promise.resolve(new Response(JSON.stringify({
+ detail: 'Chat listing unavailable',
+ }), { status: 503, statusText: 'Unavailable' }));
+ }
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/clear_history' && options.method === 'POST') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${RESEARCH_ID}"]`))
+ .not.toBeNull();
+ });
+ document.getElementById('clear-history-btn').click();
+
+ await vi.waitFor(() => {
+ expect(showMessage).toHaveBeenCalledWith(
+ expect.stringContaining('chat sessions could not all be cleared'),
+ 'error',
+ );
+ });
+ expect(showMessage).not.toHaveBeenCalledWith(
+ 'Research history cleared successfully',
+ );
+ expect(fetchMock.mock.calls.some(([url, options = {}]) => (
+ String(url).startsWith('/api/chat/sessions/')
+ && options.method === 'DELETE'
+ ))).toBe(false);
+ expect(historyLoads).toBe(2);
+ expect(chatListLoads).toBe(3);
+});
+
+it('routes news actions, persists rerun configuration, and copies the query', async () => {
+ const safeAssign = await installHistoryGlobals();
+ const showMessage = vi.fn();
+ window.ui = { showMessage };
+ const clipboardDescriptor = Object.getOwnPropertyDescriptor(
+ navigator,
+ 'clipboard',
+ );
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText },
+ });
+ vi.stubGlobal('isSecureContext', true);
+ const query = 'Track climate policy & source changes';
+ const newsId = 'news-actions-3299';
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: newsId,
+ title: 'Climate policy monitor',
+ query,
+ mode: 'detailed',
+ status: 'completed',
+ created_at: '2026-09-01T10:00:00Z',
+ document_count: 3,
+ metadata: { is_news_search: true },
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ try {
+ await import('@js/components/history.js');
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${newsId}"]`))
+ .not.toBeNull();
+ });
+ const item = document.querySelector(`[data-id="${newsId}"]`);
+
+ item.querySelector('.ldr-library-btn').click();
+ item.querySelector('.ldr-subscribe-btn').click();
+ item.querySelector('.ldr-rerun-btn').click();
+ item.querySelector('.ldr-copy-query-btn').click();
+ await vi.waitFor(() => expect(writeText).toHaveBeenCalledWith(query));
+
+ expect(safeAssign).toHaveBeenNthCalledWith(
+ 1,
+ window.location,
+ 'href',
+ `/library/?research=${encodeURIComponent(newsId)}`,
+ );
+ const subscriptionUrl = new URL(
+ safeAssign.mock.calls[1][2],
+ 'http://localhost',
+ );
+ expect(subscriptionUrl.pathname).toBe('/news/subscriptions/new');
+ expect(Object.fromEntries(subscriptionUrl.searchParams)).toEqual({
+ query,
+ name: query,
+ source_id: newsId,
+ });
+ expect(safeAssign).toHaveBeenNthCalledWith(
+ 3,
+ window.location,
+ 'href',
+ '/',
+ );
+ expect(JSON.parse(sessionStorage.getItem('rerunConfig'))).toEqual({
+ query,
+ mode: 'detailed',
+ });
+ expect(showMessage).toHaveBeenCalledWith(
+ 'Query copied to clipboard',
+ );
+ } finally {
+ if (clipboardDescriptor) {
+ Object.defineProperty(
+ navigator,
+ 'clipboard',
+ clipboardDescriptor,
+ );
+ } else {
+ delete navigator.clipboard;
+ }
+ }
+});
+
+it('removes a deleted research locally and keeps a failed deletion visible', async () => {
+ await installHistoryGlobals();
+ const showMessage = vi.fn();
+ window.ui = { showMessage };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const successfulId = 'delete-success-3299';
+ const failedId = 'delete-failure-3299';
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [successfulId, failedId].map((id, index) => ({
+ id,
+ title: `Delete candidate ${index + 1}`,
+ query: `Delete query ${index + 1}`,
+ mode: 'quick',
+ status: 'failed',
+ created_at: `2026-09-01T10:0${index}:00Z`,
+ metadata: {},
+ })),
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ if (url === `/api/delete/${successfulId}` && options.method === 'DELETE') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ if (url === `/api/delete/${failedId}` && options.method === 'DELETE') {
+ return Promise.resolve(new Response(JSON.stringify({
+ detail: 'Research is still running',
+ }), { status: 409 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${successfulId}"]`))
+ .not.toBeNull();
+ });
+
+ document.querySelector(
+ `[data-id="${successfulId}"] .ldr-delete-item-btn`,
+ ).click();
+ await vi.waitFor(() => {
+ expect(document.querySelector(`[data-id="${successfulId}"]`))
+ .toBeNull();
+ });
+ expect(showMessage).toHaveBeenCalledWith(
+ 'Research deleted successfully',
+ );
+
+ document.querySelector(
+ `[data-id="${failedId}"] .ldr-delete-item-btn`,
+ ).click();
+ await vi.waitFor(() => {
+ expect(showMessage).toHaveBeenCalledWith(
+ 'Error deleting item: Research is still running',
+ 'error',
+ );
+ });
+ expect(document.querySelector(`[data-id="${failedId}"]`))
+ .not.toBeNull();
+});
+
+it('filters chat groups down to matching children and expands the result', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ const chatId = 'filter-chat-3299';
+ const matchingChild = 'filter-child-match';
+ const hiddenChild = 'filter-child-hidden';
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [
+ {
+ id: matchingChild,
+ title: 'Quantum evidence review',
+ query: 'Review quantum evidence',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T10:02:00Z',
+ metadata: { chat_session_id: chatId },
+ },
+ {
+ id: hiddenChild,
+ title: 'Unrelated economics review',
+ query: 'Review economics evidence',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T10:01:00Z',
+ metadata: { chat_session_id: chatId },
+ },
+ ],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [{
+ id: chatId,
+ title: 'General conversation',
+ status: 'active',
+ created_at: '2026-09-01T10:00:00Z',
+ }],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.querySelector(`[data-id="${matchingChild}"]`))
+ .not.toBeNull();
+
+ document.querySelector('[data-mode="text"]').click();
+ const input = document.getElementById('history-search');
+ input.value = 'quantum';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(250);
+
+ const group = document.querySelector(
+ `.ldr-history-group[data-id="${chatId}"]`,
+ );
+ expect(group).not.toBeNull();
+ expect(group.querySelector('.ldr-group-toggle').getAttribute('aria-expanded'))
+ .toBe('true');
+ expect(group.querySelector(`[data-id="${matchingChild}"]`))
+ .not.toBeNull();
+ expect(group.querySelector(`[data-id="${hiddenChild}"]`)).toBeNull();
+ expect(group.querySelector('.ldr-history-child-count').textContent)
+ .toContain('1 research');
+});
+
+it('merges hybrid results through the real history renderer and keeps semantic-only data inert', async () => {
+ const safeAssign = await installHistoryGlobals();
+ vi.useFakeTimers();
+ const textId = 'hybrid-text-3299';
+ const semanticId = 'semantic/only-3299';
+ window.HistorySearch = {
+ getSemanticCollectionId: vi.fn(() => 'history-collection'),
+ semanticSearchHistory: vi.fn().mockResolvedValue([{
+ research_id: textId,
+ similarity: 97,
+ snippet: 'Migration text and semantic match',
+ }, {
+ research_id: semanticId,
+ similarity: 88,
+ research_title: '<img src=x onerror="window.__historySemanticXss=true">',
+ snippet: '<script>window.__historySemanticXss=true</script> semantic only',
+ research_created_at: '2026-09-01T10:00:00Z',
+ }]),
+ };
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: textId,
+ title: 'FastAPI migration contract',
+ query: 'Audit the migration contract',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ const input = document.getElementById('history-search');
+ input.value = 'migration';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+
+ await vi.waitFor(() => {
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('migration');
+ expect(document.querySelector(`[data-id="${textId}"] .ldr-ai-match-badge`)
+ .textContent).toContain('97% match');
+ expect(document.querySelector('.ldr-hybrid-divider').textContent)
+ .toBe('Also found in content');
+ });
+ const semanticOnly = document.querySelector(
+ `.ldr-history-item--semantic-only[data-id="${semanticId}"]`,
+ );
+ expect(semanticOnly).not.toBeNull();
+ expect(semanticOnly.textContent).toContain('<img src=x onerror=');
+ expect(semanticOnly.querySelector('img')).toBeNull();
+ expect(semanticOnly.querySelector('script')).toBeNull();
+ expect(window.__historySemanticXss).toBeUndefined();
+
+ semanticOnly.querySelector('.ldr-view-btn').click();
+ expect(safeAssign).toHaveBeenLastCalledWith(
+ window.location,
+ 'href',
+ `/results/${semanticId}`,
+ );
+});
+
+it('keeps the full history after clearing a pending semantic search', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ const pendingSearch = deferred();
+ const historyId = 'semantic-clear-history-3299';
+ const renderSemanticResults = vi.fn((results) => {
+ document.getElementById('history-items').textContent =
+ `stale semantic result: ${results[0].research_id}`;
+ });
+ window.HistorySearch = {
+ semanticSearchHistory: vi.fn(() => pendingSearch.promise),
+ renderSemanticResults,
+ };
+ vi.stubGlobal('fetch', vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: historyId,
+ title: 'Durable full-history row',
+ query: 'A different query',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ document.querySelector('[data-mode="semantic"]').click();
+ const input = document.getElementById('history-search');
+ input.value = 'pending semantic query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('pending semantic query');
+
+ input.value = '';
+ input.dispatchEvent(new Event('input'));
+ pendingSearch.resolve([{ research_id: 'stale-semantic-3299' }]);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(renderSemanticResults).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(document.querySelector(`[data-id="${historyId}"]`)).not.toBeNull();
+ expect(document.getElementById('history-items').textContent)
+ .not.toContain('stale semantic result');
+});
+
+it('invalidates an in-flight semantic result at the synchronous input boundary', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ const olderSearch = deferred();
+ const newestResults = [{ research_id: 'newest-input-boundary-3299' }];
+ const renderSemanticResults = vi.fn((results, query) => {
+ document.getElementById('history-items').textContent =
+ `${query}: ${results[0].research_id}`;
+ });
+ window.HistorySearch = {
+ semanticSearchHistory: vi.fn()
+ .mockReturnValueOnce(olderSearch.promise)
+ .mockResolvedValueOnce(newestResults),
+ renderSemanticResults,
+ };
+ vi.stubGlobal('fetch', vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ document.querySelector('[data-mode="semantic"]').click();
+ const input = document.getElementById('history-search');
+
+ input.value = 'older query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('older query');
+
+ input.value = 'newer query';
+ input.dispatchEvent(new Event('input'));
+ olderSearch.resolve([{ research_id: 'stale-input-boundary-3299' }]);
+ // Flush the old request immediately, without advancing the 250 ms input
+ // debounce that will render and launch work for the newer query.
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(window.HistorySearch.semanticSearchHistory).toHaveBeenCalledTimes(1);
+ expect(renderSemanticResults).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(750);
+
+ expect(renderSemanticResults).toHaveBeenCalledOnce();
+ expect(renderSemanticResults).toHaveBeenCalledWith(
+ newestResults,
+ 'newer query',
+ );
+ expect(document.getElementById('history-items').textContent)
+ .toBe('newer query: newest-input-boundary-3299');
+});
+
+it('cancels a semantic search cleared before its request starts', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ const historyId = 'semantic-debounce-clear-3299';
+ window.HistorySearch = {
+ semanticSearchHistory: vi.fn().mockResolvedValue([]),
+ renderSemanticResults: vi.fn(),
+ };
+ vi.stubGlobal('fetch', vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: historyId,
+ title: 'History survives cancelled debounce',
+ query: 'A durable row',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ document.querySelector('[data-mode="semantic"]').click();
+ const input = document.getElementById('history-search');
+ input.value = 'cancel before request';
+ input.dispatchEvent(new Event('input'));
+ // The outer input debounce has installed the 500 ms semantic timer, but
+ // the request itself has not started yet.
+ await vi.advanceTimersByTimeAsync(250);
+
+ input.value = '';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+
+ expect(window.HistorySearch.semanticSearchHistory).not.toHaveBeenCalled();
+ expect(window.HistorySearch.renderSemanticResults).not.toHaveBeenCalled();
+ expect(document.querySelector(`[data-id="${historyId}"]`)).not.toBeNull();
+ expect(document.querySelector('.ldr-loading-spinner')).toBeNull();
+});
+
+it('does not replay a typed query after an immediate search-mode switch', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ window.HistorySearch = {
+ semanticSearchHistory: vi.fn().mockResolvedValue([]),
+ renderSemanticResults: vi.fn(),
+ };
+ vi.stubGlobal('fetch', vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ const input = document.getElementById('history-search');
+ input.value = 'single semantic request';
+ input.dispatchEvent(new Event('input'));
+ document.querySelector('[data-mode="semantic"]').click();
+
+ await vi.advanceTimersByTimeAsync(750);
+
+ expect(window.HistorySearch.semanticSearchHistory).toHaveBeenCalledOnce();
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('single semantic request');
+});
+
+it('keeps the full history after clearing a pending hybrid search', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ const pendingSearch = deferred();
+ const historyId = 'hybrid-clear-history-3299';
+ window.HistorySearch = {
+ getSemanticCollectionId: vi.fn(() => 'history-collection'),
+ semanticSearchHistory: vi.fn(() => pendingSearch.promise),
+ };
+ vi.stubGlobal('fetch', vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [{
+ id: historyId,
+ title: 'Durable hybrid full-history row',
+ query: 'A different query',
+ mode: 'quick',
+ status: 'completed',
+ created_at: '2026-09-01T09:00:00Z',
+ metadata: {},
+ }],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ const input = document.getElementById('history-search');
+ input.value = 'pending hybrid query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('pending hybrid query');
+
+ input.value = '';
+ input.dispatchEvent(new Event('input'));
+ pendingSearch.resolve([{
+ research_id: 'stale-hybrid-3299',
+ similarity: 99,
+ research_title: 'Stale hybrid result',
+ snippet: 'Must not repaint the cleared search',
+ }]);
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(document.querySelector('[data-id="stale-hybrid-3299"]')).toBeNull();
+ expect(document.getElementById('hybrid-loading-indicator')).toBeNull();
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(document.querySelector(`[data-id="${historyId}"]`)).not.toBeNull();
+ expect(document.querySelector('[data-id="stale-hybrid-3299"]')).toBeNull();
+ expect(document.getElementById('hybrid-loading-indicator')).toBeNull();
+});
+
+it('keeps the newest semantic results when an older request rejects late', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ let rejectOlder;
+ const older = new Promise((_resolve, reject) => {
+ rejectOlder = reject;
+ });
+ const newestResults = [{ research_id: 'newest-semantic-3299' }];
+ const renderSemanticResults = vi.fn((results, query) => {
+ document.getElementById('history-items').textContent =
+ `${query}: ${results[0].research_id}`;
+ });
+ window.HistorySearch = {
+ semanticSearchHistory: vi.fn()
+ .mockReturnValueOnce(older)
+ .mockResolvedValueOnce(newestResults),
+ renderSemanticResults,
+ };
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ document.querySelector('[data-mode="semantic"]').click();
+ const input = document.getElementById('history-search');
+
+ input.value = 'older query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(window.HistorySearch.semanticSearchHistory)
+ .toHaveBeenCalledWith('older query');
+
+ input.value = 'newest query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(renderSemanticResults).toHaveBeenCalledWith(
+ newestResults,
+ 'newest query',
+ );
+ expect(document.getElementById('history-items').textContent)
+ .toBe('newest query: newest-semantic-3299');
+
+ rejectOlder(new Error('late older failure'));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(document.getElementById('history-items').textContent)
+ .toBe('newest query: newest-semantic-3299');
+});
+
+it('keeps the current hybrid loading indicator when an older request rejects', async () => {
+ await installHistoryGlobals();
+ vi.useFakeTimers();
+ let rejectOlder;
+ let resolveNewest;
+ const older = new Promise((_resolve, reject) => {
+ rejectOlder = reject;
+ });
+ const newest = new Promise(resolve => {
+ resolveNewest = resolve;
+ });
+ window.HistorySearch = {
+ getSemanticCollectionId: vi.fn(() => 'history-collection'),
+ semanticSearchHistory: vi.fn()
+ .mockReturnValueOnce(older)
+ .mockReturnValueOnce(newest),
+ };
+ const fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ items: [],
+ }), { status: 200 }));
+ }
+ if (url === '/api/chat/sessions?status=all&limit=100&offset=0') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ sessions: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/components/history.js');
+ await vi.advanceTimersByTimeAsync(0);
+ const input = document.getElementById('history-search');
+ input.value = 'older hybrid';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+
+ input.value = 'newest hybrid';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(window.HistorySearch.semanticSearchHistory).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('hybrid-loading-indicator')).not.toBeNull();
+
+ rejectOlder(new Error('late older hybrid failure'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('hybrid-loading-indicator')).not.toBeNull();
+
+ resolveNewest([]);
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('hybrid-loading-indicator')).toBeNull();
+});
diff --git a/tests/js/components/history-search-polling-runtime.test.js b/tests/js/components/history-search-polling-runtime.test.js
new file mode 100644
index 0000000000..59457c2e78
--- /dev/null
+++ b/tests/js/components/history-search-polling-runtime.test.js
@@ -0,0 +1,322 @@
+/** Direct runtime coverage for history indexing polling and cache recovery. */
+
+const COLLECTION_URL = '/library/api/research-history/collection';
+const CONVERT_URL = '/library/api/research-history/convert-all';
+const STATUS_TEMPLATE = '/library/api/collections/{id}/index/status';
+const START_TEMPLATE = '/library/api/collections/{id}/index/start';
+const SEARCH_TEMPLATE = '/library/api/collections/{id}/search';
+
+const originalFetch = globalThis.fetch;
+const originalReadyState = Object.getOwnPropertyDescriptor(
+ document,
+ 'readyState',
+);
+const originalWindowState = new Map([
+ 'HistorySearch',
+ 'URLS',
+ 'URLBuilder',
+ 'ResearchStates',
+ 'api',
+].map(key => [key, {
+ owned: Object.hasOwn(window, key),
+ value: window[key],
+}]));
+
+let documentListeners = [];
+let windowListeners = [];
+
+function response(body, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: vi.fn().mockResolvedValue(body),
+ };
+}
+
+async function flushPromises(turns = 12) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+function renderFixture() {
+ document.body.innerHTML = `
+ <div id="semantic-panel-header" role="button" tabindex="0"
+ aria-expanded="true"></div>
+ <i id="semantic-panel-toggle" class="fas fa-chevron-down"></i>
+ <div id="semantic-panel-content"></div>
+ <span id="indexed-count"></span>
+ <span id="total-count"></span>
+ <button id="index-all-btn">Index All</button>
+ <section id="indexing-progress" style="display:none">
+ <div id="indexing-progress-bar"></div>
+ <div id="indexing-progress-text"></div>
+ </section>
+ `;
+}
+
+async function loadHistorySearch(fetchMock) {
+ globalThis.fetch = fetchMock;
+ await import('@js/components/history_search.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+ return window.HistorySearch;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ renderFixture();
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ documentListeners = [];
+ windowListeners = [];
+ const addDocumentListener = document.addEventListener.bind(document);
+ const addWindowListener = window.addEventListener.bind(window);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ vi.spyOn(window, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ windowListeners.push([type, listener, options]);
+ addWindowListener(type, listener, options);
+ },
+ );
+ window.URLS = {
+ LIBRARY_API: {
+ RESEARCH_HISTORY_COLLECTION: COLLECTION_URL,
+ RESEARCH_HISTORY_CONVERT_ALL: CONVERT_URL,
+ COLLECTION_INDEX_START: START_TEMPLATE,
+ COLLECTION_INDEX_STATUS: STATUS_TEMPLATE,
+ COLLECTION_SEARCH: SEARCH_TEMPLATE,
+ },
+ };
+ window.URLBuilder = {
+ build: (template, id) => template.replace('{id}', id),
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => status === 'failed',
+ isCancelled: status => status === 'cancelled',
+ };
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-history-runtime') };
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ for (const [type, listener, options] of windowListeners) {
+ window.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ windowListeners = [];
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ globalThis.fetch = originalFetch;
+ document.body.replaceChildren();
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+ originalWindowState.forEach((state, key) => {
+ if (state.owned) {
+ window[key] = state.value;
+ } else {
+ delete window[key];
+ }
+ });
+});
+
+it('resumes active indexing, renders terminal progress, and refreshes counts', async () => {
+ let collectionCalls = 0;
+ let statusCalls = 0;
+ const fetchMock = vi.fn(async url => {
+ if (url === COLLECTION_URL) {
+ collectionCalls += 1;
+ return response({
+ success: true,
+ collection_id: 'history-collection',
+ indexed_documents: collectionCalls === 1 ? 1 : 4,
+ total_documents: 4,
+ });
+ }
+ if (url === '/library/api/collections/history-collection/index/status') {
+ statusCalls += 1;
+ return response(statusCalls === 1 ? {
+ status: 'processing',
+ progress_current: 2,
+ progress_total: 4,
+ progress_message: 'Embedding research 2 of 4',
+ } : {
+ status: 'completed',
+ progress_current: 4,
+ progress_total: 4,
+ progress_message: 'History indexing complete',
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ await loadHistorySearch(fetchMock);
+
+ expect(document.getElementById('index-all-btn').disabled).toBe(true);
+ expect(document.getElementById('indexing-progress').style.display)
+ .toBe('block');
+ expect(document.getElementById('indexing-progress-bar').style.width)
+ .toBe('50%');
+ expect(document.getElementById('indexing-progress-text').textContent)
+ .toBe('Embedding research 2 of 4');
+
+ const header = document.getElementById('semantic-panel-header');
+ const keyboardToggle = new KeyboardEvent('keydown', {
+ key: ' ',
+ bubbles: true,
+ cancelable: true,
+ });
+ header.dispatchEvent(keyboardToggle);
+ expect(keyboardToggle.defaultPrevented).toBe(true);
+ expect(header.getAttribute('aria-expanded')).toBe('false');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(document.getElementById('indexing-progress-bar').style.width)
+ .toBe('100%');
+ expect(document.getElementById('indexing-progress-text').textContent)
+ .toBe('History indexing complete');
+
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(document.getElementById('indexing-progress').style.display)
+ .toBe('none');
+ expect(document.getElementById('indexed-count').textContent).toBe('4');
+ expect(document.getElementById('index-all-btn').disabled).toBe(true);
+ expect(document.getElementById('index-all-btn').textContent)
+ .toContain('All Indexed');
+ expect(collectionCalls).toBe(2);
+});
+
+it('stops polling and restores retry controls after five status failures', async () => {
+ let indexingStarted = false;
+ let failedStatusCalls = 0;
+ const fetchMock = vi.fn(async (url) => {
+ if (url === COLLECTION_URL) {
+ return response({
+ success: true,
+ collection_id: 'history-collection',
+ indexed_documents: 0,
+ total_documents: 3,
+ });
+ }
+ if (url === '/library/api/collections/history-collection/index/status') {
+ if (!indexingStarted) return response({ status: 'idle' });
+ failedStatusCalls += 1;
+ throw new Error('status connection lost');
+ }
+ if (url === CONVERT_URL) return response({ converted: 3 });
+ if (url === '/library/api/collections/history-collection/index/start') {
+ indexingStarted = true;
+ return response({ success: true });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ await loadHistorySearch(fetchMock);
+
+ document.getElementById('index-all-btn').click();
+ await flushPromises();
+ for (let attempt = 0; attempt < 5; attempt += 1) {
+ await vi.advanceTimersByTimeAsync(2000);
+ await flushPromises();
+ }
+
+ expect(failedStatusCalls).toBe(5);
+ expect(document.getElementById('indexing-progress-text').textContent)
+ .toBe('Lost connection to server. Please try again.');
+ expect(document.getElementById('indexing-progress-text').style.color)
+ .toBe('var(--error-color)');
+ const indexButton = document.getElementById('index-all-btn');
+ expect(indexButton.disabled).toBe(false);
+ expect(indexButton.textContent).toContain('Index All');
+
+ await vi.advanceTimersByTimeAsync(4000);
+ expect(failedStatusCalls).toBe(5);
+});
+
+it('invalidates a deleted collection cache before the next semantic search', async () => {
+ let collectionCalls = 0;
+ const fetchMock = vi.fn(async (url) => {
+ if (url === COLLECTION_URL) {
+ collectionCalls += 1;
+ return response({
+ success: true,
+ collection_id: collectionCalls === 1
+ ? 'deleted-collection'
+ : 'replacement-collection',
+ indexed_documents: 1,
+ total_documents: 1,
+ });
+ }
+ if (url === '/library/api/collections/deleted-collection/index/status') {
+ return response({ status: 'idle' });
+ }
+ if (url === '/library/api/collections/deleted-collection/search') {
+ return response({}, 404);
+ }
+ if (url === '/library/api/collections/replacement-collection/search') {
+ return response({
+ success: true,
+ results: [{ research_id: 'replacement-result' }],
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const historySearch = await loadHistorySearch(fetchMock);
+
+ await expect(historySearch.semanticSearchHistory('first query'))
+ .rejects.toThrow('Server returned 404');
+ expect(historySearch.getSemanticCollectionId()).toBeNull();
+
+ await expect(historySearch.semanticSearchHistory('retry query'))
+ .resolves.toEqual([{ research_id: 'replacement-result' }]);
+ expect(historySearch.getSemanticCollectionId())
+ .toBe('replacement-collection');
+ expect(collectionCalls).toBe(2);
+});
+
+it('shows a recoverable unavailable-collection state without starting work', async () => {
+ const fetchMock = vi.fn(async url => {
+ if (url === COLLECTION_URL) {
+ return response({
+ success: true,
+ collection_id: null,
+ indexed_documents: 0,
+ total_documents: 0,
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const historySearch = await loadHistorySearch(fetchMock);
+
+ await expect(historySearch.semanticSearchHistory('not indexed'))
+ .resolves.toEqual({ needsIndexing: true });
+ document.getElementById('index-all-btn').click();
+ await flushPromises();
+
+ expect(document.getElementById('indexing-progress-text').textContent)
+ .toBe('Collection not available. Please refresh the page.');
+ expect(document.getElementById('indexing-progress-text').style.color)
+ .toBe('var(--error-color)');
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock.mock.calls.every(([url]) => url === COLLECTION_URL))
+ .toBe(true);
+});
diff --git a/tests/js/components/history-search.test.js b/tests/js/components/history-search.test.js
index eb9f13e2a0..54d05193b4 100644
--- a/tests/js/components/history-search.test.js
+++ b/tests/js/components/history-search.test.js
@@ -77,6 +77,71 @@ describe('HistorySearch namespace', () => {
});
});
+describe('HistorySearch.triggerIndexing migration contract', () => {
+ afterEach(() => {
+ document.body.innerHTML = '';
+ });
+
+ it('serializes rapid starts and sends the migrated convert/index requests once', async () => {
+ const progressText = document.createElement('div');
+ progressText.id = 'indexing-progress-text';
+ document.body.appendChild(progressText);
+
+ let releaseConvert;
+ const convertPending = new Promise(resolve => {
+ releaseConvert = resolve;
+ });
+ globalThis.fetch = vi.fn((url) => {
+ if (url === '/library/api/research-history/convert-all') {
+ return convertPending;
+ }
+ if (url === '/library/api/collections/coll-1/index/start') {
+ // End this run at the start boundary so the module's private
+ // isIndexing flag is restored without leaving a poll timer.
+ return Promise.resolve({ ok: false, status: 503 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ const firstStart = HS.triggerIndexing();
+ const overlappingStart = HS.triggerIndexing();
+
+ await overlappingStart;
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+
+ releaseConvert({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({ converted: 4 }),
+ });
+ await firstStart;
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
+ const [convertUrl, convertOptions] = globalThis.fetch.mock.calls[0];
+ expect(convertUrl).toBe('/library/api/research-history/convert-all');
+ expect(convertOptions).toEqual({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'test-token',
+ },
+ body: JSON.stringify({}),
+ });
+
+ const [startUrl, startOptions] = globalThis.fetch.mock.calls[1];
+ expect(startUrl).toBe('/library/api/collections/coll-1/index/start');
+ expect(startOptions).toEqual({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'test-token',
+ },
+ body: JSON.stringify({ force_reindex: false }),
+ });
+ expect(progressText.textContent).toBe('Error: Server returned 503');
+ });
+});
+
describe('HistorySearch.semanticSearchHistory', () => {
it('returns [] for empty query', async () => {
const r = await HS.semanticSearchHistory('');
diff --git a/tests/js/components/library-search-ui.test.js b/tests/js/components/library-search-ui.test.js
new file mode 100644
index 0000000000..3c8a1e2ba7
--- /dev/null
+++ b/tests/js/components/library-search-ui.test.js
@@ -0,0 +1,473 @@
+/**
+ * Runtime coverage for the library page search controller.
+ *
+ * These tests drive the real mode menu and debounce path. The lower-level
+ * LibrarySearch module remains real as well, so assertions cover both the
+ * migrated collection-search route and what the user sees after it returns.
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const originalWindowState = new Map([
+ 'LibrarySearch',
+ 'SemanticSearch',
+ 'URLBuilder',
+ 'URLS',
+ 'api',
+ 'safeUpdateButton',
+].map(key => [key, {
+ owned: Object.hasOwn(window, key),
+ value: window[key],
+}]));
+
+function jsonResponse(body, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ json: vi.fn().mockResolvedValue(body),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function installFixture() {
+ document.body.innerHTML = `
+ <div id="library-search-notice" style="display: none"></div>
+ <button id="search-mode-btn"></button>
+ <div id="search-mode-menu">
+ <button class="dropdown-item active" data-mode="hybrid">Hybrid</button>
+ <button class="dropdown-item" data-mode="text">Text</button>
+ <button class="dropdown-item" data-mode="semantic">Semantic</button>
+ </div>
+ <input id="search-documents">
+ <select id="filter-collection">
+ <option value="">All collections</option>
+ <option value="collection-a">Collection A</option>
+ </select>
+ <select id="filter-domain">
+ <option value="">All domains</option>
+ <option value="example.com">example.com</option>
+ </select>
+ <select id="filter-research">
+ <option value="">All research</option>
+ </select>
+ <select id="filter-date">
+ <option value="">Any date</option>
+ </select>
+ <div id="documents-container">
+ <article class="ldr-document-card" data-doc-id="existing-doc"
+ data-domain="example.com" data-research="research-a">
+ <div class="card-header"></div>
+ <div class="card-body">Existing climate document</div>
+ </article>
+ </div>
+ <div id="semantic-results-container" style="display: none"></div>
+ `;
+}
+
+function semanticCardFactory() {
+ return vi.fn(result => {
+ const card = document.createElement('article');
+ card.className = 'ldr-semantic-result';
+ card.dataset.docId = result.document_id;
+ card.textContent = result.title || result.document_id;
+ return card;
+ });
+}
+
+async function installController({ collections, fetchImpl }) {
+ const createSemanticResultCard = semanticCardFactory();
+ window.SemanticSearch = {
+ createSemanticResultCard,
+ buildTieredResults: vi.fn(),
+ renderSnippet: vi.fn(),
+ };
+ window.URLBuilder = {
+ build: (template, id) => template.replace('{id}', id),
+ documentPage: id => `/library/document/${id}`,
+ };
+ window.URLS = {
+ LIBRARY_API: {
+ COLLECTION_SEARCH: '/library/api/collections/{id}/search',
+ },
+ };
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-library-test') };
+ window.safeUpdateButton = vi.fn();
+ vi.stubGlobal('safeFetch', vi.fn(fetchImpl));
+
+ await import('@js/components/library_search.js');
+ window.LibrarySearch.initLibrarySearch(null, collections);
+ await import('@js/components/library_search_ui.js');
+
+ return {
+ createSemanticResultCard,
+ safeFetch: globalThis.safeFetch,
+ };
+}
+
+function selectMode(mode) {
+ document.querySelector(`[data-mode="${mode}"]`).click();
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ installFixture();
+});
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ originalWindowState.forEach((state, key) => {
+ if (state.owned) {
+ window[key] = state.value;
+ } else {
+ delete window[key];
+ }
+ });
+});
+
+describe('library search UI runtime contracts', () => {
+ it('posts a selected-collection semantic search to the migrated route and renders its result', async () => {
+ const { createSemanticResultCard, safeFetch } = await installController({
+ collections: [{ id: 'collection-a', indexed_document_count: 1 }],
+ fetchImpl: () => Promise.resolve(jsonResponse({
+ success: true,
+ results: [{
+ document_id: 'semantic-doc',
+ title: 'Climate evidence',
+ similarity: 91,
+ }],
+ })),
+ });
+
+ document.getElementById('filter-collection').value = 'collection-a';
+ document.getElementById('search-documents').value = 'climate';
+ selectMode('semantic');
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(safeFetch).toHaveBeenCalledTimes(1);
+ expect(safeFetch).toHaveBeenCalledWith(
+ '/library/api/collections/collection-a/search',
+ expect.objectContaining({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-library-test',
+ },
+ body: JSON.stringify({ query: 'climate', limit: 20 }),
+ }),
+ );
+ expect(createSemanticResultCard).toHaveBeenCalledWith(
+ expect.objectContaining({ document_id: 'semantic-doc' }),
+ expect.any(Object),
+ 'climate',
+ );
+ expect(document.getElementById('semantic-results-container').textContent)
+ .toContain('Climate evidence');
+ expect(document.getElementById('documents-container').style.display).toBe('none');
+ });
+
+ it('fans out across indexed collections, deduplicates, and applies the active domain filter', async () => {
+ const responseByCollection = {
+ 'collection-a': {
+ success: true,
+ results: [
+ { document_id: 'shared', title: 'Older match', similarity: 70, domain: 'example.com' },
+ { document_id: 'other-domain', title: 'Wrong domain', similarity: 99, domain: 'other.test' },
+ ],
+ },
+ 'collection-b': {
+ success: true,
+ results: [
+ { document_id: 'shared', title: 'Best match', similarity: 94, domain: 'example.com' },
+ { document_id: 'second', title: 'Second match', similarity: 80, domain: 'example.com' },
+ ],
+ },
+ };
+ const { createSemanticResultCard, safeFetch } = await installController({
+ collections: [
+ { id: 'collection-a', indexed_document_count: 2 },
+ { id: 'collection-b', indexed_document_count: 2 },
+ { id: 'not-indexed', indexed_document_count: 0 },
+ ],
+ fetchImpl: url => {
+ const collectionId = String(url).split('/').at(-2);
+ return Promise.resolve(jsonResponse(responseByCollection[collectionId]));
+ },
+ });
+
+ document.getElementById('filter-domain').value = 'example.com';
+ document.getElementById('search-documents').value = 'evidence';
+ selectMode('semantic');
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(safeFetch.mock.calls.map(([url]) => url)).toEqual([
+ '/library/api/collections/collection-a/search',
+ '/library/api/collections/collection-b/search',
+ ]);
+ expect(createSemanticResultCard).toHaveBeenCalledTimes(2);
+ expect(createSemanticResultCard.mock.calls.map(([result]) => [
+ result.document_id,
+ result.title,
+ ])).toEqual([
+ ['shared', 'Best match'],
+ ['second', 'Second match'],
+ ]);
+ expect(document.getElementById('library-search-notice').textContent)
+ .toContain('Searching across 2 indexed collections');
+ });
+
+ it('does not let a late semantic response overwrite the UI after switching back to text mode', async () => {
+ let resolveSearch;
+ const pendingSearch = new Promise(resolve => {
+ resolveSearch = resolve;
+ });
+ const { createSemanticResultCard } = await installController({
+ collections: [{ id: 'collection-a', indexed_document_count: 1 }],
+ fetchImpl: () => pendingSearch,
+ });
+
+ document.getElementById('filter-collection').value = 'collection-a';
+ document.getElementById('search-documents').value = 'climate';
+ selectMode('semantic');
+ await vi.advanceTimersByTimeAsync(500);
+
+ selectMode('text');
+ resolveSearch(jsonResponse({
+ success: true,
+ results: [{ document_id: 'late-result', title: 'Late result', similarity: 99 }],
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(createSemanticResultCard).not.toHaveBeenCalled();
+ expect(document.getElementById('semantic-results-container').style.display).toBe('none');
+ expect(document.getElementById('documents-container').style.display).toBe('grid');
+ expect(document.getElementById('semantic-results-container').textContent)
+ .not.toContain('Late result');
+ });
+
+ it('renders and then clears hybrid badges, snippets, and content-only results', async () => {
+ const { createSemanticResultCard, safeFetch } = await installController({
+ collections: [{ id: 'collection-a', indexed_document_count: 2 }],
+ fetchImpl: () => Promise.resolve(jsonResponse({
+ success: true,
+ results: [
+ {
+ document_id: 'existing-doc',
+ title: 'Existing climate document',
+ similarity: 93,
+ snippet: 'Matched climate evidence',
+ },
+ {
+ document_id: 'content-only',
+ title: 'Content-only evidence',
+ similarity: 81,
+ },
+ ],
+ })),
+ });
+ window.SemanticSearch.renderSnippet.mockReturnValue(
+ '<mark>Matched climate evidence</mark>',
+ );
+ window.SemanticSearch.buildTieredResults.mockImplementation(
+ (textResults, semanticResults) => ({
+ tier1: [{
+ historyItem: textResults[0],
+ semanticMatch: semanticResults[0],
+ }],
+ tier2: [],
+ tier3: [{ semanticResult: semanticResults[1] }],
+ }),
+ );
+ document.getElementById('filter-collection').value = 'collection-a';
+ const input = document.getElementById('search-documents');
+ input.value = 'climate';
+
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+
+ expect(safeFetch).toHaveBeenCalledWith(
+ '/library/api/collections/collection-a/search',
+ expect.any(Object),
+ );
+ expect(window.SemanticSearch.buildTieredResults).toHaveBeenCalledOnce();
+ const existingCard = document.querySelector(
+ '[data-doc-id="existing-doc"]',
+ );
+ expect(existingCard.querySelector('[data-similarity]').textContent)
+ .toContain('93% match');
+ expect(existingCard.querySelector('.ldr-library-snippet').textContent)
+ .toContain('Matched climate evidence');
+ expect(createSemanticResultCard).toHaveBeenCalledWith(
+ expect.objectContaining({ document_id: 'content-only' }),
+ expect.any(Object),
+ 'climate',
+ );
+ expect(document.getElementById('documents-container').textContent)
+ .toContain('Content-only evidence');
+
+ input.value = '';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(existingCard.querySelector('[data-similarity]')).toBeNull();
+ expect(existingCard.querySelector('.ldr-library-snippet')).toBeNull();
+ expect(document.querySelector('.ldr-semantic-result')).toBeNull();
+ expect(document.querySelector('.ldr-hybrid-divider')).toBeNull();
+ expect(document.getElementById('documents-container').firstElementChild)
+ .toBe(existingCard);
+ });
+
+ it('keeps the newest hybrid query when overlapping searches resolve out of order', async () => {
+ const older = deferred();
+ const newer = deferred();
+ const { createSemanticResultCard, safeFetch } = await installController({
+ collections: [{ id: 'collection-a', indexed_document_count: 2 }],
+ fetchImpl: vi.fn()
+ .mockReturnValueOnce(older.promise)
+ .mockReturnValueOnce(newer.promise),
+ });
+ window.SemanticSearch.buildTieredResults.mockImplementation(
+ (_textResults, semanticResults) => ({
+ tier1: [],
+ tier2: [],
+ tier3: semanticResults.map(semanticResult => ({
+ semanticResult,
+ })),
+ }),
+ );
+ document.getElementById('filter-collection').value = 'collection-a';
+ const input = document.getElementById('search-documents');
+
+ input.value = 'older query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ input.value = 'newer query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+ expect(safeFetch).toHaveBeenCalledTimes(2);
+
+ newer.resolve(jsonResponse({
+ success: true,
+ results: [{
+ document_id: 'newer-result',
+ title: 'Newest result',
+ similarity: 95,
+ }],
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('documents-container').textContent)
+ .toContain('Newest result');
+
+ older.resolve(jsonResponse({
+ success: true,
+ results: [{
+ document_id: 'older-result',
+ title: 'Stale result',
+ similarity: 99,
+ }],
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(createSemanticResultCard.mock.calls.map(([result]) => (
+ result.document_id
+ ))).toEqual(['newer-result']);
+ expect(document.getElementById('documents-container').textContent)
+ .not.toContain('Stale result');
+ });
+
+ it('explains why semantic search is unavailable without indexed collections', async () => {
+ const { safeFetch } = await installController({
+ collections: [{ id: 'not-indexed', indexed_document_count: 0 }],
+ fetchImpl: vi.fn(),
+ });
+ document.getElementById('search-documents').value = 'evidence';
+
+ selectMode('semantic');
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(safeFetch).not.toHaveBeenCalled();
+ const notice = document.getElementById('library-search-notice');
+ expect(notice.style.display).toBe('block');
+ expect(notice.textContent).toContain(
+ 'No collections have been indexed yet',
+ );
+ expect(notice.querySelector('a').getAttribute('href'))
+ .toBe('/library/collections');
+ expect(document.getElementById('semantic-results-container').textContent)
+ .toBe('');
+ });
+
+ it('recovers the semantic results surface after a request failure', async () => {
+ const fetchImpl = vi.fn()
+ .mockRejectedValueOnce(new Error('search backend unavailable'))
+ .mockResolvedValueOnce(jsonResponse({
+ success: true,
+ results: [{
+ document_id: 'recovered-result',
+ title: 'Recovered evidence',
+ similarity: 88,
+ }],
+ }));
+ const { createSemanticResultCard } = await installController({
+ collections: [{ id: 'collection-a', indexed_document_count: 1 }],
+ fetchImpl,
+ });
+ document.getElementById('filter-collection').value = 'collection-a';
+ const input = document.getElementById('search-documents');
+ input.value = 'first attempt';
+
+ selectMode('semantic');
+ await vi.advanceTimersByTimeAsync(500);
+ expect(document.getElementById('semantic-results-container').textContent)
+ .toContain('Search failed. Please try again.');
+
+ input.value = 'retry query';
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(750);
+
+ expect(fetchImpl).toHaveBeenCalledTimes(2);
+ expect(createSemanticResultCard).toHaveBeenCalledWith(
+ expect.objectContaining({ document_id: 'recovered-result' }),
+ expect.any(Object),
+ 'retry query',
+ );
+ expect(document.getElementById('semantic-results-container').textContent)
+ .toContain('Recovered evidence');
+ });
+
+ it('filters visible cards locally in text mode', async () => {
+ const secondCard = document.createElement('article');
+ secondCard.className = 'ldr-document-card';
+ secondCard.dataset.docId = 'other-doc';
+ secondCard.dataset.domain = 'other.test';
+ secondCard.dataset.research = 'research-b';
+ secondCard.textContent = 'Unrelated economics paper';
+ document.getElementById('documents-container').appendChild(secondCard);
+ await installController({
+ collections: [],
+ fetchImpl: vi.fn(),
+ });
+ selectMode('text');
+ const input = document.getElementById('search-documents');
+ input.value = 'climate';
+
+ input.dispatchEvent(new Event('input'));
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(document.querySelector('[data-doc-id="existing-doc"]').style.display)
+ .toBe('');
+ expect(secondCard.style.display).toBe('none');
+ expect(document.getElementById('semantic-results-container').style.display)
+ .toBe('none');
+ });
+});
diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.js
index 830c96b5e2..64c0a71572 100644
--- a/tests/js/components/logpanel.test.js
+++ b/tests/js/components/logpanel.test.js
@@ -480,8 +480,9 @@ describe('addLog / loadLogs — ordering invariants', () => {
// Explicit timeout: this test is genuinely heavy, not hung. 501 inserts
// each run addLogEntryToPanel's full-container querySelectorAll scans
// (dedup window, chronological insert position, prune check) — O(n²)
- // DOM work that takes ~2.6-2.9s in happy-dom on a dev machine, so the
- // 5s vitest default leaves no headroom under parallel CI load. #4304
+ // DOM work that takes about 10s in the current happy-dom stack even in
+ // isolation and can approach 20s under full-suite worker contention.
+ // Keep enough headroom for the dedicated migration Vitest gate. #4304
// already fixed the *timer* pileup (501 real setTimeout(autoscroll, 0)
// tasks) by faking all timers; what remains is honest compute, so a
// bigger budget is the right lever now — unlike #4299, which proposed
@@ -495,7 +496,7 @@ describe('addLog / loadLogs — ordering invariants', () => {
// the part the priority order actually changes -- is exercised by
// the `pruneToCap -- per-category ordered prune` describe block
// lower in this file.
- it('drops the oldest info entry when the cap is exceeded by info-only inserts', { timeout: 20000 }, () => {
+ it('drops the oldest info entry when the cap is exceeded by info-only inserts', { timeout: 40000 }, () => {
const container = document.getElementById('console-log-container');
// One insert over the cap. The live-insert prune in
@@ -1385,15 +1386,16 @@ describe('per-category counters', () => {
// MAX_LOG_ENTRIES cap (501 inserts) to exercise the live prune path.
// Each addLog -> addLogEntryToPanel queues a setTimeout(autoscroll, 0)
// (logpanel.js:1138) AND runs a full-container querySelectorAll
- // dedup/insert/scan -- O(n^2) DOM work (~2.6-2.9s in happy-dom). Without
- // faked timers the 501 real setTimeout tasks pile onto the timer queue
- // and blow the 5s default. Same flake + same fix as the `ordering
+ // dedup/insert/scan -- O(n^2) DOM work (about 10s in isolation with the
+ // current happy-dom stack, and close to 20s under full-suite contention).
+ // Without faked timers the 501 real setTimeout tasks pile onto the timer
+ // queue. Same flake + same fix as the `ordering
// invariants` prune test (see release notes 1.8.1 / #4304). Faking timers
// here rather than in a beforeEach because the batch-load test below
// depends on a real setTimeout(resolve, 10). The assertions read DOM
// contents only, so leaving the autoscroll timers queued (unflushed) is
// fine.
- it('decrements the matching category count when the cap prunes an entry', { timeout: 20000 }, () => {
+ it('decrements the matching category count when the cap prunes an entry', { timeout: 40000 }, () => {
vi.useFakeTimers();
// Stub fetch so initialize()'s fire-and-forget loadLogs (kicked off
// inside setupPanelDom) is hermetic. happy-dom ships a real native
diff --git a/tests/js/components/notes-shared.test.js b/tests/js/components/notes-shared.test.js
index 1b039d746c..7af3818cf8 100644
--- a/tests/js/components/notes-shared.test.js
+++ b/tests/js/components/notes-shared.test.js
@@ -69,6 +69,19 @@ describe('NotesShared.postJson', () => {
);
await expect(NotesShared.postJson('/notes/api/x')).rejects.toThrow('Server returned 500');
});
+
+ it('surfaces a FastAPI detail response', async () => {
+ globalThis.safeFetch = vi.fn(() =>
+ Promise.resolve({
+ ok: false,
+ status: 409,
+ json: () => Promise.resolve({ detail: 'note is locked' }),
+ })
+ );
+
+ await expect(NotesShared.postJson('/notes/api/x'))
+ .rejects.toThrow('note is locked');
+ });
});
describe('NotesShared.toast', () => {
@@ -84,3 +97,37 @@ describe('NotesShared.toast', () => {
expect(() => NotesShared.toast('x')).not.toThrow();
});
});
+
+describe('NotesShared.renderNoteRow', () => {
+ it('encodes the note route and renders an inert Markdown preview', () => {
+ const stripMarkdownToText = vi.spyOn(
+ window.formatting,
+ 'stripMarkdownToText',
+ ).mockReturnValue('<img src=x onerror="window.pwned=true">');
+
+ const row = NotesShared.renderNoteRow({
+ id: 'note /?#',
+ title: '<svg onload="window.pwned=true">',
+ content_preview: '**unsafe-looking source**',
+ });
+
+ expect(row.getAttribute('href')).toBe('/notes/note%20%2F%3F%23');
+ expect(stripMarkdownToText)
+ .toHaveBeenCalledWith('**unsafe-looking source**');
+ expect(row.querySelector('.ldr-research-note-title').textContent)
+ .toBe('<svg onload="window.pwned=true">');
+ expect(row.querySelector('.ldr-research-note-preview').textContent)
+ .toBe('<img src=x onerror="window.pwned=true">');
+ expect(row.querySelector('svg, img')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ stripMarkdownToText.mockRestore();
+ });
+
+ it('uses the title fallback and omits an empty preview', () => {
+ const row = NotesShared.renderNoteRow({ id: 'note-2' });
+
+ expect(row.querySelector('.ldr-research-note-title').textContent)
+ .toBe('Untitled note');
+ expect(row.querySelector('.ldr-research-note-preview')).toBeNull();
+ });
+});
diff --git a/tests/js/components/progress-agent-phase-runtime.test.js b/tests/js/components/progress-agent-phase-runtime.test.js
new file mode 100644
index 0000000000..efd907a192
--- /dev/null
+++ b/tests/js/components/progress-agent-phase-runtime.test.js
@@ -0,0 +1,123 @@
+/** Additional runtime coverage for FastAPI agent-phase progress frames. */
+
+let progressComponent;
+
+beforeAll(async () => {
+ await import('@js/components/progress.js');
+ progressComponent = window.progressComponent;
+});
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <section id="agent-thinking-panel" style="display: none">
+ <div id="agent-thinking-content"></div>
+ </section>
+ `;
+});
+
+afterEach(() => {
+ document.body.replaceChildren();
+ delete window.__agentPhaseXss;
+});
+
+const phaseCases = [
+ [
+ { phase: 'react', iteration: 3, message: 'Planning the next cycle' },
+ 'ldr-info',
+ 'CYCLE 3',
+ 'Planning the next cycle',
+ ],
+ [
+ { phase: 'thought', thought: 'Compare the primary sources' },
+ 'ldr-thought',
+ '💭 THINKING',
+ 'Compare the primary sources',
+ ],
+ [
+ { phase: 'error', error: 'Provider authentication failed' },
+ 'ldr-error',
+ '❌ ERROR',
+ 'Provider authentication failed',
+ ],
+ [
+ { phase: 'synthesis' },
+ 'ldr-info',
+ '📝 SYNTHESIZING',
+ 'Synthesizing findings with citations...',
+ ],
+ [
+ { phase: 'sub_research', message: 'Checking a disputed claim' },
+ 'ldr-action',
+ '🔬 SUB-RESEARCH',
+ 'Checking a disputed claim',
+ ],
+ [
+ { phase: 'init' },
+ 'ldr-info',
+ '🚀 STARTING',
+ 'Initializing research...',
+ ],
+ [
+ { phase: 'complete', message: 'Report assembled' },
+ 'ldr-info',
+ '✅ COMPLETE',
+ 'Report assembled',
+ ],
+];
+
+it.each(phaseCases)(
+ 'renders the $phase frame with its semantic label and content',
+ (frame, expectedClass, expectedLabel, expectedContent) => {
+ progressComponent.updateAgentThinking(frame);
+
+ const panel = document.getElementById('agent-thinking-panel');
+ const step = panel.querySelector('.ldr-agent-step');
+ expect(panel.style.display).toBe('block');
+ expect(step.classList).toContain(expectedClass);
+ expect(step.querySelector('.ldr-agent-step-label').textContent)
+ .toBe(expectedLabel);
+ expect(step.querySelector('.ldr-agent-step-content').textContent)
+ .toBe(expectedContent);
+ },
+);
+
+it('serializes non-query tool arguments when the frame has no display message', () => {
+ progressComponent.updateAgentThinking({
+ phase: 'tool_call',
+ tool: 'fetch_document',
+ arguments: {
+ document_id: 'doc-3299',
+ include_metadata: true,
+ },
+ });
+
+ expect(document.querySelector('.ldr-agent-step-content').textContent)
+ .toBe(
+ 'Using fetch_document\nArgs: {\n'
+ + ' "document_id": "doc-3299",\n'
+ + ' "include_metadata": true\n}',
+ );
+});
+
+it('keeps hostile phase content inert in the agent panel', () => {
+ const payload = '</div><img src=x onerror="window.__agentPhaseXss=true">';
+
+ progressComponent.updateAgentThinking({
+ phase: 'thought',
+ thought: payload,
+ });
+
+ const content = document.querySelector('.ldr-agent-step-content');
+ expect(content.textContent).toBe(payload);
+ expect(content.querySelector('img')).toBeNull();
+ expect(window.__agentPhaseXss).toBeUndefined();
+});
+
+it('ignores an agent frame when the optional panel is absent', () => {
+ document.body.replaceChildren();
+
+ expect(() => progressComponent.updateAgentThinking({
+ phase: 'init',
+ message: 'No panel on this layout',
+ })).not.toThrow();
+});
diff --git a/tests/js/components/progress-cancel-ownership.test.js b/tests/js/components/progress-cancel-ownership.test.js
new file mode 100644
index 0000000000..6af6a6bf2b
--- /dev/null
+++ b/tests/js/components/progress-cancel-ownership.test.js
@@ -0,0 +1,139 @@
+/** Terminal ownership after cancelling an active progress page. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'progress-cancel-owner-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+it('keeps Cancelled owned against a stale poll, socket frame, and reconnect', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="25">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator">In progress</div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn">Cancel Research</button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed', 'failed', 'error', 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+
+ let progressCallback;
+ let reconnectCallback;
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ unsubscribeFromResearch: vi.fn(),
+ onReconnect: vi.fn(callback => {
+ reconnectCallback = callback;
+ }),
+ isUsingPolling: vi.fn(() => true),
+ };
+ const statusMock = vi.fn().mockResolvedValue({
+ status: 'in_progress',
+ progress: 25,
+ current_task: 'Initial task',
+ });
+ window.api = {
+ getResearchStatus: statusMock,
+ terminateResearch: vi.fn().mockResolvedValue({ status: 'success' }),
+ };
+ window.ui = {
+ showMessage: vi.fn(),
+ showError: vi.fn(),
+ };
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+
+ try {
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(statusMock).toHaveBeenCalledTimes(2);
+ expect(progressCallback).toBeTypeOf('function');
+ expect(reconnectCallback).toBeTypeOf('function');
+ expect(document.getElementById('progress-bar').style.width)
+ .toBe('25%');
+ });
+
+ const stalePoll = deferred();
+ statusMock.mockImplementationOnce(() => stalePoll.promise);
+ const stalePollRequest = window.progressComponent.checkProgress();
+ await vi.waitFor(() => expect(statusMock).toHaveBeenCalledTimes(3));
+
+ const intervalClearsBeforeCancel = clearIntervalSpy.mock.calls.length;
+ document.getElementById('cancel-research-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(window.api.terminateResearch).toHaveBeenCalledWith(RESEARCH_ID);
+ expect(document.getElementById('status-text').textContent)
+ .toBe('Cancelled');
+ expect(window.socket.unsubscribeFromResearch)
+ .toHaveBeenCalledWith(RESEARCH_ID);
+ expect(clearIntervalSpy.mock.calls.length)
+ .toBeGreaterThan(intervalClearsBeforeCancel);
+
+ stalePoll.resolve({
+ status: 'in_progress',
+ progress: 70,
+ current_task: 'Late HTTP task',
+ });
+ await stalePollRequest;
+ progressCallback({
+ status: 'in_progress',
+ progress: 90,
+ current_task: 'Late socket task',
+ });
+ reconnectCallback();
+
+ expect(document.getElementById('status-text').textContent)
+ .toBe('Cancelled');
+ expect(document.getElementById('progress-bar').style.width).toBe('25%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Initial task');
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledOnce();
+ expect(statusMock).toHaveBeenCalledTimes(3);
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.socket;
+ delete window.ui;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+ }
+});
diff --git a/tests/js/components/progress-cancellation-runtime.test.js b/tests/js/components/progress-cancellation-runtime.test.js
new file mode 100644
index 0000000000..4e9804f37f
--- /dev/null
+++ b/tests/js/components/progress-cancellation-runtime.test.js
@@ -0,0 +1,173 @@
+/** Direct browser-runtime contracts for progress-page research cancellation. */
+
+import '@js/config/urls.js';
+import '@js/security/url-validator.js';
+
+const RESEARCH_ID = 'progress-cancel-3299';
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="25">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator">In progress</div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn">
+ <i class="fas fa-stop-circle"></i> Cancel Research
+ </button>
+ <a id="view-results-btn" style="display:none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+ window.api = {
+ getResearchStatus: vi.fn().mockResolvedValue({
+ status: 'in_progress',
+ progress: 25,
+ }),
+ terminateResearch: vi.fn().mockResolvedValue({ status: 'success' }),
+ };
+ window.ui = {
+ showMessage: vi.fn(),
+ showError: vi.fn(),
+ };
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLValidator', window.URLValidator);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: async () => ({ status: 'success', data: { overview: { truncation_occurred: false } } }),
+ }));
+
+ // Fresh page state for each case; do not retain prior terminal flags or
+ // accumulate DOMContentLoaded handlers across shuffled cases.
+ let initialize;
+ const addListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation((type, callback, options) => {
+ if (type === 'DOMContentLoaded') initialize = callback;
+ else addListener(type, callback, options);
+ });
+ await import('@js/components/progress.js');
+ initialize();
+ await vi.advanceTimersByTimeAsync(0);
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.socket;
+ delete window.ui;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ document.body.replaceChildren();
+});
+
+it('renders the cancelled state after the authenticated API call succeeds', async () => {
+ document.getElementById('cancel-research-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(confirm).toHaveBeenCalledWith(
+ 'Are you sure you want to cancel this research?',
+ );
+ expect(window.api.terminateResearch).toHaveBeenCalledWith(RESEARCH_ID);
+ expect(document.getElementById('status-text').textContent).toBe('Cancelled');
+ expect(document.getElementById('status-text').classList)
+ .toContain('ldr-status-cancelled');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+ const homeLink = document.getElementById('view-results-btn');
+ expect(homeLink.textContent).toBe('Start New Research');
+ expect(homeLink.getAttribute('href')).toBe('/');
+ expect(homeLink.style.display).toBe('inline-block');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Research has been cancelled.',
+ );
+ expect(window.ui.showError).not.toHaveBeenCalled();
+});
+
+it('restores the cancel control and reports an API failure', async () => {
+ window.api.terminateResearch.mockRejectedValueOnce(
+ new Error('FastAPI cancellation unavailable'),
+ );
+
+ const cancelButton = document.getElementById('cancel-research-btn');
+ cancelButton.click();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(window.api.terminateResearch).toHaveBeenCalledWith(RESEARCH_ID);
+ expect(cancelButton.disabled).toBe(false);
+ expect(cancelButton.textContent).toContain('Cancel Research');
+ expect(cancelButton.style.display).not.toBe('none');
+ expect(document.getElementById('status-text').textContent)
+ .toBe('In progress');
+ expect(window.ui.showError).toHaveBeenCalledWith(
+ 'Failed to cancel research. Please try again.',
+ );
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+});
+
+it.each(['success', 'failure'])('keeps completion when the pending Cancel ends in %s', async outcome => {
+ let settle;
+ window.api.terminateResearch.mockReturnValueOnce(new Promise((resolve, reject) => {
+ settle = outcome === 'success' ? resolve : reject;
+ }));
+ document.getElementById('cancel-research-btn').click();
+ const progressCallback = window.socket.subscribeToResearch.mock.calls[0][1];
+ progressCallback({ status: 'completed', progress: 100 });
+ const resultLink = document.getElementById('view-results-btn').getAttribute('href');
+ expect(resultLink).toBe(`/results/${RESEARCH_ID}`);
+ settle(outcome === 'success'
+ ? { status: 'success', research_status: 'completed' }
+ : new Error('late cancellation response failed'));
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('status-text').textContent).not.toBe('Cancelled');
+ expect(document.getElementById('view-results-btn').getAttribute('href')).toBe(resultLink);
+ expect(document.getElementById('cancel-research-btn').style.display).toBe('none');
+ expect(window.ui.showError).not.toHaveBeenCalled();
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith('Research has been cancelled.');
+});
+
+it('honors already-completed termination responses without a final socket frame', async () => {
+ window.api.terminateResearch.mockResolvedValueOnce({
+ status: 'success', research_status: 'completed', message: 'Research already completed',
+ });
+ document.getElementById('cancel-research-btn').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('view-results-btn').getAttribute('href')).toBe(`/results/${RESEARCH_ID}`);
+ expect(document.getElementById('status-text').textContent).not.toBe('Cancelled');
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith('Research has been cancelled.');
+});
diff --git a/tests/js/components/progress-fallback-runtime.test.js b/tests/js/components/progress-fallback-runtime.test.js
new file mode 100644
index 0000000000..5a98e1a08f
--- /dev/null
+++ b/tests/js/components/progress-fallback-runtime.test.js
@@ -0,0 +1,177 @@
+/** Direct contracts for progress-page bootstrap degradation paths. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'fallback/research-3299';
+let registeredWindowListeners = [];
+
+async function importAndInitializeProgress() {
+ let initializeProgress;
+ const originalDocumentAdd = document.addEventListener.bind(document);
+ const originalWindowAdd = window.addEventListener.bind(window);
+ const documentAddSpy = vi.spyOn(document, 'addEventListener')
+ .mockImplementation((type, listener, options) => {
+ if (type === 'DOMContentLoaded') {
+ initializeProgress = listener;
+ return;
+ }
+ originalDocumentAdd(type, listener, options);
+ });
+ const windowAddSpy = vi.spyOn(window, 'addEventListener')
+ .mockImplementation((type, listener, options) => {
+ registeredWindowListeners.push([type, listener, options]);
+ originalWindowAdd(type, listener, options);
+ });
+
+ try {
+ await import('@js/components/progress.js');
+ } finally {
+ documentAddSpy.mockRestore();
+ windowAddSpy.mockRestore();
+ }
+
+ expect(initializeProgress).toEqual(expect.any(Function));
+ initializeProgress();
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ registeredWindowListeners = [];
+ document.body.innerHTML = `
+ <main>
+ <div class="ldr-progress-container"></div>
+ <div class="ldr-status-container"></div>
+ <div class="ldr-task-container"></div>
+ <a id="owned-navigation" href="/history">History</a>
+ </main>
+ `;
+
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed', 'failed', 'error', 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+});
+
+afterEach(() => {
+ registeredWindowListeners.forEach(([type, listener, options]) => {
+ window.removeEventListener(type, listener, options);
+ });
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.socket;
+ delete window.pollIntervals;
+ delete window.addConsoleLog;
+ delete window.progressComponent;
+ delete window.showNotification;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+});
+
+it('creates required UI and starts one owned poll when socket setup throws', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+
+ const getResearchStatus = vi.fn().mockResolvedValue({
+ status: 'in_progress',
+ progress: 17,
+ current_task: 'Migrating realtime state',
+ });
+ window.api = { getResearchStatus };
+ window.addConsoleLog = vi.fn();
+ window.socket = {
+ subscribeToResearch: vi.fn(() => {
+ throw new Error('socket bootstrap failed');
+ }),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => true),
+ };
+ const intervalSpy = vi.spyOn(globalThis, 'setInterval');
+
+ await importAndInitializeProgress();
+ await vi.waitFor(() => expect(getResearchStatus).toHaveBeenCalledTimes(2));
+
+ const progress = document.getElementById('progress-bar');
+ expect(progress).not.toBeNull();
+ expect(progress.parentElement.getAttribute('role')).toBe('progressbar');
+ expect(progress.parentElement.getAttribute('aria-valuenow')).toBe('17');
+ expect(document.getElementById('progress-percentage').textContent).toBe('17%');
+ // The page intentionally keeps the specific task instead of replacing it
+ // with the generic "In Progress" status label.
+ expect(document.getElementById('status-text').textContent).toBe('Initializing');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Migrating realtime state');
+ expect(intervalSpy.mock.calls.filter(([, delay]) => delay === 3000))
+ .toHaveLength(1);
+ expect(window.addConsoleLog).toHaveBeenCalledWith(
+ 'Using polling for research updates instead of WebSockets',
+ 'info',
+ );
+
+ const websocketError = new window.ErrorEvent('error', {
+ message: 'Invalid WebSocket frame header',
+ cancelable: true,
+ });
+ window.dispatchEvent(websocketError);
+ expect(websocketError.defaultPrevented).toBe(true);
+});
+
+it('cleans service-owned polling before preserving a navigation callback', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ window.api = {
+ getResearchStatus: vi.fn().mockResolvedValue({
+ status: 'in_progress',
+ progress: 1,
+ }),
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => true),
+ };
+ const originalNavigation = vi.fn(() => false);
+ document.getElementById('owned-navigation').onclick = originalNavigation;
+ const pollingTimer = setInterval(() => {}, 60000);
+ window.pollIntervals = { [RESEARCH_ID]: pollingTimer };
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+
+ await importAndInitializeProgress();
+ await vi.waitFor(() => expect(window.api.getResearchStatus).toHaveBeenCalled());
+
+ const navigation = document.getElementById('owned-navigation');
+ const click = new MouseEvent('click', { bubbles: true, cancelable: true });
+ navigation.dispatchEvent(click);
+
+ expect(clearIntervalSpy).toHaveBeenCalledWith(pollingTimer);
+ expect(originalNavigation).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/components/progress-initial-cancelled-ownership.test.js b/tests/js/components/progress-initial-cancelled-ownership.test.js
new file mode 100644
index 0000000000..1bf7d6f2bb
--- /dev/null
+++ b/tests/js/components/progress-initial-cancelled-ownership.test.js
@@ -0,0 +1,151 @@
+/** Initial user-termination ownership for the progress page bootstrap. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'progress-initial-suspended-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+async function flushPromises(turns = 8) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+beforeEach(async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar" class="bg-primary"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ SUSPENDED: 'suspended',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ 'suspended',
+ ]);
+ await import('@js/config/constants.js');
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ delete window.api;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.RESEARCH_TERMINAL_STATES;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('owns an initial FastAPI suspended status over older HTTP and later socket updates', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('URLValidator', {
+ safeAssign: vi.fn((target, property, value) => {
+ target[property] = value;
+ }),
+ });
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+
+ const olderPoll = deferred();
+ const getResearchStatus = vi.fn()
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockResolvedValueOnce({
+ status: 'suspended',
+ progress: 64,
+ completed_at: null,
+ report_path: null,
+ metadata: {},
+ });
+ window.api = { getResearchStatus };
+
+ let progressCallback;
+ let reconnectCallback;
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ onReconnect: vi.fn(callback => {
+ reconnectCallback = callback;
+ }),
+ isUsingPolling: vi.fn(() => false),
+ };
+
+ expect(window.ResearchStates.isCancelled('suspended')).toBe(true);
+ expect(window.ResearchStates.isTerminal('suspended')).toBe(true);
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('progress-bar').style.width).toBe('64%');
+ expect(document.getElementById('status-text').textContent).toBe('Cancelled');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Suspended...');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('view-results-btn').textContent)
+ .toBe('Start New Research');
+ expect(document.getElementById('view-results-btn').style.display)
+ .toBe('inline-block');
+ expect(URLValidator.safeAssign).toHaveBeenCalledWith(
+ document.getElementById('view-results-btn'),
+ 'href',
+ '/',
+ );
+
+ olderPoll.resolve({
+ status: 'in_progress',
+ progress: 12,
+ current_task: 'Stale provider setup',
+ });
+ await olderPoll.promise;
+ await flushPromises();
+
+ progressCallback({
+ status: 'in_progress',
+ progress: 88,
+ current_task: 'Late socket work',
+ });
+ reconnectCallback();
+ await window.progressComponent.checkProgress();
+
+ expect(document.getElementById('progress-bar').style.width).toBe('64%');
+ expect(document.getElementById('status-text').textContent).toBe('Cancelled');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Suspended...');
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledTimes(1);
+});
diff --git a/tests/js/components/progress-initial-completed-runtime.test.js b/tests/js/components/progress-initial-completed-runtime.test.js
new file mode 100644
index 0000000000..4f3eb9628b
--- /dev/null
+++ b/tests/js/components/progress-initial-completed-runtime.test.js
@@ -0,0 +1,111 @@
+/** Completed bootstrap parity for the migrated progress status endpoint. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'initial-completed-3299';
+
+beforeEach(() => {
+ document.title = 'Research in progress';
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed', 'failed', 'error', 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.ui;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('restores result navigation, title, and overflow recovery from an initial completed status', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('URLValidator', {
+ safeAssign: vi.fn((element, property, value) => {
+ element.setAttribute(property, value);
+ }),
+ });
+ const contextFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ data: { overview: { truncation_occurred: false } },
+ }),
+ });
+ vi.stubGlobal('fetch', contextFetch);
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ window.api = {
+ getResearchStatus: vi.fn()
+ .mockResolvedValueOnce({
+ status: 'in_progress',
+ progress: 75,
+ current_task: 'Finishing report',
+ })
+ .mockResolvedValueOnce({
+ status: 'completed',
+ progress: 100,
+ }),
+ };
+ window.ui = {
+ updateFavicon: vi.fn(),
+ showError: vi.fn(),
+ };
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('view-results-btn').getAttribute('href'))
+ .toBe(`/results/${RESEARCH_ID}`);
+ });
+ expect(document.getElementById('view-results-btn').style.display)
+ .toBe('inline-block');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Research completed successfully');
+ expect(document.title).toBe('Research (100%) - Local Deep Research');
+ expect(contextFetch).toHaveBeenCalledWith(
+ `/api/research/${RESEARCH_ID}/context-overflow`,
+ );
+});
diff --git a/tests/js/components/progress-initial-error-envelope.test.js b/tests/js/components/progress-initial-error-envelope.test.js
new file mode 100644
index 0000000000..38b7cb35db
--- /dev/null
+++ b/tests/js/components/progress-initial-error-envelope.test.js
@@ -0,0 +1,121 @@
+/** FastAPI failure-envelope coverage for progress-page bootstrap. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'progress-initial-error-envelope-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+async function flushPromises(turns = 8) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar" class="bg-primary"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'error',
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ delete window.api;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('renders persisted FastAPI metadata.error_info detail for an initial failure', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+
+ const olderPoll = deferred();
+ const getResearchStatus = vi.fn()
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockResolvedValueOnce({
+ status: 'failed',
+ progress: 37,
+ completed_at: null,
+ report_path: null,
+ metadata: {
+ error_info: {
+ type: 'connection',
+ message: 'Provider credentials rejected',
+ suggestion: 'Check the provider settings.',
+ },
+ },
+ });
+ window.api = { getResearchStatus };
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Error: Provider credentials rejected');
+ expect(document.getElementById('current-task').textContent)
+ .not.toContain('Unknown error');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('view-results-btn').textContent)
+ .toBe('View Error Report');
+
+ olderPoll.resolve({
+ status: 'in_progress',
+ progress: 12,
+ current_task: 'Stale provider setup',
+ });
+ await olderPoll.promise;
+ await flushPromises();
+
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Error: Provider credentials rejected');
+});
diff --git a/tests/js/components/progress-initial-error-ownership.test.js b/tests/js/components/progress-initial-error-ownership.test.js
new file mode 100644
index 0000000000..cd7be0c36c
--- /dev/null
+++ b/tests/js/components/progress-initial-error-ownership.test.js
@@ -0,0 +1,120 @@
+/** Initial failure ownership for the progress page's HTTP fallback. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'progress-initial-error-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+async function flushPromises(turns = 8) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar" class="bg-primary"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'error',
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ delete window.api;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('retires fallback polling and ignores an older status after initial failure', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ const olderPoll = deferred();
+ const getResearchStatus = vi.fn()
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockResolvedValueOnce({
+ status: 'failed',
+ message: 'Provider credentials rejected',
+ });
+ window.api = { getResearchStatus };
+ const intervalSpy = vi.spyOn(globalThis, 'setInterval');
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(intervalSpy).toHaveBeenCalledWith(expect.any(Function), 3000);
+ const fallbackInterval = intervalSpy.mock.results[0].value;
+ expect(clearIntervalSpy).toHaveBeenCalledWith(fallbackInterval);
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+ expect(document.getElementById('progress-bar').classList)
+ .toContain('bg-danger');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Error: Provider credentials rejected');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+ expect(document.getElementById('view-results-btn').textContent)
+ .toBe('View Error Report');
+
+ olderPoll.resolve({
+ status: 'in_progress',
+ progress: 12,
+ current_task: 'Stale provider setup',
+ });
+ await olderPoll.promise;
+ await flushPromises();
+
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Error: Provider credentials rejected');
+ expect(document.getElementById('view-results-btn').style.display)
+ .toBe('inline-block');
+});
diff --git a/tests/js/components/progress-malformed-ownership.test.js b/tests/js/components/progress-malformed-ownership.test.js
new file mode 100644
index 0000000000..86c2ea5cf1
--- /dev/null
+++ b/tests/js/components/progress-malformed-ownership.test.js
@@ -0,0 +1,97 @@
+/** Malformed HTTP snapshots must not steal progress ownership. */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+
+const RESEARCH_ID = 'progress-malformed-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('lets an older valid status recover after a newer malformed snapshot', async () => {
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ const olderValidStatus = deferred();
+ const statusMock = vi.spyOn(window.api, 'getResearchStatus')
+ .mockImplementationOnce(() => olderValidStatus.promise)
+ .mockResolvedValueOnce({});
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(statusMock).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('status-text').textContent)
+ .toMatch(/Error/i);
+ });
+
+ olderValidStatus.resolve({
+ status: 'in_progress',
+ progress: 65,
+ current_task: 'Recovered valid status',
+ });
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('progress-bar').style.width).toBe('65%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Recovered valid status');
+ });
+});
diff --git a/tests/js/components/progress-notification-dismiss-runtime.test.js b/tests/js/components/progress-notification-dismiss-runtime.test.js
new file mode 100644
index 0000000000..74bf49d77d
--- /dev/null
+++ b/tests/js/components/progress-notification-dismiss-runtime.test.js
@@ -0,0 +1,42 @@
+/** Notification removal remains idempotent across manual and timed dismissal. */
+
+import '@js/config/urls.js';
+
+it('does not remove the same notification twice after manual close', async () => {
+ vi.useFakeTimers();
+ vi.stubGlobal('Notification', { permission: 'denied' });
+
+ try {
+ await import('@js/components/progress.js');
+ window.showNotification(
+ 'Migration complete',
+ 'This notification can be dismissed immediately.',
+ 'info',
+ 1000,
+ );
+
+ const notification = document.querySelector(
+ '#notification-container .ldr-alert',
+ );
+ expect(notification).not.toBeNull();
+ notification.querySelector('.btn-close').click();
+
+ await vi.advanceTimersByTimeAsync(300);
+ expect(document.querySelector('#notification-container .ldr-alert'))
+ .toBeNull();
+
+ // The independent expiry timer still fires later. It must recognize
+ // that manual dismissal already detached this exact element.
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(document.querySelector('#notification-container .ldr-alert'))
+ .toBeNull();
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+ }
+});
diff --git a/tests/js/components/progress-queued-reconnect-runtime.test.js b/tests/js/components/progress-queued-reconnect-runtime.test.js
new file mode 100644
index 0000000000..5c3be788eb
--- /dev/null
+++ b/tests/js/components/progress-queued-reconnect-runtime.test.js
@@ -0,0 +1,108 @@
+/** FastAPI queued-state hydration and websocket reconnect contracts. */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'queued-progress-3299';
+
+async function flushPromises(turns = 10) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed', 'failed', 'error', 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+});
+
+it('renders queue ownership once and reuses its progress consumer on reconnect', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ const queued = {
+ status: 'queued',
+ progress: 0,
+ queue_position: 4,
+ };
+ window.api = {
+ getResearchStatus: vi.fn().mockResolvedValue(queued),
+ };
+ let reconnect;
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(callback => {
+ reconnect = callback;
+ }),
+ isUsingPolling: vi.fn(() => false),
+ };
+ const intervalSpy = vi.spyOn(globalThis, 'setInterval');
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+
+ expect(window.api.getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('status-text').textContent).toBe('queued');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Waiting in queue (position 4)...');
+ expect(document.getElementById('progress-percentage').textContent).toBe('0%');
+ expect(intervalSpy.mock.calls.filter(([, delay]) => delay === 5000))
+ .toHaveLength(1);
+
+ const firstSubscription = window.socket.subscribeToResearch.mock.calls[0];
+ expect(firstSubscription).toEqual([RESEARCH_ID, expect.any(Function)]);
+ expect(reconnect).toBeTypeOf('function');
+ reconnect();
+
+ expect(window.socket.subscribeToResearch).toHaveBeenCalledTimes(2);
+ expect(window.socket.subscribeToResearch.mock.calls[1][0]).toBe(RESEARCH_ID);
+ expect(window.socket.subscribeToResearch.mock.calls[1][1])
+ .toBe(firstSubscription[1]);
+});
diff --git a/tests/js/components/progress-socket-frame-ownership.test.js b/tests/js/components/progress-socket-frame-ownership.test.js
new file mode 100644
index 0000000000..4c1c2ff798
--- /dev/null
+++ b/tests/js/components/progress-socket-frame-ownership.test.js
@@ -0,0 +1,174 @@
+/** Live ownership contracts between progress HTTP snapshots and socket frames. */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+
+const RESEARCH_ID = 'progress-socket-owner-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+let progressCallback;
+
+beforeEach(() => {
+ progressCallback = null;
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn((_researchId, callback) => {
+ progressCallback = callback;
+ }),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('keeps nonterminal ownership ordered but never suppresses HTTP completion', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ const olderBootstrap = deferred();
+ const newerBootstrap = deferred();
+ const statusMock = vi.spyOn(window.api, 'getResearchStatus')
+ .mockImplementationOnce(() => olderBootstrap.promise)
+ .mockImplementationOnce(() => newerBootstrap.promise);
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(statusMock).toHaveBeenCalledTimes(2);
+ expect(progressCallback).toBeTypeOf('function');
+ });
+
+ progressCallback({
+ log_entry: {
+ message: 'A socket log with no status snapshot',
+ type: 'INFO',
+ time: '2026-09-01T00:00:00Z',
+ },
+ });
+ newerBootstrap.resolve({
+ status: 'in_progress',
+ progress: 40,
+ current_task: 'Hydrated from HTTP',
+ });
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('progress-bar').style.width).toBe('40%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Hydrated from HTTP');
+ });
+
+ olderBootstrap.resolve({
+ status: 'in_progress',
+ progress: 10,
+ current_task: 'Older bootstrap snapshot',
+ });
+ await olderBootstrap.promise;
+ await Promise.resolve();
+
+ const stalePoll = deferred();
+ statusMock.mockImplementationOnce(() => stalePoll.promise);
+ const stalePollRequest = window.progressComponent.checkProgress();
+ await vi.waitFor(() => expect(statusMock).toHaveBeenCalledTimes(3));
+
+ progressCallback({
+ status: 'in_progress',
+ progress: 80,
+ current_task: 'Owned by live socket status',
+ });
+ expect(document.getElementById('progress-bar').style.width).toBe('80%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Owned by live socket status');
+
+ stalePoll.resolve({
+ status: 'in_progress',
+ progress: 20,
+ current_task: 'Stale HTTP status',
+ });
+ await stalePollRequest;
+
+ expect(document.getElementById('progress-bar').style.width).toBe('80%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Owned by live socket status');
+
+ const terminalPoll = deferred();
+ statusMock.mockImplementationOnce(() => terminalPoll.promise);
+ const terminalRequest = window.progressComponent.checkProgress();
+ await vi.waitFor(() => expect(statusMock).toHaveBeenCalledTimes(4));
+
+ progressCallback({
+ status: 'in_progress',
+ progress: 85,
+ current_task: 'Latest nonterminal socket frame',
+ });
+ expect(document.getElementById('progress-bar').style.width).toBe('85%');
+
+ terminalPoll.resolve({
+ status: 'completed',
+ progress: 100,
+ });
+ await terminalRequest;
+
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+ expect(document.getElementById('view-results-btn').style.display)
+ .toBe('inline-block');
+
+ progressCallback({
+ status: 'in_progress',
+ progress: 25,
+ current_task: 'Late nonterminal socket frame',
+ });
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+});
diff --git a/tests/js/components/progress-stale-ownership.test.js b/tests/js/components/progress-stale-ownership.test.js
new file mode 100644
index 0000000000..78495b1b82
--- /dev/null
+++ b/tests/js/components/progress-stale-ownership.test.js
@@ -0,0 +1,109 @@
+/** Async ownership contracts for competing progress status sources. */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+
+const RESEARCH_ID = 'progress-race-3299';
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+beforeEach(() => {
+ document.title = 'Research in progress';
+ document.body.innerHTML = `
+ <div role="progressbar" aria-valuenow="0">
+ <div id="progress-bar"></div>
+ </div>
+ <div id="progress-percentage"></div>
+ <div id="status-text" class="ldr-status-indicator"></div>
+ <div id="current-task"></div>
+ <button id="cancel-research-btn"></button>
+ <a id="view-results-btn" style="display: none"></a>
+ `;
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ };
+ window.ResearchStates = {
+ isTerminal: status => ['completed', 'failed', 'error', 'cancelled'].includes(status),
+ isCompleted: status => status === 'completed',
+ isFailed: status => ['failed', 'error'].includes(status),
+ isCancelled: status => status === 'cancelled',
+ isInProgress: status => status === 'in_progress',
+ formatStatus: status => status,
+ logLevel: () => 'info',
+ };
+ window.socket = {
+ subscribeToResearch: vi.fn(),
+ onReconnect: vi.fn(),
+ isUsingPolling: vi.fn(() => false),
+ };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.RESEARCH_STATUS;
+ delete window.progressComponent;
+ delete window.showNotification;
+ document.body.replaceChildren();
+});
+
+it('does not let the older bootstrap poll regress a newer terminal status', async () => {
+ vi.stubGlobal('URLBuilder', window.URLBuilder);
+ vi.stubGlobal('URLS', window.URLS);
+ vi.stubGlobal('ResearchStates', window.ResearchStates);
+ vi.stubGlobal('Notification', { permission: 'denied' });
+ vi.stubGlobal('URLValidator', {
+ safeAssign: vi.fn((element, property, value) => {
+ element.setAttribute(property, value);
+ }),
+ });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false }));
+ vi.spyOn(window.URLBuilder, 'extractResearchIdFromPattern')
+ .mockReturnValue(RESEARCH_ID);
+ const olderPoll = deferred();
+ const statusMock = vi.spyOn(window.api, 'getResearchStatus')
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockResolvedValueOnce({ status: 'completed', progress: 100 });
+ const intervalSpy = vi.spyOn(globalThis, 'setInterval');
+
+ await import('@js/components/progress.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Research completed successfully');
+ });
+ expect(statusMock).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+ expect(document.getElementById('view-results-btn').style.display)
+ .toBe('inline-block');
+ expect(document.getElementById('cancel-research-btn').style.display)
+ .toBe('none');
+
+ olderPoll.resolve({
+ status: 'in_progress',
+ progress: 40,
+ current_task: 'Stale gathering step',
+ });
+ await olderPoll.promise;
+ await Promise.resolve();
+
+ expect(document.getElementById('progress-bar').style.width).toBe('100%');
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Research completed successfully');
+ expect(document.title).toBe('Research (100%) - Local Deep Research');
+ expect(intervalSpy).not.toHaveBeenCalled();
+});
diff --git a/tests/js/components/report-issue-runtime.test.js b/tests/js/components/report-issue-runtime.test.js
new file mode 100644
index 0000000000..0fbabc0049
--- /dev/null
+++ b/tests/js/components/report-issue-runtime.test.js
@@ -0,0 +1,63 @@
+/** Direct runtime contracts for the results-page help modal. */
+
+let reportButton;
+let modal;
+
+beforeAll(async () => {
+ document.body.innerHTML = `
+ <button id="report-issue-btn">Help improve</button>
+ <div id="reportIssueModal"><div id="modal-content">Content</div></div>
+ `;
+ reportButton = document.getElementById('report-issue-btn');
+ modal = document.getElementById('reportIssueModal');
+
+ await import('@js/components/report_issue.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+});
+
+afterEach(() => {
+ delete globalThis.bootstrap;
+ modal.style.display = '';
+ modal.classList.remove('show');
+});
+
+afterAll(() => {
+ document.body.innerHTML = '';
+});
+
+it('opens and closes the modal without Bootstrap', () => {
+ reportButton.click();
+
+ expect(modal.style.display).toBe('block');
+ expect(modal.classList.contains('show')).toBe(true);
+
+ modal.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(modal.style.display).toBe('none');
+ expect(modal.classList.contains('show')).toBe(false);
+});
+
+it('does not close when a click bubbles from the modal contents', () => {
+ reportButton.click();
+ document.getElementById('modal-content').click();
+
+ expect(modal.style.display).toBe('block');
+ expect(modal.classList.contains('show')).toBe(true);
+});
+
+it('delegates modal ownership to the checked-in Bootstrap API when present', () => {
+ const show = vi.fn();
+ const hide = vi.fn();
+ const Modal = vi.fn(function BootstrapModal() {
+ return { show };
+ });
+ Modal.getInstance = vi.fn(() => ({ hide }));
+ globalThis.bootstrap = { Modal };
+
+ reportButton.click();
+ expect(Modal).toHaveBeenCalledWith(modal);
+ expect(show).toHaveBeenCalledOnce();
+
+ modal.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(Modal.getInstance).toHaveBeenCalledWith(modal);
+ expect(hide).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/components/research-api-runtime.test.js b/tests/js/components/research-api-runtime.test.js
new file mode 100644
index 0000000000..aefa5442aa
--- /dev/null
+++ b/tests/js/components/research-api-runtime.test.js
@@ -0,0 +1,688 @@
+/**
+ * Direct browser-runtime contracts for the research page's remaining API
+ * mutations and initialization path. The dropdowns are replaced only at the
+ * widget boundary so their shipped callbacks still drive research.js itself.
+ */
+
+import '@js/config/urls.js';
+import '@js/utils/alert-helpers.js';
+import '@js/security/xss-protection.js';
+import '@js/utils/form-validation.js';
+
+const AVAILABLE_MODELS = '/settings/api/available-models';
+const AVAILABLE_ENGINES = '/settings/api/available-search-engines';
+const SETTINGS = '/settings/api';
+const START_RESEARCH = '/api/start_research';
+const CHAT_SESSIONS = '/api/chat/sessions';
+
+const dropdowns = new Map();
+const responseOverrides = new Map();
+let fetchMock;
+let initialSnapshot;
+
+function response(body, { ok = true, status = 200 } = {}) {
+ return Promise.resolve({
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(body),
+ text: vi.fn().mockResolvedValue(''),
+ });
+}
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function buildForm() {
+ const apiKeys = [
+ 'openai',
+ 'anthropic',
+ 'google',
+ 'openrouter',
+ 'orcarouter',
+ 'atlascloud',
+ 'xai',
+ 'ionos',
+ 'openai_endpoint',
+ 'anthropic_endpoint',
+ 'ollama',
+ 'lmstudio',
+ ];
+ // eslint-disable-next-line no-unsanitized/property -- static, repository-owned test fixture.
+ document.body.innerHTML = `
+ <form id="research-form">
+ <div id="research-alert" role="alert" style="display:none"></div>
+ <div id="research-error-alert" style="display:none"></div>
+ <textarea id="query" name="query"></textarea>
+
+ <label class="ldr-mode-option active" data-mode="quick" tabindex="0">
+ <input id="mode-quick" type="radio" name="research_mode" value="quick" checked>
+ </label>
+ <label class="ldr-mode-option" data-mode="detailed" tabindex="-1">
+ <input id="mode-detailed" type="radio" name="research_mode" value="detailed">
+ </label>
+ <label class="ldr-mode-option" data-mode="chat" tabindex="-1">
+ <input id="mode-chat" type="radio" name="research_mode" value="chat">
+ </label>
+
+ <div class="ldr-privacy-panel" data-scope="adaptive">
+ <i id="ldr-privacy-panel-icon"></i>
+ <select id="policy_egress_scope">
+ <option value="adaptive" selected>Adaptive</option>
+ <option value="public_only">Public only</option>
+ <option value="private_only">Private only</option>
+ <option value="strict">Primary only</option>
+ </select>
+ <input id="llm_require_local_endpoint" type="checkbox">
+ <input id="embeddings_require_local" type="checkbox">
+ </div>
+
+ <button type="button" class="ldr-advanced-options-toggle ldr-open" aria-expanded="true">
+ <i class="fas fa-chevron-up"></i><span class="sr-only"></span>
+ </button>
+ <div class="ldr-advanced-options-panel ldr-expanded">
+ <select id="model_provider" data-initial-value="OLLAMA">
+ <option value="OLLAMA">Ollama</option>
+ </select>
+ <input id="llm.provider_hidden" name="llm.provider">
+
+ <div class="form-group">
+ <input id="model" data-initial-value="">
+ <input id="model_hidden" name="llm.model">
+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
+ <button type="button" id="model-refresh"><i></i></button>
+ </div>
+
+ <div class="form-group">
+ <input id="search_engine" data-initial-value="searxng">
+ <input id="search_engine_hidden" name="search.tool" value="searxng">
+ <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
+ <button type="button" id="search_engine-refresh"><i></i></button>
+ </div>
+
+ <select id="strategy"><option value="source-based">Source based</option></select>
+ <input id="iterations" value="2">
+ <input id="questions_per_iteration" value="3">
+ <input id="notification-toggle" type="checkbox" checked>
+
+ <div id="endpoint_container"><input id="custom_endpoint"></div>
+ <div id="anthropic_endpoint_container"><input id="anthropic_endpoint_url"></div>
+ <div id="ollama_url_container"><input id="ollama_url"></div>
+ <div id="lmstudio_url_container"><input id="lmstudio_url"></div>
+ <div id="context_window_container"><input id="context_window"></div>
+ ${apiKeys.map(key => `
+ <div id="${key}_api_key_container">
+ <input id="${key}_api_key" type="password">
+ </div>
+ `).join('')}
+ </div>
+ <button id="start-research-btn" type="submit"><span></span></button>
+ </form>
+ `;
+}
+
+function initialSettings() {
+ const settings = {
+ 'llm.provider': { value: 'openai_endpoint', editable: false },
+ 'llm.model': { value: 'gateway-model', editable: false },
+ 'llm.openai_endpoint.url': { value: 'https://gateway.example/v1', editable: false },
+ 'llm.anthropic_endpoint.url': { value: 'https://claude.example/v1', editable: true },
+ 'llm.ollama.url': { value: 'http://ollama.test', editable: true },
+ 'llm.lmstudio.url': { value: 'http://lmstudio.test', editable: false },
+ 'llm.local_context_window_size': { value: 16384, editable: true },
+ 'search.tool': { value: 'searxng', editable: true },
+ };
+ for (const key of [
+ 'openai',
+ 'anthropic',
+ 'google',
+ 'openrouter',
+ 'orcarouter',
+ 'atlascloud',
+ 'xai',
+ 'ionos',
+ 'openai_endpoint',
+ 'anthropic_endpoint',
+ 'ollama',
+ 'lmstudio',
+ ]) {
+ settings[`llm.${key}.api_key`] = {
+ value: '[REDACTED]',
+ editable: key !== 'google',
+ };
+ }
+ return { settings };
+}
+
+function routeFetch(url, init = {}) {
+ const override = responseOverrides.get(url);
+ if (override) return response(override.body, override);
+
+ if (url === AVAILABLE_MODELS) {
+ return response({
+ provider_options: [
+ { value: 'OLLAMA', label: 'Ollama', is_cloud: false },
+ { value: 'OPENAI_ENDPOINT', label: 'OpenAI-compatible', is_cloud: true },
+ { value: 'ANTHROPIC_ENDPOINT', label: 'Anthropic-compatible', is_cloud: true },
+ ],
+ providers: {
+ ollama_models: [{ value: 'qwen3:4b', name: 'Qwen 3', provider: 'OLLAMA' }],
+ openai_endpoint_models: [
+ { value: 'gateway-model', name: 'Gateway model', provider: 'OPENAI_ENDPOINT' },
+ ],
+ },
+ });
+ }
+ if (typeof url === 'string' && url.startsWith(AVAILABLE_ENGINES)) {
+ return response({
+ engine_options: [
+ { value: 'searxng', label: 'SearXNG' },
+ { value: 'library', label: 'Search All Collections' },
+ ],
+ });
+ }
+ if (url === SETTINGS && (!init.method || init.method === 'GET')) {
+ return response(initialSettings());
+ }
+ return response({ status: 'ok' });
+}
+
+function selectMode(value) {
+ for (const radio of document.querySelectorAll('input[name="research_mode"]')) {
+ radio.checked = radio.value === value;
+ }
+}
+
+function submit() {
+ document.getElementById('research-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+}
+
+beforeAll(async () => {
+ sessionStorage.clear();
+ localStorage.clear();
+ sessionStorage.setItem('rerunConfig', JSON.stringify({
+ query: '<b>re-run this literally</b>',
+ mode: 'detailed',
+ model: 'stale-history-model',
+ }));
+ buildForm();
+
+ window.api = { getCsrfToken: vi.fn(() => 'research-csrf') };
+ window.ui = { showAlert: vi.fn(), showMessage: vi.fn() };
+ window.RESEARCH_STATUS = { QUEUED: 'queued', IN_PROGRESS: 'in_progress' };
+ window.setupCustomDropdown = vi.fn((input, _list, getOptions, onSelect) => {
+ dropdowns.set(input.id, { getOptions, onSelect });
+ return {};
+ });
+ window.updateDropdownOptions = vi.fn();
+
+ fetchMock = vi.fn(routeFetch);
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('requestIdleCallback', vi.fn(callback => callback()));
+
+ await import('@js/components/research.js');
+ await import('@js/components/settings_sync.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('model_hidden').value).toBe('gateway-model');
+ expect(dropdowns.has('model')).toBe(true);
+ expect(dropdowns.has('search_engine')).toBe(true);
+ });
+
+ initialSnapshot = {
+ query: document.getElementById('query').value,
+ rerunConfig: sessionStorage.getItem('rerunConfig'),
+ detailedChecked: document.getElementById('mode-detailed').checked,
+ detailedActive: document.querySelector('[data-mode="detailed"]').classList.contains('active'),
+ notification: document.getElementById('research-alert').textContent,
+ provider: document.getElementById('model_provider').value,
+ providerDisabled: document.getElementById('model_provider').disabled,
+ model: document.getElementById('model').value,
+ modelDisabled: document.getElementById('model').disabled,
+ endpoint: document.getElementById('custom_endpoint').value,
+ endpointDisabled: document.getElementById('custom_endpoint').disabled,
+ anthropicEndpoint: document.getElementById('anthropic_endpoint_url').value,
+ ollamaUrl: document.getElementById('ollama_url').value,
+ lmstudioUrl: document.getElementById('lmstudio_url').value,
+ contextWindow: document.getElementById('context_window').value,
+ openaiKey: document.getElementById('openai_api_key').value,
+ orcarouterKey: document.getElementById('orcarouter_api_key').value,
+ apiKeyValues: Array.from(
+ document.querySelectorAll('input[type="password"]'),
+ input => input.value,
+ ),
+ googleKeyDisabled: document.getElementById('google_api_key').disabled,
+ activeProviderContainer: document.getElementById('endpoint_container').style.display,
+ };
+});
+
+beforeEach(() => {
+ responseOverrides.clear();
+ fetchMock.mockClear();
+ fetchMock.mockImplementation(routeFetch);
+ window.ui.showAlert.mockClear();
+ window.ui.showMessage.mockClear();
+ document.getElementById('query').value = 'A current research query';
+ document.getElementById('model_hidden').value = 'gateway-model';
+ document.getElementById('research-alert').replaceChildren();
+ document.getElementById('research-alert').style.display = 'none';
+ document.getElementById('research-error-alert').replaceChildren();
+ document.getElementById('research-error-alert').style.display = 'none';
+ document.querySelectorAll('.ldr-loading-overlay').forEach(element => element.remove());
+ selectMode('quick');
+});
+
+afterAll(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ sessionStorage.clear();
+ localStorage.clear();
+ delete window.api;
+ delete window.ui;
+ delete window.RESEARCH_STATUS;
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+});
+
+it('applies one history rerun after initialization without trusting stale settings', () => {
+ expect(initialSnapshot).toMatchObject({
+ query: '<b>re-run this literally</b>',
+ rerunConfig: null,
+ detailedChecked: true,
+ detailedActive: true,
+ });
+ expect(initialSnapshot.notification).toContain('Re-running previous research');
+ expect(document.querySelector('#research-alert b')).toBeNull();
+});
+
+it('hydrates the editable settings envelope and reconciles its provider and model', () => {
+ expect(initialSnapshot).toMatchObject({
+ provider: 'OPENAI_ENDPOINT',
+ providerDisabled: true,
+ model: 'Gateway model',
+ modelDisabled: true,
+ endpoint: 'https://gateway.example/v1',
+ endpointDisabled: true,
+ anthropicEndpoint: 'https://claude.example/v1',
+ ollamaUrl: 'http://ollama.test',
+ lmstudioUrl: 'http://lmstudio.test',
+ contextWindow: '16384',
+ openaiKey: '',
+ orcarouterKey: '',
+ googleKeyDisabled: true,
+ activeProviderContainer: 'block',
+ });
+ expect(initialSnapshot.apiKeyValues).toHaveLength(12);
+ expect(initialSnapshot.apiKeyValues).toEqual(Array(12).fill(''));
+});
+
+it('replaces one redacted API key through the canonical FastAPI setting route', async () => {
+ const input = document.getElementById('openai_api_key');
+ expect(initialSnapshot.apiKeyValues).toEqual(Array(12).fill(''));
+
+ input.value = 'replacement-openai-key';
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ const writes = fetchMock.mock.calls.filter(([url, options]) => (
+ url === '/settings/api/llm.openai.api_key'
+ && options.method === 'PUT'
+ ));
+ expect(writes).toHaveLength(1);
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/llm.openai.api_key',
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'research-csrf',
+ },
+ body: JSON.stringify({ value: 'replacement-openai-key' }),
+ },
+ );
+});
+
+it('reports a rejected custom-model save using FastAPI detail and keeps hidden settings in sync', async () => {
+ responseOverrides.set('/settings/api/llm.model', {
+ body: { detail: 'model is blocked by policy' },
+ ok: false,
+ status: 422,
+ });
+
+ dropdowns.get('model').onSelect('blocked-model', null);
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating model: model is blocked by policy',
+ 'error',
+ 3000,
+ );
+ });
+ expect(document.getElementById('model_hidden').value).toBe('blocked-model');
+ expect(document.getElementById('custom-model-warning').textContent)
+ .toContain('Custom model name entered');
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.model', expect.objectContaining({
+ method: 'PUT',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ body: JSON.stringify({ value: 'blocked-model' }),
+ }));
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith(
+ expect.stringContaining('Model updated'),
+ 'success',
+ 2000,
+ );
+});
+
+it('preserves same-key setting order while unrelated settings save concurrently', async () => {
+ const firstModelResponse = deferred();
+ const startedWrites = [];
+ fetchMock.mockImplementation((url, options = {}) => {
+ if (options.method === 'PUT'
+ && ['/settings/api/llm.model', '/settings/api/search.iterations'].includes(url)) {
+ const value = JSON.parse(options.body).value;
+ startedWrites.push({ url, value });
+ if (url === '/settings/api/llm.model' && value === 'model-a') {
+ return firstModelResponse.promise;
+ }
+ }
+ return routeFetch(url, options);
+ });
+
+ dropdowns.get('model').onSelect('model-a', { label: 'Model A' });
+ dropdowns.get('model').onSelect('model-b', { label: 'Model B' });
+
+ const iterations = document.getElementById('iterations');
+ iterations.value = '4';
+ iterations.dispatchEvent(new Event('change', { bubbles: true }));
+
+ await vi.waitFor(() => {
+ expect(startedWrites.filter(write => write.url === '/settings/api/llm.model'))
+ .toEqual([{ url: '/settings/api/llm.model', value: 'model-a' }]);
+ expect(startedWrites).toContainEqual({
+ url: '/settings/api/search.iterations',
+ value: 4,
+ });
+ });
+
+ firstModelResponse.resolve(response({ status: 'ok' }));
+
+ await vi.waitFor(() => {
+ expect(startedWrites.filter(write => write.url === '/settings/api/llm.model'))
+ .toEqual([
+ { url: '/settings/api/llm.model', value: 'model-a' },
+ { url: '/settings/api/llm.model', value: 'model-b' },
+ ]);
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Model updated to: model-b',
+ 'success',
+ 2000,
+ );
+ });
+});
+
+it.each([
+ {
+ failure: 'a rejected request',
+ message: 'network unavailable',
+ settle: pending => pending.reject(new Error('network unavailable')),
+ },
+ {
+ failure: 'a non-ok response',
+ message: 'model save unavailable',
+ settle: pending => pending.resolve(response(
+ { detail: 'model save unavailable' },
+ { ok: false, status: 503 },
+ )),
+ },
+])('continues a same-key setting queue after $failure', async ({ message, settle }) => {
+ const firstModelResponse = deferred();
+ const startedModels = [];
+ fetchMock.mockImplementation((url, options = {}) => {
+ if (url === '/settings/api/llm.model' && options.method === 'PUT') {
+ const value = JSON.parse(options.body).value;
+ startedModels.push(value);
+ if (startedModels.length === 1) return firstModelResponse.promise;
+ }
+ return routeFetch(url, options);
+ });
+
+ dropdowns.get('model').onSelect('model-before-failure', { label: 'First model' });
+ dropdowns.get('model').onSelect('model-after-failure', { label: 'Second model' });
+
+ await vi.waitFor(() => {
+ expect(startedModels).toEqual(['model-before-failure']);
+ });
+
+ settle(firstModelResponse);
+
+ await vi.waitFor(() => {
+ expect(startedModels).toEqual([
+ 'model-before-failure',
+ 'model-after-failure',
+ ]);
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ `Error updating model: ${message}`,
+ 'error',
+ 3000,
+ );
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Model updated to: model-after-failure',
+ 'success',
+ 2000,
+ );
+ });
+});
+
+it('does not claim a rejected search-engine save succeeded', async () => {
+ responseOverrides.set('/settings/api/search.tool', {
+ body: { detail: 'engine is not allowed for this scope' },
+ ok: false,
+ status: 400,
+ });
+
+ dropdowns.get('search_engine').onSelect('library', {
+ label: 'Search All Collections',
+ });
+ document.getElementById('search_engine_hidden').value = 'library';
+ document.getElementById('search_engine_hidden').dispatchEvent(
+ new Event('change', { bubbles: true }),
+ );
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating search.tool: engine is not allowed for this scope',
+ 'error',
+ 3000,
+ );
+ });
+ expect(document.getElementById('search_engine_hidden').value).toBe('library');
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/search.tool', expect.objectContaining({
+ method: 'PUT',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ body: JSON.stringify({ value: 'library' }),
+ }));
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith(
+ expect.stringContaining('Search engine updated'),
+ 'success',
+ 2000,
+ );
+});
+
+it('assigns one settings writer to every control shared with the base bridge', async () => {
+ const provider = document.getElementById('model_provider');
+ provider.disabled = false;
+ provider.value = 'OLLAMA';
+ provider.dispatchEvent(new Event('change', { bubbles: true }));
+
+ dropdowns.get('model').onSelect('qwen3:4b', { label: 'Qwen 3' });
+ document.getElementById('model_hidden').value = 'qwen3:4b';
+ document.getElementById('model_hidden').dispatchEvent(
+ new Event('change', { bubbles: true }),
+ );
+
+ dropdowns.get('search_engine').onSelect('library', {
+ label: 'Search All Collections',
+ });
+ document.getElementById('search_engine_hidden').value = 'library';
+ document.getElementById('search_engine_hidden').dispatchEvent(
+ new Event('change', { bubbles: true }),
+ );
+
+ const iterations = document.getElementById('iterations');
+ iterations.value = '5';
+ iterations.dispatchEvent(new Event('change', { bubbles: true }));
+ const questions = document.getElementById('questions_per_iteration');
+ questions.value = '2';
+ questions.dispatchEvent(new Event('change', { bubbles: true }));
+ const ollamaUrl = document.getElementById('ollama_url');
+ ollamaUrl.value = 'http://ollama-new.test';
+ ollamaUrl.dispatchEvent(new Event('change', { bubbles: true }));
+
+ const strategy = document.getElementById('strategy');
+ strategy.value = 'source-based';
+ strategy.dispatchEvent(new Event('change', { bubbles: true }));
+ const customEndpoint = document.getElementById('custom_endpoint');
+ customEndpoint.value = 'https://gateway-new.example/v1';
+ customEndpoint.dispatchEvent(new Event('change', { bubbles: true }));
+
+ const expectedWrites = new Map([
+ ['/settings/api/llm.provider', 'ollama'],
+ ['/settings/api/llm.model', 'qwen3:4b'],
+ ['/settings/api/search.tool', 'library'],
+ ['/settings/api/search.iterations', 5],
+ ['/settings/api/search.questions_per_iteration', 2],
+ ['/settings/api/llm.ollama.url', 'http://ollama-new.test'],
+ ['/settings/api/search.search_strategy', 'source-based'],
+ ['/settings/api/llm.openai_endpoint.url', 'https://gateway-new.example/v1'],
+ ]);
+ await vi.waitFor(() => {
+ for (const url of expectedWrites.keys()) {
+ expect(fetchMock.mock.calls.filter(([calledUrl, options = {}]) =>
+ calledUrl === url && options.method === 'PUT'
+ )).toHaveLength(1);
+ }
+ });
+ for (const [url, value] of expectedWrites) {
+ expect(fetchMock).toHaveBeenCalledWith(url, expect.objectContaining({
+ method: 'PUT',
+ body: JSON.stringify({ value }),
+ }));
+ }
+});
+
+it('does not claim a rejected provider save succeeded', async () => {
+ responseOverrides.set('/settings/api/llm.provider', {
+ body: { detail: 'provider is operator locked' },
+ ok: false,
+ status: 403,
+ });
+ const provider = document.getElementById('model_provider');
+ provider.disabled = false;
+ provider.value = 'ANTHROPIC_ENDPOINT';
+ provider.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating provider: provider is operator locked',
+ 'error',
+ 3000,
+ );
+ });
+ expect(document.getElementById('anthropic_endpoint_container').style.display).toBe('block');
+ expect(document.getElementById('llm.provider_hidden').value).toBe('ANTHROPIC_ENDPOINT');
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.provider', expect.objectContaining({
+ method: 'PUT',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ body: JSON.stringify({ value: 'anthropic_endpoint' }),
+ }));
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith(
+ expect.stringContaining('Provider updated'),
+ 'success',
+ 2000,
+ );
+});
+
+it('surfaces FastAPI detail from a rejected numeric setting save', async () => {
+ responseOverrides.set('/settings/api/search.iterations', {
+ body: { detail: 'iterations must be between 1 and 10' },
+ ok: false,
+ status: 422,
+ });
+ const iterations = document.getElementById('iterations');
+ iterations.value = '99';
+ iterations.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating search.iterations: iterations must be between 1 and 10',
+ 'error',
+ 3000,
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/search.iterations', expect.objectContaining({
+ method: 'PUT',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ body: JSON.stringify({ value: 99 }),
+ }));
+});
+
+it('renders a rejected research detail as text and restores submit ownership', async () => {
+ window.__researchDetailExecuted = false;
+ responseOverrides.set(START_RESEARCH, {
+ body: {
+ detail: '<img src=x onerror="window.__researchDetailExecuted=true"> denied',
+ field: 'policy_egress_scope',
+ },
+ ok: false,
+ status: 400,
+ });
+
+ submit();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ });
+ const alert = document.getElementById('research-alert');
+ expect(alert.textContent).toContain('<img src=x onerror=');
+ expect(alert.querySelector('img')).toBeNull();
+ expect(window.__researchDetailExecuted).toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ expect(fetchMock).toHaveBeenCalledWith(START_RESEARCH, expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ }));
+ delete window.__researchDetailExecuted;
+});
+
+it('surfaces a rejected chat-session detail and leaves the form retryable', async () => {
+ selectMode('chat');
+ responseOverrides.set(CHAT_SESSIONS, {
+ body: { detail: 'chat service is temporarily unavailable' },
+ ok: false,
+ status: 503,
+ });
+
+ submit();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Failed to start chat: chat service is temporarily unavailable');
+ });
+ expect(document.getElementById('start-research-btn').disabled).toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ expect(fetchMock).toHaveBeenCalledWith(CHAT_SESSIONS, expect.objectContaining({
+ method: 'POST',
+ headers: expect.objectContaining({ 'X-CSRFToken': 'research-csrf' }),
+ body: JSON.stringify({ initial_query: 'A current research query' }),
+ }));
+});
diff --git a/tests/js/components/research-notes-runtime.test.js b/tests/js/components/research-notes-runtime.test.js
new file mode 100644
index 0000000000..0521b5b81d
--- /dev/null
+++ b/tests/js/components/research-notes-runtime.test.js
@@ -0,0 +1,292 @@
+/**
+ * Direct runtime contracts for the results-page research-notes component.
+ * Exercises the real endpoint builders, mutation ownership, annotation action,
+ * and browser state instead of duplicating the component's implementation.
+ */
+
+let notes;
+let originalLocation;
+
+function setLocation(pathname = '/results/research-1') {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: {
+ pathname,
+ search: '',
+ hash: '',
+ href: pathname,
+ host: 'localhost',
+ protocol: 'http:',
+ },
+ });
+}
+
+function response(data) {
+ return { json: () => Promise.resolve(data) };
+}
+
+beforeAll(async () => {
+ originalLocation = window.location;
+ document.body.replaceChildren();
+ window.__VITEST_TEST__ = true;
+ window.NotesShared = {
+ toast: vi.fn(),
+ postJson: vi.fn(),
+ renderNoteRow: vi.fn((note) => {
+ const row = document.createElement('article');
+ row.dataset.noteId = note.id;
+ row.textContent = note.title;
+ return row;
+ }),
+ };
+ window.LDRAnnotationSurface = { init: vi.fn() };
+ globalThis.URLBuilder = {
+ extractResearchIdFromPattern: vi.fn(() => null),
+ };
+ globalThis.safeFetchWithAuth = vi.fn();
+
+ await import('@js/components/research_notes.js');
+ notes = window.__researchNotesTest;
+});
+
+afterAll(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ writable: true,
+ value: originalLocation,
+ });
+ delete window.__VITEST_TEST__;
+ delete window.__researchNotesTest;
+});
+
+beforeEach(() => {
+ setLocation();
+ document.body.innerHTML = `
+ <section id="research-notes-section">
+ <button id="research-add-note-btn"></button>
+ <button id="research-save-as-note-btn"></button>
+ <div id="research-notes-list"></div>
+ <p id="research-notes-empty">No research notes.</p>
+ </section>
+ <button id="research-save-as-note-top-btn"></button>
+ <h1 id="result-query">Research query</h1>
+ <main id="results-content"></main>
+ `;
+ notes.reset();
+ notes.setResearchId('research-1');
+ URLBuilder.extractResearchIdFromPattern.mockReset()
+ .mockReturnValue('research-1');
+ window.LDRAnnotationSurface.init.mockReset();
+ window.NotesShared.toast.mockReset();
+ window.NotesShared.postJson.mockReset();
+ window.NotesShared.renderNoteRow.mockClear();
+ globalThis.safeFetchWithAuth = vi.fn()
+ .mockResolvedValue(response({ success: true, notes: [] }));
+ vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+it('hides the feature when the results route has no research owner', () => {
+ URLBuilder.extractResearchIdFromPattern.mockReturnValue(null);
+
+ notes.initResearchNotes();
+
+ expect(document.getElementById('research-notes-section').style.display)
+ .toBe('none');
+ expect(window.LDRAnnotationSurface.init).not.toHaveBeenCalled();
+ expect(globalThis.safeFetchWithAuth).not.toHaveBeenCalled();
+});
+
+it('initializes encoded notes and annotation endpoints for the current run', async () => {
+ URLBuilder.extractResearchIdFromPattern.mockReturnValue('run /?#');
+
+ notes.initResearchNotes();
+
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith(
+ '/notes/api/research/run%20%2F%3F%23/notes',
+ { credentials: 'same-origin' },
+ );
+ });
+ const config = window.LDRAnnotationSurface.init.mock.calls[0][0];
+ expect(config.containerId).toBe('results-content');
+ expect(config.endpoints.list)
+ .toBe('/notes/api/research/run%20%2F%3F%23/annotations');
+ expect(config.endpoints.create)
+ .toBe('/notes/api/research/run%20%2F%3F%23/annotations');
+ expect(config.endpoints.deleteFor('note /?#'))
+ .toBe('/notes/api/research/run%20%2F%3F%23/annotations/note%20%2F%3F%23');
+ expect(config.extraActions[0]).toMatchObject({
+ icon: 'fas fa-quote-right',
+ label: 'Clip to note',
+ });
+ expect(config.onChanged).toBe(notes.loadResearchNotes);
+});
+
+it('renders the latest successful FastAPI notes envelope and owns empty state', async () => {
+ globalThis.safeFetchWithAuth.mockResolvedValue(response({
+ success: true,
+ notes: [
+ { id: 'note-1', title: 'Migration observation' },
+ { id: 'note-2', title: 'Follow-up' },
+ ],
+ }));
+
+ await notes.loadResearchNotes();
+
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith(
+ '/notes/api/research/research-1/notes',
+ { credentials: 'same-origin' },
+ );
+ expect([...document.getElementById('research-notes-list').children]
+ .map((row) => row.dataset.noteId)).toEqual(['note-1', 'note-2']);
+ expect(document.getElementById('research-notes-empty').style.display)
+ .toBe('none');
+});
+
+it('keeps the report usable and does not render an untrusted load error', async () => {
+ globalThis.safeFetchWithAuth.mockResolvedValue(response({
+ success: false,
+ error: '<img src=x onerror="window.pwned=true">',
+ }));
+
+ await notes.loadResearchNotes();
+
+ const empty = document.getElementById('research-notes-empty');
+ expect(empty.textContent).toBe("Couldn't load notes for this research.");
+ expect(empty.style.display).toBe('block');
+ expect(empty.querySelector('img')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error loading research notes:',
+ expect.objectContaining({
+ message: '<img src=x onerror="window.pwned=true">',
+ }),
+ );
+});
+
+it('does not let an older transport failure replace a newer notes refresh', async () => {
+ let rejectOlder;
+ globalThis.safeFetchWithAuth
+ .mockImplementationOnce(() => new Promise((resolve, reject) => {
+ rejectOlder = reject;
+ }))
+ .mockResolvedValueOnce(response({
+ success: true,
+ notes: [{ id: 'fresh', title: 'Fresh note' }],
+ }));
+
+ const olderLoad = notes.loadResearchNotes();
+ const newerLoad = notes.loadResearchNotes();
+ await newerLoad;
+ rejectOlder(new Error('stale network failure'));
+ await olderLoad;
+
+ expect(document.getElementById('research-notes-list').textContent)
+ .toBe('Fresh note');
+ expect(document.getElementById('research-notes-empty').style.display)
+ .toBe('none');
+ expect(SafeLogger.error).not.toHaveBeenCalled();
+});
+
+it('creates an owned starter note and encodes the returned navigation ID', async () => {
+ window.NotesShared.postJson.mockResolvedValue({ note_id: 'note /?#' });
+
+ await notes.addNoteForResearch();
+
+ expect(window.NotesShared.postJson).toHaveBeenCalledWith(
+ '/notes/api/research/research-1/notes',
+ {},
+ );
+ expect(document.getElementById('research-add-note-btn').disabled).toBe(true);
+ expect(window.location.href).toBe('/notes/note%20%2F%3F%23');
+});
+
+it('re-enables starter-note creation and reports a failed mutation', async () => {
+ window.NotesShared.postJson.mockRejectedValue(new Error('quota reached'));
+
+ await notes.addNoteForResearch();
+
+ expect(document.getElementById('research-add-note-btn').disabled)
+ .toBe(false);
+ expect(window.NotesShared.toast)
+ .toHaveBeenCalledWith('quota reached', 'error');
+});
+
+it('locks both save-as-note entry points around one in-flight mutation', async () => {
+ let rejectSave;
+ window.NotesShared.postJson.mockImplementationOnce(() => new Promise((resolve, reject) => {
+ rejectSave = reject;
+ }));
+
+ const first = notes.saveReportAsNote();
+ const duplicate = notes.saveReportAsNote();
+
+ expect(window.NotesShared.postJson).toHaveBeenCalledOnce();
+ expect(document.getElementById('research-save-as-note-btn').disabled)
+ .toBe(true);
+ expect(document.getElementById('research-save-as-note-top-btn').disabled)
+ .toBe(true);
+
+ rejectSave(new Error('save failed'));
+ await Promise.all([first, duplicate]);
+
+ expect(document.getElementById('research-save-as-note-btn').disabled)
+ .toBe(false);
+ expect(document.getElementById('research-save-as-note-top-btn').disabled)
+ .toBe(false);
+ expect(window.NotesShared.toast)
+ .toHaveBeenCalledWith('save failed', 'error');
+});
+
+it('saves one linked report copy and encodes its returned note ID', async () => {
+ window.NotesShared.postJson.mockResolvedValue({ note_id: 'copy/id' });
+
+ await notes.saveReportAsNote();
+
+ expect(window.NotesShared.postJson).toHaveBeenCalledWith(
+ '/notes/api/research/research-1/save-as-note',
+ {},
+ );
+ expect(window.location.href).toBe('/notes/copy%2Fid');
+});
+
+it('clips a bounded quote with an escaped markdown provenance label and refreshes', async () => {
+ const query = 'Report ](javascript:alert(1))\n[more]\\';
+ document.getElementById('result-query').textContent = query;
+ const quote = 'x'.repeat(4010);
+ window.NotesShared.postJson.mockResolvedValue({ note_id: 'clip-1' });
+
+ await notes.clipSelectionToNote({ text: quote });
+
+ expect(window.NotesShared.postJson).toHaveBeenCalledOnce();
+ const [url, body] = window.NotesShared.postJson.mock.calls[0];
+ expect(url).toBe('/notes/api/research/research-1/notes');
+ expect(body.title).toBe(`Clip: ${'x'.repeat(60)}`);
+ expect(body.content).toContain(`> ${'x'.repeat(4000)}…`);
+ expect(body.content).toContain('\\]\\(javascript:alert\\(1\\)\\)');
+ expect(body.content).toContain('\\[more\\]\\\\](/results/research-1)');
+ expect(body.content).not.toContain('](javascript:');
+ expect(window.NotesShared.toast)
+ .toHaveBeenCalledWith('Clipped to note', 'success');
+ await vi.waitFor(() => {
+ expect(globalThis.safeFetchWithAuth).toHaveBeenCalledWith(
+ '/notes/api/research/research-1/notes',
+ { credentials: 'same-origin' },
+ );
+ });
+});
+
+it('does not refresh after a failed clip mutation', async () => {
+ window.NotesShared.postJson.mockRejectedValue(new Error('clip rejected'));
+
+ await notes.clipSelectionToNote({ text: 'A useful excerpt' });
+
+ expect(window.NotesShared.toast)
+ .toHaveBeenCalledWith('clip rejected', 'error');
+ expect(globalThis.safeFetchWithAuth).not.toHaveBeenCalled();
+});
diff --git a/tests/js/components/research-search-favorite-runtime.test.js b/tests/js/components/research-search-favorite-runtime.test.js
new file mode 100644
index 0000000000..a8a307637c
--- /dev/null
+++ b/tests/js/components/research-search-favorite-runtime.test.js
@@ -0,0 +1,180 @@
+/**
+ * Live consumer contract for the research form's favorite-star callback.
+ * It executes the shipped callback body, including server-authoritative
+ * regrouping and sorting, instead of only checking the URL constant.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import '@js/config/urls.js';
+
+const RESEARCH_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/components/research.js',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in research.js`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function initialOptions() {
+ return [
+ {
+ value: 'searxng',
+ label: 'Alpha Search',
+ is_favorite: false,
+ group_label: 'General',
+ group_order: 4,
+ base_group_label: 'General',
+ base_group_order: 4,
+ },
+ {
+ value: 'brave',
+ label: 'Zulu Search',
+ is_favorite: false,
+ group_label: 'Privacy',
+ group_order: 3,
+ base_group_label: 'Privacy',
+ base_group_order: 3,
+ },
+ ];
+}
+
+function compileHarness(options = initialOptions()) {
+ const callback = extractFunction(
+ readFileSync(RESEARCH_SOURCE_PATH, 'utf8'),
+ 'handleSearchEngineFavoriteToggle',
+ );
+ const invalidateCacheKey = vi.fn();
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'URLS',
+ 'SafeLogger',
+ 'invalidateCacheKey',
+ 'initialSearchEngineOptions',
+ `
+ const CACHE_KEYS = {
+ SEARCH_ENGINES: 'deepResearch.searchEngines',
+ };
+ let searchEngineOptions = initialSearchEngineOptions;
+ ${callback}
+ return {
+ toggle: handleSearchEngineFavoriteToggle,
+ getOptions: () => searchEngineOptions,
+ };
+ `,
+ );
+ return {
+ runtime: factory(
+ window.URLS,
+ { log: vi.fn(), error: vi.fn() },
+ invalidateCacheKey,
+ options,
+ ),
+ invalidateCacheKey,
+ };
+}
+
+beforeEach(() => {
+ window.api = { getCsrfToken: vi.fn(() => 'favorite-csrf') };
+ window.ui = { showMessage: vi.fn() };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.ui;
+});
+
+it('posts the engine id and moves server-confirmed favorites to the first band', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ favorites: ['brave'],
+ is_favorite: true,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const { runtime, invalidateCacheKey } = compileHarness();
+
+ runtime.toggle('brave', null, true);
+
+ await vi.waitFor(() => {
+ expect(invalidateCacheKey).toHaveBeenCalledWith(
+ 'deepResearch.searchEngines',
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/search-favorites/toggle',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'favorite-csrf',
+ },
+ body: JSON.stringify({ engine_id: 'brave' }),
+ },
+ );
+ expect(runtime.getOptions().map(option => option.value)).toEqual([
+ 'brave',
+ 'searxng',
+ ]);
+ expect(runtime.getOptions()[0]).toMatchObject({
+ is_favorite: true,
+ group_label: 'Favorites',
+ group_order: 0,
+ });
+ expect(runtime.getOptions()[1]).toMatchObject({
+ is_favorite: false,
+ group_label: 'General',
+ group_order: 4,
+ });
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Search engine added to favorites',
+ 'success',
+ 2000,
+ );
+});
+
+it('does not mutate or report success when FastAPI rejects the toggle', async () => {
+ const options = initialOptions();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 403,
+ json: vi.fn().mockResolvedValue({ detail: 'favorite not allowed' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const { runtime, invalidateCacheKey } = compileHarness(options);
+
+ runtime.toggle('brave', null, true);
+
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating favorites: favorite not allowed',
+ 'error',
+ 3000,
+ );
+ });
+ expect(runtime.getOptions()).toEqual(options);
+ expect(invalidateCacheKey).not.toHaveBeenCalled();
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith(
+ expect.stringContaining('added to'),
+ 'success',
+ 2000,
+ );
+});
diff --git a/tests/js/components/research-settings-failure-runtime.test.js b/tests/js/components/research-settings-failure-runtime.test.js
new file mode 100644
index 0000000000..b745c419e8
--- /dev/null
+++ b/tests/js/components/research-settings-failure-runtime.test.js
@@ -0,0 +1,159 @@
+/** Isolated research bootstrap recovery contract for a failed settings GET. */
+
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+const RESEARCH_TEMPLATE = readFileSync(resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/research.html',
+), 'utf8');
+
+const AVAILABLE_MODELS = '/settings/api/available-models';
+const AVAILABLE_ENGINES = '/settings/api/available-search-engines';
+const SETTINGS = '/settings/api';
+
+function response(body, { ok = true, status = 200 } = {}) {
+ return Promise.resolve({
+ ok,
+ status,
+ statusText: ok ? 'OK' : 'Unavailable',
+ json: vi.fn().mockResolvedValue(body),
+ text: vi.fn().mockResolvedValue(JSON.stringify(body)),
+ });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ sessionStorage.clear();
+ localStorage.clear();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.ui;
+ delete window.RESEARCH_STATUS;
+ delete window.RESEARCH_TERMINAL_STATES;
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+});
+
+it('releases initialization and applies one rerun when settings bootstrap fails', async () => {
+ vi.resetModules();
+ sessionStorage.clear();
+ localStorage.clear();
+ sessionStorage.setItem('rerunConfig', JSON.stringify({
+ query: 'Recovered after settings outage',
+ mode: 'detailed',
+ }));
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture.
+ document.body.innerHTML = RESEARCH_TEMPLATE;
+ // Jinja macro calls remain text when the checked-in template is loaded
+ // directly, so supply the two rendered dropdown widgets that research.js
+ // owns in the browser.
+ const renderedDropdowns = document.createElement('div');
+ renderedDropdowns.innerHTML = `
+ <input id="model" data-initial-value="">
+ <input id="model_hidden" name="llm.model">
+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
+ <button type="button" id="model-refresh"><i></i></button>
+ <input id="search_engine" data-initial-value="searxng">
+ <input id="search_engine_hidden" name="search.tool" value="searxng">
+ <div id="search-engine-dropdown">
+ <div id="search-engine-dropdown-list"></div>
+ </div>
+ <button type="button" id="search_engine-refresh"><i></i></button>
+ `;
+ document.getElementById('research-form').appendChild(renderedDropdowns);
+
+ window.api = { getCsrfToken: vi.fn(() => 'research-csrf') };
+ window.ui = { showAlert: vi.fn(), showMessage: vi.fn() };
+ window.RESEARCH_STATUS = {
+ QUEUED: 'queued',
+ IN_PROGRESS: 'in_progress',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ SUSPENDED: 'suspended',
+ PENDING: 'pending',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'failed', 'error', 'cancelled', 'suspended',
+ ]);
+
+ const dropdowns = new Map();
+ window.setupCustomDropdown = vi.fn((input, _list, getOptions, onSelect) => {
+ dropdowns.set(input.id, { getOptions, onSelect });
+ return {};
+ });
+ window.updateDropdownOptions = vi.fn();
+
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === AVAILABLE_MODELS) {
+ return response({
+ provider_options: [{
+ value: 'OLLAMA',
+ label: 'Ollama',
+ is_cloud: false,
+ }],
+ providers: {
+ ollama_models: [{
+ value: 'qwen3:4b',
+ name: 'Qwen 3',
+ provider: 'OLLAMA',
+ }],
+ },
+ });
+ }
+ if (String(url).startsWith(AVAILABLE_ENGINES)) {
+ return response({
+ engine_options: [{ value: 'searxng', label: 'SearXNG' }],
+ });
+ }
+ if (url === SETTINGS && (!options.method || options.method === 'GET')) {
+ return response(
+ { detail: 'settings temporarily unavailable' },
+ { ok: false, status: 503 },
+ );
+ }
+ return response({ status: 'ok' });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('requestIdleCallback', vi.fn(callback => callback()));
+
+ await import('@js/config/constants.js');
+ await import('@js/config/urls.js');
+ await import('@js/utils/alert-helpers.js');
+ await import('@js/security/xss-protection.js');
+ await import('@js/utils/form-validation.js');
+ await import('@js/components/research.js');
+ await import('@js/components/settings_sync.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('query').value)
+ .toBe('Recovered after settings outage');
+ expect(sessionStorage.getItem('rerunConfig')).toBeNull();
+ expect(document.getElementById('mode-detailed').checked).toBe(true);
+ expect(dropdowns.has('model')).toBe(true);
+ });
+
+ fetchMock.mockClear();
+ dropdowns.get('model').onSelect('recovered-model-3299', null);
+
+ await vi.waitFor(() => {
+ const writes = fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/settings/api/llm.model' && options.method === 'PUT'
+ ));
+ expect(writes).toHaveLength(1);
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/llm.model',
+ expect.objectContaining({
+ method: 'PUT',
+ headers: expect.objectContaining({
+ 'X-CSRFToken': 'research-csrf',
+ }),
+ body: JSON.stringify({ value: 'recovered-model-3299' }),
+ }),
+ );
+});
diff --git a/tests/js/components/research.test.js b/tests/js/components/research.test.js
index 85b3999c90..798fd38001 100644
--- a/tests/js/components/research.test.js
+++ b/tests/js/components/research.test.js
@@ -58,15 +58,19 @@ function buildForm() {
<div class="ldr-advanced-options-panel ldr-expanded" id="advanced-options-panel" role="group">
<select id="model_provider"><option value="OLLAMA" selected>Ollama</option></select>
- <input type="text" id="model">
- <input type="hidden" id="model_hidden" value="">
- <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
- <button type="button" id="model-refresh"></button>
-
- <input type="text" id="search_engine">
- <input type="hidden" id="search_engine_hidden" value="searxng">
- <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
- <button type="button" id="search_engine-refresh"></button>
+ <div class="ldr-model-control">
+ <input type="text" id="model">
+ <input type="hidden" id="model_hidden" value="">
+ <div id="model-dropdown"><div id="model-dropdown-list"></div></div>
+ <button type="button" id="model-refresh"></button>
+ </div>
+
+ <div class="ldr-search-engine-control">
+ <input type="text" id="search_engine">
+ <input type="hidden" id="search_engine_hidden" value="searxng">
+ <div id="search-engine-dropdown"><div id="search-engine-dropdown-list"></div></div>
+ <button type="button" id="search_engine-refresh"></button>
+ </div>
<select id="strategy"><option value="source-based" selected>source-based</option><option value="langgraph-agent">LangGraph Agent</option></select>
<input id="iterations" value="2">
@@ -196,6 +200,56 @@ describe('research form fixture fidelity', () => {
});
});
+describe('research form — submission ownership', () => {
+ it('coalesces rapid keyboard/form submits and removes only its own overlay', async () => {
+ let resolveRequest;
+ const pendingRequest = new Promise(resolve => {
+ resolveRequest = resolve;
+ });
+ fetchMock.mockImplementationOnce(() => pendingRequest);
+ document.getElementById('model_hidden').value = 'qwen3:4b';
+
+ document.getElementById('query').dispatchEvent(new KeyboardEvent(
+ 'keydown',
+ {
+ key: 'Enter',
+ ctrlKey: true,
+ bubbles: true,
+ cancelable: true,
+ },
+ ));
+ submitForm();
+
+ expect(callsTo(START_RESEARCH)).toHaveLength(1);
+ expect(document.querySelectorAll('.ldr-loading-overlay')).toHaveLength(1);
+ expect(document.getElementById('start-research-btn').disabled).toBe(true);
+
+ const ownedOverlay = document.querySelector('.ldr-loading-overlay');
+ const unrelatedOverlay = document.createElement('div');
+ unrelatedOverlay.className = 'ldr-loading-overlay';
+ unrelatedOverlay.dataset.owner = 'unrelated';
+ document.body.prepend(unrelatedOverlay);
+
+ resolveRequest({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({
+ status: 'error',
+ message: 'stubbed completion',
+ }),
+ text: () => Promise.resolve(''),
+ });
+
+ await vi.waitFor(() => {
+ expect(ownedOverlay.isConnected).toBe(false);
+ expect(document.getElementById('start-research-btn').disabled)
+ .toBe(false);
+ });
+ expect(unrelatedOverlay.isConnected).toBe(true);
+ unrelatedOverlay.remove();
+ });
+});
+
describe('research form — model-required guard', () => {
it('blocks submission, shows an inline error, and focuses the model field when no model is selected', () => {
document.getElementById('model_hidden').value = '';
@@ -248,6 +302,11 @@ describe('research form — model-required guard', () => {
const calls = callsTo(START_RESEARCH);
expect(calls).toHaveLength(1);
+ expect(calls[0][1].method).toBe('POST');
+ expect(calls[0][1].headers).toEqual({
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'test-csrf',
+ });
// The chosen model is included in the request payload.
const body = JSON.parse(calls[0][1].body);
expect(body.model).toBe('qwen3:4b');
@@ -990,6 +1049,68 @@ describe('research form — malformed response resilience', () => {
expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
});
+ it('does not trust a success-shaped body from a non-ok response', async () => {
+ fetchMock.mockImplementationOnce(() => Promise.resolve({
+ ok: false,
+ status: 503,
+ json: () => Promise.resolve({
+ status: 'success',
+ research_id: 'must-not-redirect',
+ }),
+ text: () => Promise.resolve(''),
+ }));
+ const progressPageSpy = vi.spyOn(window.URLBuilder, 'progressPage')
+ .mockReturnValue(window.location.href);
+
+ try {
+ submitForm();
+ await flush();
+
+ expect(progressPageSpy).not.toHaveBeenCalled();
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Failed to start research');
+ expect(document.getElementById('start-research-btn').disabled)
+ .toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ } finally {
+ progressPageSpy.mockRestore();
+ }
+ });
+
+ it.each([
+ ['missing', undefined],
+ ['blank', ' '],
+ ])('does not redirect when a successful response has a %s research ID', async (
+ _label,
+ researchId,
+ ) => {
+ fetchMock.mockImplementationOnce(() => Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({
+ status: 'success',
+ research_id: researchId,
+ }),
+ text: () => Promise.resolve(''),
+ }));
+ const progressPageSpy = vi.spyOn(window.URLBuilder, 'progressPage')
+ .mockReturnValue(window.location.href);
+
+ try {
+ submitForm();
+ await flush();
+
+ expect(progressPageSpy).not.toHaveBeenCalled();
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Failed to start research');
+ expect(document.getElementById('start-research-btn').disabled)
+ .toBe(false);
+ expect(document.querySelector('.ldr-loading-overlay')).toBeNull();
+ } finally {
+ progressPageSpy.mockRestore();
+ }
+ });
+
it('surfaces a top-of-form alert with a fallback message when the body has no message field', async () => {
fetchMock.mockImplementationOnce(() => Promise.resolve({
ok: false,
@@ -1344,6 +1465,19 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
return Array.from(list.querySelectorAll('.ldr-custom-dropdown-item'));
}
+ async function waitForOptionDisabled(value, expectedDisabled) {
+ let option;
+ await vi.waitFor(() => {
+ option = openDropdownAndReadOptions().find(
+ element => element.getAttribute('data-value') === value
+ );
+ expect(option).toBeDefined();
+ expect(option.classList.contains('ldr-custom-dropdown-item--disabled'))
+ .toBe(expectedDisabled);
+ });
+ return option;
+ }
+
function decorateForScope(opt, scope, primary) {
if (scope === 'private_only') {
if (opt.value === 'library' || opt.category === 'Local RAG') {
@@ -1377,6 +1511,7 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
hidden.value = 'arxiv';
const input = document.getElementById('search_engine');
input.value = '';
+ document.getElementById('strategy').value = 'source-based';
fetchMock.mockClear();
});
@@ -1423,16 +1558,13 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
expect(rendered.length).toBe(FULL_OPTIONS.length);
// Arxiv (public) is denied under private_only; library (the
// local primary) is allowed by carve-out.
- const arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
- const library = rendered.find((el) => el.getAttribute('data-value') === 'library');
- expect(arxiv).toBeDefined();
- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ const arxiv = await waitForOptionDisabled('arxiv', true);
+ const library = await waitForOptionDisabled('library', false);
expect(arxiv.getAttribute('aria-disabled')).toBe('true');
const reason = arxiv.querySelector('.ldr-dropdown-item-disabled-reason');
expect(reason).not.toBeNull();
expect(reason.textContent).toMatch(/not a local source under Private only/i);
// The local primary is allowed (carve-out) and not disabled.
- expect(library.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
expect(library.getAttribute('aria-disabled')).toBeNull();
});
@@ -1452,9 +1584,7 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
// The local library entry is now disabled (local source under
// public-only is denied).
- let rendered = openDropdownAndReadOptions();
- let lib = rendered.find((el) => el.getAttribute('data-value') === 'library');
- expect(lib.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ await waitForOptionDisabled('library', true);
// 2. Switch to private_only.
scope.value = 'private_only';
@@ -1463,9 +1593,7 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
await flush();
// The local library entry is now allowed.
- rendered = openDropdownAndReadOptions();
- lib = rendered.find((el) => el.getAttribute('data-value') === 'library');
- expect(lib.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ await waitForOptionDisabled('library', false);
});
it('disables primary if it violates the active egress scope', async () => {
@@ -1482,10 +1610,8 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
await flush();
await flush();
- const rendered = openDropdownAndReadOptions();
- const arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
// arxiv is a public engine so under private_only it must be disabled
- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ await waitForOptionDisabled('arxiv', true);
});
it('does not request egress filtering under "Adaptive" scope so all primary options remain selectable', async () => {
@@ -1633,8 +1759,6 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
it('keeps the user\'s current selection when it is still visible after an update', async () => {
// When the current selection survives the options refresh (still allowed),
// the reconcile must NOT touch it.
- document.getElementById('search_engine_hidden').value = 'library';
- document.getElementById('search_engine').value = 'Library';
fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
ok: true, status: 200,
json: () => Promise.resolve({ engines: [], engine_options: [] }),
@@ -1647,6 +1771,21 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
await flush();
await flush();
+ // Select library through the real dropdown callback so both the DOM
+ // fields and the module-private selectedSearchEngineValue agree.
+ const library = openDropdownAndReadOptions().find(
+ option => option.getAttribute('data-value') === 'library'
+ );
+ expect(library).toBeDefined();
+ library.click();
+ await flush();
+ await flush();
+
+ // A subsequent options refresh must preserve that live selection.
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
// library is allowed under adaptive scope so it must stay selected
expect(document.getElementById('search_engine_hidden').value).toBe('library');
});
@@ -1680,6 +1819,46 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
expect(hasPrimary).toBe(true);
});
+ it('uses the submitted hidden primary when cached dropdown state diverges', async () => {
+ fetchMock.mockImplementation((url) => Promise.resolve(stubEngines(url) || {
+ ok: true, status: 200,
+ json: () => Promise.resolve({ engines: [], engine_options: [] }),
+ text: () => Promise.resolve(''),
+ }));
+
+ // First select library through the real dropdown so the module cache
+ // owns a different value from the form field used below.
+ document.getElementById('policy_egress_scope').value = 'adaptive';
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+ const library = openDropdownAndReadOptions().find(
+ option => option.getAttribute('data-value') === 'library'
+ );
+ expect(library).toBeDefined();
+ library.click();
+ await flush();
+ await flush();
+
+ // A form hydration/reconciliation path updates the submitted value.
+ // Scope classification must use that value, not the stale cache.
+ const hidden = document.getElementById('search_engine_hidden');
+ hidden.value = 'arxiv';
+ fetchMock.mockClear();
+ const scope = document.getElementById('policy_egress_scope');
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change'));
+ await flush();
+ await flush();
+
+ const privateOnlyCall = getEnginesCalls().find(([url]) => (
+ url.includes('egress_scope=private_only')
+ ));
+ expect(privateOnlyCall).toBeDefined();
+ expect(privateOnlyCall[0]).toContain('primary=arxiv');
+ expect(privateOnlyCall[0]).not.toContain('primary=library');
+ });
+
it('reclassifies using the just-clicked primary, not the previous one (issue #5204 follow-up)', async () => {
// Regression: the hidden input's change listener fires before
// the dropdown's onSelect callback (custom_dropdown.js), which
@@ -1705,9 +1884,7 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
await flush();
// Under private_only, arxiv (public) is disabled.
- let rendered = openDropdownAndReadOptions();
- let arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
+ await waitForOptionDisabled('arxiv', true);
// User clicks library. library is a local engine, so it is
// selectable under private_only.
@@ -1735,11 +1912,8 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
// The dropdown has re-rendered with the new disabled set:
// arxiv loses its primary carve-out and is now denied under
// private_only (because the re-fetch used primary=library).
- rendered = openDropdownAndReadOptions();
- arxiv = rendered.find((el) => el.getAttribute('data-value') === 'arxiv');
- expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
- const library = rendered.find((el) => el.getAttribute('data-value') === 'library');
- expect(library.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
+ await waitForOptionDisabled('arxiv', true);
+ await waitForOptionDisabled('library', false);
});
it('ignores a superseded (older) response when a newer fetch is in flight (issue #5204 follow-up)', async () => {
@@ -1816,8 +1990,15 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
// Resolve the SECOND (newer) request first.
responders[1].resolve();
- await flush();
- await flush();
+ await vi.waitFor(() => {
+ const github = openDropdownAndReadOptions().find(
+ (el) => el.getAttribute('data-value') === 'github'
+ );
+ expect(github).toBeDefined();
+ expect(
+ github.classList.contains('ldr-custom-dropdown-item--disabled')
+ ).toBe(false);
+ });
// Then resolve the FIRST (older, now superseded) request.
responders[0].resolve();
@@ -1829,7 +2010,7 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
// under private_only (public source under private), so the disabled
// state of github is the visible signal. With primary=library, the
// library entry is the carve-out under both scopes, so we deliberately
-// check github instead.
+ // check github instead.
const rendered = openDropdownAndReadOptions();
const github = rendered.find((el) => el.getAttribute('data-value') === 'github');
expect(github).toBeDefined();
@@ -1840,14 +2021,20 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
const fetchPromises = [];
fetchMock.mockImplementation((url) => {
+ const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
+ if (!urlStr.includes('available-search-engines')) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(''),
+ });
+ }
let resFn;
const p = new Promise((res) => {
resFn = res;
});
- const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
- if (urlStr.includes('available-search-engines')) {
- fetchPromises.push({ resolve: resFn });
- }
+ fetchPromises.push({ resolve: resFn });
return p;
});
@@ -1901,14 +2088,20 @@ describe('research form — scope-aware search engine dropdown (issue #5204)', (
const fetchPromises = [];
fetchMock.mockImplementation((url) => {
+ const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
+ if (!urlStr.includes('available-search-engines')) {
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve({}),
+ text: () => Promise.resolve(''),
+ });
+ }
let resFn;
const p = new Promise((res) => {
resFn = res;
});
- const urlStr = typeof url === 'string' ? url : (url && url.toString ? url.toString() : '');
- if (urlStr.includes('available-search-engines')) {
- fetchPromises.push({ resolve: resFn });
- }
+ fetchPromises.push({ resolve: resFn });
return p;
});
@@ -1967,8 +2160,6 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// to a different strategy. The backend's ``_precheck_collection_agent_enabled``
// is the second backstop for direct API callers; this is the UX layer.
- const ENGINES_URL = '/settings/api/available-search-engines';
-
const FULL_OPTIONS = [
{ value: 'collection_disabled', label: 'Indian History (Collection)',
category: 'Local RAG', requires_api_key: false, is_favorite: false,
@@ -2016,6 +2207,17 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
sel.dispatchEvent(new Event('change'));
}
+ async function waitForOptionState(value, disabled) {
+ await vi.waitFor(() => {
+ const option = getOption(value);
+ expect(option).toBeDefined();
+ expect(
+ option.classList.contains('ldr-custom-dropdown-item--disabled')
+ ).toBe(disabled);
+ });
+ return getOption(value);
+ }
+
beforeEach(() => {
// Reset to source-based so each test starts from a known strategy.
const strategy = document.getElementById('strategy');
@@ -2035,10 +2237,7 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// reads #strategy at call time.
setStrategy('langgraph-agent');
document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
- await flush();
- await flush();
-
- const disabled = getOption('collection_disabled');
+ const disabled = await waitForOptionState('collection_disabled', true);
const enabled = getOption('collection_enabled');
const arxiv = getOption('arxiv');
@@ -2059,10 +2258,7 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// source-based never consults the agent_enabled flag, so the
// collection is selectable regardless of the flag value.
document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
- await flush();
- await flush();
-
- const disabled = getOption('collection_disabled');
+ const disabled = await waitForOptionState('collection_disabled', false);
expect(disabled.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
expect(disabled.getAttribute('aria-disabled')).toBeNull();
});
@@ -2070,17 +2266,13 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
it('switching from source-based to LangGraph disables the collection', async () => {
// 1. Start with source-based: the collection is enabled.
document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
- await flush();
- await flush();
- let coll = getOption('collection_disabled');
+ let coll = await waitForOptionState('collection_disabled', false);
expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
// 2. Switch to LangGraph. No server re-fetch needed — the
// strategy reapplier re-maps the existing options in memory.
setStrategy('langgraph-agent');
- await flush();
-
- coll = getOption('collection_disabled');
+ coll = await waitForOptionState('collection_disabled', true);
expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
expect(coll.getAttribute('aria-disabled')).toBe('true');
});
@@ -2089,16 +2281,12 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// 1. Start with LangGraph: the collection is disabled.
setStrategy('langgraph-agent');
document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
- await flush();
- await flush();
- let coll = getOption('collection_disabled');
+ let coll = await waitForOptionState('collection_disabled', true);
expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(true);
// 2. Switch back to source-based.
setStrategy('source-based');
- await flush();
-
- coll = getOption('collection_disabled');
+ coll = await waitForOptionState('collection_disabled', false);
expect(coll.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
});
@@ -2109,8 +2297,7 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// engines when the backend hasn't been updated.
setStrategy('langgraph-agent');
document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
- await flush();
- await flush();
+ await waitForOptionState('collection_disabled', true);
const arxiv = getOption('arxiv');
expect(arxiv.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
@@ -2123,7 +2310,8 @@ describe('research form — LangGraph agent_enabled dropdown filter', () => {
// ?egress_scope=) MUST still render every option as enabled
// when the strategy isn't LangGraph.
setStrategy('source-based');
- await flush();
+ document.getElementById('policy_egress_scope').dispatchEvent(new Event('change'));
+ await waitForOptionState('collection_disabled', false);
for (const opt of FULL_OPTIONS.filter(o => !o.egress || o.egress.allowed !== false)) {
const el = getOption(opt.value);
expect(el.classList.contains('ldr-custom-dropdown-item--disabled')).toBe(false);
diff --git a/tests/js/components/results-display-runtime.test.js b/tests/js/components/results-display-runtime.test.js
new file mode 100644
index 0000000000..fc5fd136ee
--- /dev/null
+++ b/tests/js/components/results-display-runtime.test.js
@@ -0,0 +1,365 @@
+/**
+ * Results-page rendering contracts across current and transitional report
+ * response shapes. These exercise the real component bootstrap rather than a
+ * duplicate renderer so metadata, navigation, downloads, and XSS fallbacks
+ * stay wired together.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'results-display-3299';
+const REPORT_URL = `/api/report/${RESEARCH_ID}`;
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+const originalReadyState = Object.getOwnPropertyDescriptor(
+ document,
+ 'readyState',
+);
+
+function renderPage() {
+ document.body.innerHTML = `
+ <button id="back-to-history">History</button>
+ <button id="view-metrics-btn">Metrics</button>
+ <button id="export-markdown-btn" disabled>Markdown</button>
+ <button id="download-pdf-btn" disabled>PDF</button>
+ <span id="result-query"></span>
+ <span id="result-date"></span>
+ <span id="result-mode"></span>
+ <main id="results-content"></main>
+ <div id="context-overflow-warning" style="display: none">
+ <span id="context-overflow-message"></span>
+ <a id="context-overflow-action">Details</a>
+ </div>
+ `;
+}
+
+function responseJson(payload) {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function installFetch(payload, contextResponse = { ok: false, status: 404 }) {
+ const fetchMock = vi.fn(input => {
+ const url = String(input);
+ if (url === REPORT_URL) return Promise.resolve(responseJson(payload));
+ if (url === CONTEXT_URL) return Promise.resolve(contextResponse);
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ return fetchMock;
+}
+
+function bootstrap() {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+}
+
+beforeAll(async () => {
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ await import('@js/components/results.js');
+});
+
+beforeEach(() => {
+ renderPage();
+ window.history.replaceState({}, '', `/results/${RESEARCH_ID}`);
+ vi.stubGlobal('alert', vi.fn());
+ vi.stubGlobal('URLValidator', {
+ safeAssign: vi.fn((target, attribute, value) => {
+ if (target instanceof Element) target.setAttribute(attribute, value);
+ return true;
+ }),
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.ui;
+ delete window.Prism;
+ delete window.sanitizeHtml;
+ delete window.escapeHtml;
+ document.body.replaceChildren();
+ window.history.replaceState({}, '', '/');
+});
+
+afterAll(() => {
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+});
+
+it('renders FastAPI report metadata and keeps both page routes canonical', async () => {
+ const renderMarkdown = vi.fn(() => '<article>Rendered report</article>');
+ const highlightAllUnder = vi.fn();
+ window.ui = { renderMarkdown };
+ window.Prism = { highlightAllUnder };
+ vi.spyOn(window.formatting, 'formatDate').mockReturnValue('Sep 1, 2026');
+ vi.spyOn(window.formatting, 'formatMode').mockReturnValue('Detailed Report');
+
+ const fetchMock = installFetch({
+ content: '# Report body',
+ created_at: '2026-09-01T10:00:00Z',
+ metadata: {
+ processed_query: 'Processed subscription query',
+ query: 'Original query',
+ duration_seconds: 125,
+ mode: 'detailed',
+ },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('#results-content article')?.textContent)
+ .toBe('Rendered report');
+ });
+ expect(fetchMock).toHaveBeenCalledWith(REPORT_URL);
+ expect(renderMarkdown).toHaveBeenCalledWith('# Report body');
+ expect(highlightAllUnder).toHaveBeenCalledWith(
+ document.getElementById('results-content'),
+ );
+ expect(document.getElementById('result-query').textContent)
+ .toBe('Processed subscription query');
+ expect(document.getElementById('result-date').textContent)
+ .toBe('Sep 1, 2026 (2m 5s)');
+ expect(document.getElementById('result-mode').textContent)
+ .toBe('Detailed Report');
+ expect(document.getElementById('export-markdown-btn').disabled).toBe(false);
+ expect(document.getElementById('download-pdf-btn').disabled).toBe(false);
+
+ document.getElementById('view-metrics-btn').click();
+ document.getElementById('back-to-history').click();
+
+ expect(URLValidator.safeAssign).toHaveBeenNthCalledWith(
+ 1,
+ window.location,
+ 'href',
+ `/details/${RESEARCH_ID}`,
+ );
+ expect(URLValidator.safeAssign).toHaveBeenNthCalledWith(
+ 2,
+ window.location,
+ 'href',
+ '/history/',
+ );
+});
+
+it('infers a detailed mode for stored FastAPI reports whose mode is null', async () => {
+ window.ui = { renderMarkdown: vi.fn(() => '<article>Detailed body</article>') };
+ const formatMode = vi.spyOn(window.formatting, 'formatMode')
+ .mockReturnValue('Detailed Report');
+ installFetch({
+ content: '# Report\n## Section\n### Finding',
+ metadata: {
+ query: 'Older stored report',
+ mode: null,
+ },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('result-mode').textContent)
+ .toBe('Detailed Report');
+ });
+ expect(formatMode).toHaveBeenCalledWith('detailed');
+});
+
+it('extracts display metadata from a transitional markdown-only report', async () => {
+ window.ui = {
+ renderMarkdown: vi.fn(content => `<article>${content}</article>`),
+ };
+ vi.spyOn(window.formatting, 'formatDate').mockReturnValue('Formatted date');
+ installFetch({
+ content: [
+ '# Table of Contents',
+ 'Navigation',
+ '## Actual research question',
+ 'Generated at: 2026-08-31T20:00:00Z',
+ '### Detailed findings',
+ ].join('\n'),
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('result-query').textContent)
+ .toBe('Actual research question');
+ });
+ expect(document.getElementById('result-date').textContent)
+ .toBe('Formatted date');
+ expect(document.getElementById('result-mode').textContent)
+ .toBe('Detailed');
+ expect(window.ui.renderMarkdown).toHaveBeenCalledOnce();
+});
+
+it('supports the nested research response used by stored legacy reports', async () => {
+ window.ui = {
+ renderMarkdown: vi.fn(() => '<article>Legacy report</article>'),
+ };
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL')
+ .mockReturnValue('blob:stored-report');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ vi.spyOn(window.formatting, 'formatDate').mockReturnValue('Legacy date');
+ vi.spyOn(window.formatting, 'formatMode').mockReturnValue('Quick Summary');
+ installFetch({
+ research: {
+ content: '# Stored report',
+ prompt: 'Stored research prompt',
+ created_at: '2025-01-01T00:00:00Z',
+ duration: 9,
+ research_mode: 'quick',
+ },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('#results-content article')?.textContent)
+ .toBe('Legacy report');
+ });
+ expect(window.ui.renderMarkdown).toHaveBeenCalledWith('# Stored report');
+ expect(document.getElementById('result-query').textContent)
+ .toBe('Stored research prompt');
+ expect(document.getElementById('result-date').textContent)
+ .toBe('Legacy date (9 seconds)');
+ expect(document.getElementById('result-mode').textContent)
+ .toBe('Quick Summary');
+
+ document.getElementById('export-markdown-btn').click();
+ const exportedBlob = createObjectURL.mock.calls[0][0];
+ expect(await exportedBlob.text()).toContain('# Stored report');
+ expect(await exportedBlob.text()).not.toContain('```json');
+});
+
+it('sanitizes an HTML report even when its metadata omits a mode', async () => {
+ const unsafeHtml = '<img src=x onerror="alert(1)"><p>Trusted text</p>';
+ window.sanitizeHtml = vi.fn(() => '<p>Sanitized report</p>');
+ installFetch({
+ html: unsafeHtml,
+ metadata: { query: 'Stored HTML report' },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('results-content').textContent)
+ .toBe('Sanitized report');
+ });
+ expect(window.sanitizeHtml).toHaveBeenCalledWith(unsafeHtml);
+ expect(document.querySelector('#results-content img')).toBeNull();
+ expect(document.getElementById('result-query').textContent)
+ .toBe('Stored HTML report');
+ expect(document.getElementById('result-mode').textContent).toBe('Quick');
+});
+
+it('preserves a valid empty FastAPI report for rendering and markdown export', async () => {
+ const renderMarkdown = vi.fn(() => '<article data-empty>Empty report</article>');
+ window.ui = { renderMarkdown };
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL')
+ .mockReturnValue('blob:empty-report');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ installFetch({
+ content: '',
+ summary: '',
+ sources: [],
+ findings: [],
+ metadata: {
+ query: 'Research with no generated text',
+ mode: null,
+ created_at: null,
+ },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('[data-empty]')?.textContent)
+ .toBe('Empty report');
+ });
+ expect(renderMarkdown).toHaveBeenCalledWith('');
+ expect(document.getElementById('result-query').textContent)
+ .toBe('Research with no generated text');
+ expect(document.getElementById('result-mode').textContent).toBe('Quick');
+
+ document.getElementById('export-markdown-btn').click();
+ const exportedText = await createObjectURL.mock.calls[0][0].text();
+ expect(exportedText).toContain(
+ '# Research Results: Research with no generated text',
+ );
+ expect(exportedText).not.toContain('```json');
+ expect(exportedText).not.toContain('"content"');
+});
+
+it('escapes report markdown when the shared renderer is unavailable', async () => {
+ const unsafeReport = '# <img src=x onerror="alert(1)"> & findings';
+ installFetch({
+ content: unsafeReport,
+ metadata: { query: 'Security fallback' },
+ });
+
+ bootstrap();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('#results-content pre')?.textContent)
+ .toBe(unsafeReport);
+ });
+ expect(document.querySelector('#results-content img')).toBeNull();
+ expect(document.getElementById('results-content').innerHTML)
+ .toContain('&lt;img src=x onerror="alert(1)"&gt;');
+});
+
+it('downloads the displayed report as markdown and releases its object URL', async () => {
+ window.ui = { renderMarkdown: vi.fn(() => '<article>Export me</article>') };
+ const createObjectURL = vi.spyOn(URL, 'createObjectURL')
+ .mockReturnValue('blob:markdown-report');
+ const revokeObjectURL = vi.spyOn(URL, 'revokeObjectURL')
+ .mockImplementation(() => {});
+ const anchorClick = vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ installFetch({
+ content: '## Final findings',
+ created_at: '2026-09-01T10:00:00Z',
+ metadata: {
+ query: 'Exported query',
+ mode: 'quick',
+ },
+ });
+
+ bootstrap();
+ await vi.waitFor(() => {
+ expect(document.getElementById('export-markdown-btn').disabled)
+ .toBe(false);
+ });
+
+ document.getElementById('export-markdown-btn').click();
+
+ expect(anchorClick).toHaveBeenCalledOnce();
+ const blob = createObjectURL.mock.calls[0][0];
+ expect(blob.type).toBe('text/markdown');
+ expect(await blob.text()).toContain('# Research Results: Exported query');
+ expect(await blob.text()).toContain('- **Mode:** Quick Summary');
+ expect(await blob.text()).toContain('## Final findings');
+ expect(URLValidator.safeAssign).toHaveBeenCalledWith(
+ expect.any(window.HTMLAnchorElement),
+ 'href',
+ 'blob:markdown-report',
+ );
+ const downloadLink = URLValidator.safeAssign.mock.calls.find(
+ ([, attribute, value]) => (
+ attribute === 'href' && value === 'blob:markdown-report'
+ ),
+ )[0];
+ expect(downloadLink.download).toBe(`research_${RESEARCH_ID}.md`);
+ expect(createObjectURL.mock.calls[0][0]).toBe(blob);
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:markdown-report');
+});
diff --git a/tests/js/components/results-error-recovery.test.js b/tests/js/components/results-error-recovery.test.js
new file mode 100644
index 0000000000..763779299e
--- /dev/null
+++ b/tests/js/components/results-error-recovery.test.js
@@ -0,0 +1,124 @@
+/**
+ * Results-page migration regressions.
+ *
+ * Exercise the real page bootstrap and observe the recovery UI produced for
+ * report-loading failures. The home link is especially important after the
+ * FastAPI migration: it must return to the mounted research page, rather than
+ * to a removed Flask-era route.
+ */
+
+import '@js/config/urls.js';
+
+const REPORT_PATH = '/api/report/migration-3299';
+const originalFetch = globalThis.fetch;
+const originalReadyState = Object.getOwnPropertyDescriptor(document, 'readyState');
+
+function buildResultsPage() {
+ document.body.innerHTML = `
+ <button id="export-markdown-btn">Export</button>
+ <button id="download-pdf-btn">PDF</button>
+ <div id="results-content"></div>
+ `;
+}
+
+function dispatchPageLoad(path = '/results/migration-3299') {
+ window.history.replaceState({}, '', path);
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+}
+
+function recoveryLink() {
+ return document.querySelector('#results-content a');
+}
+
+beforeAll(async () => {
+ // Register the component's normal DOMContentLoaded bootstrap so each test
+ // can exercise a fresh DOM fixture without adding a test-only export.
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ await import('@js/components/results.js');
+});
+
+beforeEach(() => {
+ buildResultsPage();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+afterAll(() => {
+ globalThis.fetch = originalFetch;
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+});
+
+describe('results page error recovery', () => {
+ it('offers a return to research when the migrated report route responds with an error', async () => {
+ globalThis.fetch = vi.fn(() => Promise.resolve({
+ ok: false,
+ status: 404,
+ }));
+
+ dispatchPageLoad();
+
+ await vi.waitFor(() => {
+ expect(recoveryLink()).not.toBeNull();
+ });
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(REPORT_PATH);
+ expect(document.querySelector('[role="alert"]').textContent).toContain(
+ 'Error loading research results: HTTP error 404',
+ );
+ expect(recoveryLink().textContent).toContain('Back to Research');
+ expect(recoveryLink().getAttribute('href')).toBe('/');
+ expect(document.getElementById('export-markdown-btn').disabled).toBe(true);
+ expect(document.getElementById('download-pdf-btn').disabled).toBe(true);
+ });
+
+ it('keeps the same recovery destination after a network failure', async () => {
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('connection lost')));
+
+ dispatchPageLoad();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain(
+ 'connection lost',
+ );
+ });
+
+ expect(recoveryLink().getAttribute('href')).toBe('/');
+ });
+
+ it('renders server failure details as text without corrupting the recovery link', async () => {
+ const unsafeMessage = '<img src=x onerror="alert(1)"> unavailable';
+ globalThis.fetch = vi.fn(() => Promise.reject(new Error(unsafeMessage)));
+
+ dispatchPageLoad();
+
+ await vi.waitFor(() => {
+ expect(document.querySelector('[role="alert"]')?.textContent).toContain(
+ unsafeMessage,
+ );
+ });
+
+ expect(document.querySelector('#results-content img')).toBeNull();
+ expect(recoveryLink().getAttribute('href')).toBe('/');
+ });
+
+ it('provides recovery without making a request when the results URL has no research id', () => {
+ globalThis.fetch = vi.fn();
+
+ dispatchPageLoad('/results/');
+
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ expect(document.querySelector('[role="alert"]').textContent).toContain(
+ 'Research ID not found in URL',
+ );
+ expect(recoveryLink().getAttribute('href')).toBe('/');
+ });
+});
diff --git a/tests/js/components/results-export-migration-contract.test.js b/tests/js/components/results-export-migration-contract.test.js
new file mode 100644
index 0000000000..419fb2cc8a
--- /dev/null
+++ b/tests/js/components/results-export-migration-contract.test.js
@@ -0,0 +1,272 @@
+/**
+ * Results-page export contracts affected by the FastAPI migration.
+ *
+ * POST /api/v1/* is no longer CSRF-exempt, so exercise the real results
+ * component bootstrap and its actual export buttons to ensure every report
+ * export carries the token minted for the current browser session.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'migration-3299-export';
+const REPORT_URL = `/api/report/${RESEARCH_ID}`;
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+const CSRF_TOKEN = 'csrf-migration-3299';
+const originalReadyState = Object.getOwnPropertyDescriptor(document, 'readyState');
+
+const formatCases = [
+ ['LaTeX', 'export-latex-btn', 'latex', 'tex'],
+ ['Quarto', 'export-quarto-btn', 'quarto', 'qmd'],
+ ['ODT', 'export-odt-btn', 'odt', 'odt'],
+ ['RIS', 'export-ris-btn', 'ris', 'ris'],
+];
+
+function buildResultsPage() {
+ document.body.innerHTML = `
+ <main id="results-content"></main>
+ <button id="export-markdown-btn" disabled>Markdown</button>
+ <button id="download-pdf-btn" disabled>PDF</button>
+ <button id="export-latex-btn">LaTeX</button>
+ <button id="export-quarto-btn">Quarto</button>
+ <button id="export-odt-btn">ODT</button>
+ <button id="export-ris-btn">RIS</button>
+ `;
+}
+
+function createFetchMock(exportUrl) {
+ return vi.fn(input => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Completed migration report',
+ metadata: { query: 'FastAPI export coverage' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === exportUrl) {
+ return Promise.resolve({
+ ok: true,
+ blob: vi.fn().mockResolvedValue(new Blob(['exported report'])),
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+function bootstrapResults(fetchMock) {
+ vi.stubGlobal('fetch', fetchMock);
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+}
+
+beforeAll(async () => {
+ // Register one real DOMContentLoaded bootstrap listener. Dispatching the
+ // event per test reinitializes the component against each fresh fixture.
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ await import('@js/components/results.js');
+});
+
+beforeEach(() => {
+ buildResultsPage();
+ window.history.replaceState({}, '', `/results/${RESEARCH_ID}`);
+ window.api = { getCsrfToken: vi.fn(() => CSRF_TOKEN) };
+
+ vi.stubGlobal('alert', vi.fn());
+ vi.stubGlobal('URLValidator', {
+ safeAssign: vi.fn((element, attribute, value) => {
+ element.setAttribute(attribute, value);
+ return true;
+ }),
+ });
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:migration-export');
+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {});
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ document.body.replaceChildren();
+ window.history.replaceState({}, '', '/');
+});
+
+afterAll(() => {
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+});
+
+describe('results format exports after the FastAPI migration', () => {
+ it.each(formatCases)(
+ '%s button POSTs to its exact /api/v1 URL with CSRF',
+ async (_label, buttonId, format, extension) => {
+ const exportUrl = `/api/v1/research/${RESEARCH_ID}/export/${format}`;
+ const fetchMock = createFetchMock(exportUrl);
+ bootstrapResults(fetchMock);
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(REPORT_URL);
+ expect(document.getElementById('download-pdf-btn').disabled)
+ .toBe(false);
+ });
+
+ document.getElementById(buttonId).click();
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(exportUrl, {
+ method: 'POST',
+ headers: { 'X-CSRFToken': CSRF_TOKEN },
+ });
+ expect(window.HTMLAnchorElement.prototype.click)
+ .toHaveBeenCalledOnce();
+ });
+
+ expect(window.api.getCsrfToken).toHaveBeenCalledOnce();
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(
+ 'blob:migration-export',
+ );
+ const downloadLink = URLValidator.safeAssign.mock.calls.find(
+ ([, attribute, value]) => (
+ attribute === 'href' && value === 'blob:migration-export'
+ ),
+ )[0];
+ expect(downloadLink.download)
+ .toBe(`research_${RESEARCH_ID}.${extension}`);
+ expect(alert).not.toHaveBeenCalled();
+ },
+ );
+
+ it('PDF button POSTs with CSRF, JSON content type, and same-origin credentials', async () => {
+ const exportUrl = `/api/v1/research/${RESEARCH_ID}/export/pdf`;
+ const fetchMock = createFetchMock(exportUrl);
+ bootstrapResults(fetchMock);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('download-pdf-btn').disabled)
+ .toBe(false);
+ });
+
+ document.getElementById('download-pdf-btn').click();
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(exportUrl, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': CSRF_TOKEN,
+ },
+ credentials: 'same-origin',
+ });
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith(
+ 'blob:migration-export',
+ );
+ });
+
+ expect(window.api.getCsrfToken).toHaveBeenCalledOnce();
+ expect(window.HTMLAnchorElement.prototype.click).toHaveBeenCalledOnce();
+ const downloadLink = URLValidator.safeAssign.mock.calls.find(
+ ([, attribute, value]) => (
+ attribute === 'href' && value === 'blob:migration-export'
+ ),
+ )[0];
+ expect(downloadLink.download).toBe(`research_${RESEARCH_ID}.pdf`);
+ expect(alert).not.toHaveBeenCalled();
+ });
+
+ it('surfaces FastAPI detail when a format export is rejected', async () => {
+ const exportUrl = `/api/v1/research/${RESEARCH_ID}/export/latex`;
+ const fetchMock = createFetchMock(exportUrl);
+ fetchMock.mockImplementation(input => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Export failure report',
+ metadata: { query: 'FastAPI error detail' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === exportUrl) {
+ return Promise.resolve({
+ ok: false,
+ json: vi.fn().mockResolvedValue({
+ detail: 'LaTeX conversion is unavailable',
+ }),
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ bootstrapResults(fetchMock);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('download-pdf-btn').disabled)
+ .toBe(false);
+ });
+ document.getElementById('export-latex-btn').click();
+
+ await vi.waitFor(() => {
+ expect(alert).toHaveBeenCalledWith(
+ 'Failed to export to latex: LaTeX conversion is unavailable',
+ );
+ });
+ expect(window.HTMLAnchorElement.prototype.click).not.toHaveBeenCalled();
+ });
+
+ it('restores the PDF button when generation fails', async () => {
+ const exportUrl = `/api/v1/research/${RESEARCH_ID}/export/pdf`;
+ const fetchMock = createFetchMock(exportUrl);
+ fetchMock.mockImplementation(input => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# PDF recovery report',
+ metadata: { query: 'PDF failure recovery' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === exportUrl) {
+ return Promise.resolve({ ok: false, status: 503 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ bootstrapResults(fetchMock);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('download-pdf-btn').disabled)
+ .toBe(false);
+ });
+ const pdfButton = document.getElementById('download-pdf-btn');
+ pdfButton.click();
+ expect(pdfButton.disabled).toBe(true);
+ expect(pdfButton.textContent).toContain('Generating PDF');
+
+ await vi.waitFor(() => {
+ expect(alert).toHaveBeenCalledWith(
+ 'Error generating PDF: HTTP error! status: 503',
+ );
+ });
+ expect(pdfButton.disabled).toBe(false);
+ expect(pdfButton.textContent).toContain('Download PDF');
+ expect(window.HTMLAnchorElement.prototype.click).not.toHaveBeenCalled();
+ });
+});
diff --git a/tests/js/components/results-rating-migration-contract.test.js b/tests/js/components/results-rating-migration-contract.test.js
new file mode 100644
index 0000000000..926aa01f7d
--- /dev/null
+++ b/tests/js/components/results-rating-migration-contract.test.js
@@ -0,0 +1,320 @@
+/**
+ * Live results-page contract for the migrated ratings API.
+ *
+ * Existing results tests cover report loading, exports, and context overflow;
+ * this keeps the independent GET/POST rating workflow tied to its browser DOM,
+ * CSRF header, and optional-detail payload semantics.
+ */
+
+import '@js/config/urls.js';
+
+const RESEARCH_ID = 'rating-migration-3299';
+const REPORT_URL = `/api/report/${RESEARCH_ID}`;
+const RATING_URL = `/metrics/api/ratings/${RESEARCH_ID}`;
+const CONTEXT_URL = `/api/research/${RESEARCH_ID}/context-overflow`;
+const originalReadyState = Object.getOwnPropertyDescriptor(
+ document,
+ 'readyState',
+);
+
+function renderPage() {
+ document.body.innerHTML = `
+ <main id="results-content"></main>
+ <button id="export-markdown-btn" disabled>Markdown</button>
+ <button id="download-pdf-btn" disabled>PDF</button>
+ <div id="research-rating">
+ <button class="ldr-star">1</button>
+ <button class="ldr-star">2</button>
+ <button class="ldr-star">3</button>
+ <button class="ldr-star">4</button>
+ <button class="ldr-star">5</button>
+ </div>
+ <button id="ldr-detailed-rating-toggle" style="display: none"
+ aria-expanded="false">Details ▾</button>
+ <section id="ldr-detailed-rating" style="display: none">
+ <input class="ldr-dimension-slider" data-dimension="accuracy"
+ value="3"><span>3</span>
+ <input class="ldr-dimension-slider" data-dimension="relevance"
+ value="3"><span>3</span>
+ <textarea id="ldr-rating-feedback"></textarea>
+ </section>
+ `;
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+beforeAll(async () => {
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ await import('@js/components/results.js');
+});
+
+beforeEach(() => {
+ renderPage();
+ window.history.replaceState({}, '', `/results/${RESEARCH_ID}`);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-rating') };
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ document.body.replaceChildren();
+ window.history.replaceState({}, '', '/');
+});
+
+afterAll(() => {
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+});
+
+it('hydrates an existing rating and POSTs only user-touched details with CSRF', async () => {
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Rated migration report',
+ metadata: { query: 'Rating migration coverage' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === RATING_URL && !options.method) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ rating: 2 }),
+ });
+ }
+ if (url === RATING_URL && options.method === 'POST') {
+ return Promise.resolve({ ok: true });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(2);
+ });
+ expect(fetchMock).toHaveBeenCalledWith(RATING_URL);
+ expect(document.getElementById('ldr-detailed-rating-toggle').style.display)
+ .toBe('inline');
+
+ document.getElementById('ldr-detailed-rating-toggle').click();
+ const accuracy = document.querySelector(
+ '[data-dimension="accuracy"]',
+ );
+ accuracy.value = '5';
+ accuracy.dispatchEvent(new Event('input'));
+ document.getElementById('ldr-rating-feedback').value = ' Useful report ';
+ document.querySelectorAll('.ldr-star')[3].click();
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(RATING_URL, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-rating',
+ },
+ body: JSON.stringify({
+ rating: 4,
+ accuracy: 5,
+ feedback: 'Useful report',
+ }),
+ });
+ });
+ expect(window.api.getCsrfToken).toHaveBeenCalledOnce();
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(4);
+ expect(JSON.parse(fetchMock.mock.calls.find(
+ ([url, options = {}]) => (
+ url === RATING_URL && options.method === 'POST'
+ ),
+ )[1].body)).not.toHaveProperty('relevance');
+});
+
+it('does not let a pending initial rating overwrite a newer user selection', async () => {
+ const initialRating = deferred();
+ const savedRating = deferred();
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Rating ownership report',
+ metadata: { query: 'Rating ownership' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === RATING_URL && !options.method) {
+ return initialRating.promise;
+ }
+ if (url === RATING_URL && options.method === 'POST') {
+ return savedRating.promise;
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ document.querySelectorAll('.ldr-star')[3].click();
+
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(4);
+ expect(fetchMock).toHaveBeenCalledWith(
+ RATING_URL,
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ rating: 4 }),
+ }),
+ );
+
+ savedRating.resolve({ ok: true });
+ await Promise.resolve();
+ const initialRatingJson = vi.fn().mockResolvedValue({ rating: 2 });
+ initialRating.resolve({
+ ok: true,
+ json: initialRatingJson,
+ });
+ await vi.waitFor(() => {
+ expect(initialRatingJson).toHaveBeenCalledOnce();
+ });
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(4);
+});
+
+it('serializes rapid rating writes so the latest click persists last', async () => {
+ const firstSave = deferred();
+ const secondSave = deferred();
+ const postBodies = [];
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Rapid rating report',
+ metadata: { query: 'Rating ordering' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === RATING_URL && !options.method) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ rating: null }),
+ });
+ }
+ if (url === RATING_URL && options.method === 'POST') {
+ postBodies.push(JSON.parse(options.body));
+ return postBodies.length === 1 ? firstSave.promise : secondSave.promise;
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ const stars = document.querySelectorAll('.ldr-star');
+ stars[1].click();
+ stars[4].click();
+
+ expect(postBodies).toEqual([{ rating: 2 }]);
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(5);
+
+ firstSave.resolve({ ok: true });
+ await vi.waitFor(() => {
+ expect(postBodies).toEqual([{ rating: 2 }, { rating: 5 }]);
+ });
+ secondSave.resolve({ ok: true });
+ await vi.waitFor(() => {
+ expect(fetchMock.mock.calls.filter(([, options = {}]) => (
+ options.method === 'POST'
+ ))).toHaveLength(2);
+ });
+
+ expect(postBodies.at(-1)).toEqual({ rating: 5 });
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(5);
+});
+
+it.each(['non-ok response', 'network rejection'])(
+ 'still persists the latest queued rating after a first %s',
+ async (failureKind) => {
+ const firstSave = deferred();
+ const secondSave = deferred();
+ const postBodies = [];
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === REPORT_URL) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ content: '# Rating retry report',
+ metadata: { query: 'Rating retry ordering' },
+ }),
+ });
+ }
+ if (url === CONTEXT_URL) {
+ return Promise.resolve({ ok: false, status: 404 });
+ }
+ if (url === RATING_URL && !options.method) {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ rating: null }),
+ });
+ }
+ if (url === RATING_URL && options.method === 'POST') {
+ postBodies.push(JSON.parse(options.body));
+ return postBodies.length === 1
+ ? firstSave.promise
+ : secondSave.promise;
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ const stars = document.querySelectorAll('.ldr-star');
+ stars[0].click();
+ stars[3].click();
+ expect(postBodies).toEqual([{ rating: 1 }]);
+
+ if (failureKind === 'non-ok response') {
+ firstSave.resolve({ ok: false, status: 503 });
+ } else {
+ firstSave.resolve(Promise.reject(new Error('rating service offline')));
+ }
+ await vi.waitFor(() => {
+ expect(postBodies).toEqual([{ rating: 1 }, { rating: 4 }]);
+ });
+
+ secondSave.resolve({ ok: true });
+ await vi.waitFor(() => {
+ expect(fetchMock.mock.calls.filter(([, request = {}]) => (
+ request.method === 'POST'
+ ))).toHaveLength(2);
+ });
+
+ expect(postBodies.at(-1)).toEqual({ rating: 4 });
+ expect(document.querySelectorAll('.ldr-star.active')).toHaveLength(4);
+ },
+);
diff --git a/tests/js/components/save-to-collection-runtime.test.js b/tests/js/components/save-to-collection-runtime.test.js
new file mode 100644
index 0000000000..4c3cbbb38c
--- /dev/null
+++ b/tests/js/components/save-to-collection-runtime.test.js
@@ -0,0 +1,178 @@
+/**
+ * End-to-end browser contract for the results-page collection picker.
+ * It binds both migrated FastAPI calls and the response envelopes consumed
+ * between opening the modal and saving a research report.
+ */
+
+const RESEARCH_ID = 'research-3299';
+
+function installFixture() {
+ document.body.innerHTML = `
+ <button id="save-to-collection-btn">Save to collection</button>
+ <div id="saveToCollectionModal"></div>
+ <div id="collection-list-loading"></div>
+ <div id="collection-list" style="display: none">
+ <div id="collection-items"></div>
+ </div>
+ <div id="collection-error" style="display: none"></div>
+ <div id="collection-success" style="display: none"></div>
+ `;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ installFixture();
+ vi.stubGlobal('URLBuilder', {
+ extractResearchIdFromPattern: vi.fn(() => RESEARCH_ID),
+ build: (template, id) => template.replace('{id}', id),
+ });
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ COLLECTIONS: '/library/api/collections',
+ RESEARCH_ADD_TO_COLLECTION:
+ '/library/api/research/{id}/add-to-collection',
+ },
+ });
+ vi.stubGlobal('bootstrap', {
+ Modal: {
+ getOrCreateInstance: vi.fn(() => ({ show: vi.fn() })),
+ },
+ });
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-save-collection') };
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ document.body.replaceChildren();
+});
+
+it('loads collections, safely renders them, and POSTs the selected collection', async () => {
+ const collectionName = '<img src=x onerror=alert(1)> Evidence';
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/library/api/collections' && !options.method) {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [{
+ id: 'collection-a',
+ name: collectionName,
+ description: '<script>bad()</script>',
+ }],
+ }), { status: 200 }));
+ }
+ if (
+ url === `/library/api/research/${RESEARCH_ID}/add-to-collection`
+ && options.method === 'POST'
+ ) {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ documents_added: 3,
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ await import('@js/components/save_to_collection.js');
+
+ document.getElementById('save-to-collection-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelector(
+ 'button[data-collection-id="collection-a"]',
+ )).not.toBeNull();
+ });
+
+ const collectionButton = document.querySelector(
+ 'button[data-collection-id="collection-a"]',
+ );
+ expect(collectionButton.textContent).toContain(collectionName);
+ expect(collectionButton.querySelector('img')).toBeNull();
+ expect(collectionButton.querySelector('script')).toBeNull();
+
+ collectionButton.click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-success').style.display)
+ .toBe('block');
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ `/library/api/research/${RESEARCH_ID}/add-to-collection`,
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-save-collection',
+ },
+ body: JSON.stringify({ collection_id: 'collection-a' }),
+ },
+ );
+ const success = document.getElementById('collection-success');
+ expect(success.textContent).toContain(`Saved to ${collectionName}!`);
+ expect(success.textContent).toContain('3 documents added.');
+ expect(success.querySelector('img')).toBeNull();
+});
+
+it('renders a FastAPI detail when loading collections is rejected', async () => {
+ vi.stubGlobal('fetch', vi.fn(() => Promise.resolve(new Response(
+ JSON.stringify({ detail: 'Collection service is unavailable' }),
+ { status: 503 },
+ ))));
+ await import('@js/components/save_to_collection.js');
+
+ document.getElementById('save-to-collection-btn').click();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-error').textContent)
+ .toBe(
+ 'Failed to load collections: '
+ + 'Collection service is unavailable',
+ );
+ });
+ expect(document.getElementById('collection-list-loading').style.display)
+ .toBe('none');
+});
+
+it('restores collection choices after a rejected save with FastAPI detail', async () => {
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/library/api/collections' && !options.method) {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [
+ { id: 'collection-a', name: 'Primary evidence' },
+ { id: 'collection-b', name: 'Secondary evidence' },
+ ],
+ }), { status: 200 }));
+ }
+ if (options.method === 'POST') {
+ return Promise.resolve(new Response(JSON.stringify({
+ detail: 'Research is already saved to this collection',
+ }), { status: 409 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ await import('@js/components/save_to_collection.js');
+
+ document.getElementById('save-to-collection-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll(
+ 'button[data-collection-id]',
+ )).toHaveLength(2);
+ });
+ const primaryButton = document.querySelector(
+ 'button[data-collection-id="collection-a"]',
+ );
+ primaryButton.click();
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('collection-error').textContent)
+ .toBe('Research is already saved to this collection');
+ });
+ expect(Array.from(document.querySelectorAll(
+ 'button[data-collection-id]',
+ )).every(button => !button.disabled)).toBe(true);
+ expect(primaryButton.textContent).toContain('Primary evidence');
+});
diff --git a/tests/js/components/semantic-search.test.js b/tests/js/components/semantic-search.test.js
index bb64e7b641..6939a80d9f 100644
--- a/tests/js/components/semantic-search.test.js
+++ b/tests/js/components/semantic-search.test.js
@@ -1,13 +1,8 @@
/**
* Tests for components/semantic_search.js
*
- * Focus on the pure data-shaping helpers exposed via window.SemanticSearch:
- * - buildTieredResults: 3-tier merge with dedup + sort
- * - isSafeExternalUrl: URL scheme validation (security-critical)
- *
- * createSemanticResultCard and renderSnippet do DOM/markdown work and depend
- * on optional libraries (marked, DOMPurify) — exercised via integration in
- * library-search tests already.
+ * Covers the shared data-shaping helpers plus the actual snippet/card DOM
+ * runtime consumed by history, library, notes, and collection search.
*/
import '@js/components/semantic_search.js';
@@ -134,6 +129,156 @@ describe('SemanticSearch.buildTieredResults', () => {
});
});
+describe('SemanticSearch rendering helpers', () => {
+ let originalMarked;
+ let originalDOMPurify;
+ let originalURLBuilder;
+ let originalURLValidator;
+
+ beforeEach(() => {
+ originalMarked = window.marked;
+ originalDOMPurify = window.DOMPurify;
+ originalURLBuilder = window.URLBuilder;
+ originalURLValidator = window.URLValidator;
+ });
+
+ afterEach(() => {
+ if (originalMarked === undefined) delete window.marked;
+ else window.marked = originalMarked;
+ if (originalDOMPurify === undefined) delete window.DOMPurify;
+ else window.DOMPurify = originalDOMPurify;
+ if (originalURLBuilder === undefined) delete window.URLBuilder;
+ else window.URLBuilder = originalURLBuilder;
+ if (originalURLValidator === undefined) delete window.URLValidator;
+ else window.URLValidator = originalURLValidator;
+ document.body.replaceChildren();
+ delete window.__semanticXss;
+ });
+
+ it('escapes snippets when markdown dependencies are unavailable', () => {
+ delete window.marked;
+ delete window.DOMPurify;
+
+ const rendered = SS.renderSnippet(
+ '<img src=x onerror="window.__semanticXss=true"> migration',
+ 'migration',
+ );
+
+ expect(rendered).toContain('&lt;img');
+ expect(rendered).not.toContain('<img');
+ expect(rendered).not.toContain('<mark');
+ expect(window.__semanticXss).toBeUndefined();
+ });
+
+ it('sanitizes markdown and highlights only text, including regex terms', () => {
+ window.marked = {
+ parseInline: vi.fn(() => (
+ '<a title="migration a+b">migration</a> plus a+b'
+ )),
+ };
+ window.DOMPurify = {
+ sanitize: vi.fn(html => html),
+ };
+
+ const rendered = SS.renderSnippet('source', 'migration a+b');
+
+ expect(window.marked.parseInline).toHaveBeenCalledWith('source');
+ expect(window.DOMPurify.sanitize).toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ ALLOW_DATA_ATTR: false,
+ ALLOWED_ATTR: ['href', 'title', 'class'],
+ }),
+ );
+ expect(rendered).toContain('title="migration a+b"');
+ expect(rendered).toContain(
+ '<mark class="ldr-search-highlight">migration</mark>',
+ );
+ expect(rendered).toContain(
+ '<mark class="ldr-search-highlight">a+b</mark>',
+ );
+ });
+
+ it('flattens all tiers without mutating the caller\'s text result', () => {
+ const matched = { id: 'both', title: 'Matched' };
+ const tiered = {
+ tier1: [{
+ historyItem: matched,
+ semanticMatch: { similarity: 0.91, snippet: 'Best excerpt' },
+ }],
+ tier2: [{ historyItem: { id: 'text-only' } }],
+ tier3: [{ semanticResult: { research_id: 'semantic-only' } }],
+ };
+
+ expect(SS.flattenTieredResults(tiered)).toEqual([
+ {
+ id: 'both',
+ title: 'Matched',
+ similarity: 0.91,
+ content_preview: 'Best excerpt',
+ },
+ { id: 'text-only' },
+ { research_id: 'semantic-only' },
+ ]);
+ expect(matched).toEqual({ id: 'both', title: 'Matched' });
+ });
+
+ it('creates an inert escaped card and delegates safe card navigation', () => {
+ delete window.marked;
+ delete window.DOMPurify;
+ window.URLBuilder = {
+ resultsPage: vi.fn(id => `/results/${id}`),
+ };
+ window.URLValidator = {
+ isSafeUrl: vi.fn(() => false),
+ safeAssign: vi.fn(),
+ };
+
+ const card = SS.createSemanticResultCard({
+ research_id: 'research-3299',
+ research_title: '<img src=x onerror="window.__semanticXss=true">',
+ similarity: 87,
+ snippet: '<script>window.__semanticXss=true</script>',
+ url: 'javascript:window.__semanticXss=true',
+ type: 'report',
+ });
+ document.body.appendChild(card);
+
+ expect(card.textContent).toContain('<img src=x');
+ expect(card.querySelector('img')).toBeNull();
+ expect(card.querySelector('script')).toBeNull();
+ expect(card.querySelector('.ldr-semantic-result-source')).toBeNull();
+ expect(card.querySelector('a').getAttribute('href'))
+ .toBe('/results/research-3299');
+ expect(window.__semanticXss).toBeUndefined();
+
+ card.querySelector('a').dispatchEvent(
+ new MouseEvent('click', { bubbles: true }),
+ );
+ expect(window.URLValidator.safeAssign).not.toHaveBeenCalled();
+ card.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(window.URLValidator.safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ '/results/research-3299',
+ );
+
+ window.URLValidator.isSafeUrl.mockReturnValue(true);
+ const safeSourceCard = SS.createSemanticResultCard({
+ research_id: 'safe-source',
+ title: 'Safe source',
+ url: 'https://example.test/source?q=3299',
+ });
+ const sourceLink = safeSourceCard.querySelector(
+ '.ldr-semantic-result-source a',
+ );
+ expect(sourceLink.getAttribute('href'))
+ .toBe('https://example.test/source?q=3299');
+ expect(sourceLink.getAttribute('target')).toBe('_blank');
+ expect(sourceLink.getAttribute('rel')).toBe('noopener noreferrer');
+ });
+});
+
describe('SemanticSearch.isSafeExternalUrl', () => {
let savedValidator;
diff --git a/tests/js/components/settings-dashboard-runtime.test.js b/tests/js/components/settings-dashboard-runtime.test.js
new file mode 100644
index 0000000000..20057e87b3
--- /dev/null
+++ b/tests/js/components/settings-dashboard-runtime.test.js
@@ -0,0 +1,408 @@
+/**
+ * Direct runtime contracts for settings-dashboard behaviors that cannot be
+ * covered by the bulk-submit harness alone: aliased policy controls, redacted
+ * secrets, tab re-rendering, and destructive reset failure recovery.
+ */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const flushPromises = async (turns = 12) => {
+ for (let turn = 0; turn < turns; turn += 1) await Promise.resolve();
+};
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function setting(overrides) {
+ return {
+ category: 'general',
+ description: '',
+ editable: true,
+ max_value: null,
+ min_value: null,
+ options: null,
+ step: null,
+ visible: true,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.ui;
+ delete window.modelProvidersRequestInProgress;
+ delete window.searchEnginesRequestInProgress;
+ delete window.modelDropdownsInitialized;
+ delete window.searchEngineDropdownInitialized;
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+ document.body.replaceChildren();
+});
+
+it('renders aliased policy settings, clears a redacted secret, and recovers from reset failure', async () => {
+ vi.useFakeTimers();
+ document.head.insertAdjacentHTML(
+ 'beforeend',
+ '<meta name="csrf-token" content="csrf-settings-dashboard">',
+ );
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <input id="settings-search">
+ <button type="button" class="ldr-settings-tab active" data-tab="all">All</button>
+ <button type="button" class="ldr-settings-tab" data-tab="search">Search</button>
+ <button type="button" class="ldr-settings-tab" data-tab="app">App</button>
+ <div id="settings-alert"></div>
+ <div id="settings-content"></div>
+ <button id="reset-to-defaults-button" type="button">Reset defaults</button>
+ <button id="toggle-raw-config" type="button"><span id="toggle-text"></span></button>
+ <section id="raw-config" style="display: none">
+ <textarea id="raw_config_editor"></textarea>
+ </section>
+ <div id="llm.model-empty-warning" style="display: none"></div>
+ </form>
+ `;
+
+ const settings = {
+ 'app.nickname': setting({
+ name: 'Nickname',
+ type: 'APP',
+ ui_element: 'text',
+ value: 'original',
+ }),
+ 'policy.egress_scope': setting({
+ category: 'policy',
+ name: 'Egress Scope',
+ type: 'SEARCH',
+ ui_element: 'select',
+ value: 'adaptive',
+ options: [
+ { value: 'adaptive', label: 'Adaptive' },
+ { value: 'private_only', label: 'Private only' },
+ ],
+ }),
+ 'llm.require_local_endpoint': setting({
+ category: 'policy',
+ name: 'Require Local LLM Endpoint',
+ type: 'LLM',
+ ui_element: 'checkbox',
+ value: false,
+ }),
+ 'embeddings.require_local': setting({
+ category: 'policy',
+ name: 'Require Local Embeddings',
+ type: 'LLM',
+ ui_element: 'checkbox',
+ value: false,
+ }),
+ 'notifications.service_url': setting({
+ category: 'notifications',
+ name: 'Notification Service URL',
+ type: 'APP',
+ ui_element: 'textarea',
+ value: '[REDACTED]',
+ }),
+ 'llm.provider': setting({
+ category: 'llm_general',
+ name: 'Provider',
+ type: 'LLM',
+ ui_element: 'select',
+ value: 'ollama',
+ }),
+ 'llm.model': setting({
+ category: 'llm_general',
+ name: 'Model',
+ type: 'LLM',
+ ui_element: 'select',
+ value: 'llama3',
+ }),
+ 'search.tool': setting({
+ category: 'search_general',
+ name: 'Search Tool',
+ type: 'SEARCH',
+ ui_element: 'select',
+ value: 'searxng',
+ }),
+ 'report.options': setting({
+ category: 'report_parameters',
+ name: 'Report Options',
+ type: 'REPORT',
+ ui_element: 'json',
+ value: {
+ limit: 3,
+ enabled: false,
+ mode: 'ITERATION',
+ label: 'brief',
+ },
+ }),
+ };
+ const saveBodies = [];
+ let resetShouldFail = false;
+ let fixCorruptedSettings = false;
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(jsonResponse({ status: 'success', settings }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ return Promise.resolve(jsonResponse({
+ providers: {
+ ollama_models: [{ value: 'llama3', label: 'Llama 3' }],
+ openai_models: [{ value: 'gpt-4o', label: 'GPT-4o' }],
+ },
+ provider_options: [
+ { value: 'ollama', label: 'Ollama' },
+ { value: 'openai', label: 'OpenAI' },
+ ],
+ }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
+ return Promise.resolve(jsonResponse({
+ engine_options: [{ value: 'searxng', label: 'SearXNG' }],
+ }));
+ }
+ if (url === '/settings/api/data-location') {
+ return Promise.resolve(jsonResponse({
+ data_directory: '/tmp/ldr',
+ security_notice: { encrypted: false },
+ }));
+ }
+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
+ return Promise.resolve(jsonResponse({ enabled: false, count: 0, backups: [] }));
+ }
+ if (url === URLS.SETTINGS_API.SAVE_ALL_SETTINGS) {
+ const body = JSON.parse(options.body);
+ saveBodies.push(body);
+ const responseSettings = {};
+ Object.entries(body).forEach(([key, value]) => {
+ responseSettings[key] = { ...settings[key], value };
+ settings[key] = responseSettings[key];
+ });
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ settings: responseSettings,
+ }));
+ }
+ if (url === URLS.SETTINGS_API.RESET_TO_DEFAULTS && resetShouldFail) {
+ return Promise.resolve(jsonResponse({
+ detail: '<img src=x onerror=alert(1)> reset denied',
+ }, 422));
+ }
+ if (url === URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS && fixCorruptedSettings) {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ fixed_settings: [],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ window.ui = { showMessage: vi.fn() };
+ window.matchMedia = vi.fn(() => ({ matches: false }));
+ window.setupCustomDropdown = vi.fn((input) => ({
+ setValue: vi.fn(value => {
+ input.value = value;
+ }),
+ }));
+ window.updateDropdownOptions = vi.fn();
+
+ await import('@js/components/settings.js');
+ if (document.readyState === 'loading') {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+ await flushPromises();
+ await vi.advanceTimersByTimeAsync(301);
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toContain(URLS.SETTINGS_API.BASE);
+ expect(
+ document.getElementById('settings-content').innerHTML,
+ `settings requests: ${fetchMock.mock.calls.map(([url]) => url).join(', ')}`,
+ ).not.toBe('');
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('setting-notifications-service_url')).not.toBeNull();
+ });
+ const redactedInput = document.getElementById('setting-notifications-service_url');
+ expect(redactedInput.value).toBe('');
+ expect(redactedInput.dataset.redacted).toBe('true');
+ expect(redactedInput.placeholder).toContain('press Enter while empty to clear');
+
+ redactedInput.dispatchEvent(new KeyboardEvent('keydown', {
+ key: 'Enter',
+ bubbles: true,
+ cancelable: true,
+ }));
+ await flushPromises();
+ expect(saveBodies).toContainEqual({ 'notifications.service_url': '' });
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Service url updated',
+ 'success',
+ 6000,
+ );
+ expect(window.ui.showMessage.mock.calls.flat().join(' ')).not.toContain('[REDACTED]');
+
+ const localToggle = document.getElementById('setting-llm-require_local_endpoint');
+ const beforeCheckboxReversal = saveBodies.length;
+ localToggle.click();
+ localToggle.click();
+ await flushPromises(40);
+ expect(saveBodies.slice(beforeCheckboxReversal).map(body => body['llm.require_local_endpoint']))
+ .toEqual([true, false]);
+ expect(settings['llm.require_local_endpoint'].value).toBe(false);
+ expect(localToggle.checked).toBe(false);
+
+ const nickname = document.getElementById('setting-app-nickname');
+ const beforeTextReversal = saveBodies.length;
+ nickname.value = 'changed';
+ nickname.dispatchEvent(new Event('blur'));
+ nickname.value = 'original';
+ nickname.dispatchEvent(new Event('blur'));
+ await flushPromises(40);
+ expect(saveBodies.slice(beforeTextReversal).map(body => body['app.nickname']))
+ .toEqual(['changed', 'original']);
+ expect(settings['app.nickname'].value).toBe('original');
+ expect(nickname.value).toBe('original');
+
+ const providerSetup = window.setupCustomDropdown.mock.calls.find(
+ ([input]) => input.id === 'llm.provider',
+ );
+ expect(providerSetup).toBeDefined();
+ providerSetup[3]('openai');
+ await flushPromises();
+ expect(document.getElementById('llm.provider_hidden').value).toBe('openai');
+ expect(document.getElementById('llm.model_hidden').value).toBe('gpt-4o');
+ expect(window.updateDropdownOptions).toHaveBeenCalledWith(
+ document.getElementById('llm.model'),
+ [{ value: 'gpt-4o', label: 'GPT-4o', provider: 'OPENAI' }],
+ );
+ expect(saveBodies).toContainEqual({ 'llm.provider': 'openai' });
+
+ const reportEnabled = document.getElementById('setting-report-options_enabled');
+ const saveCountBeforeWrapperClick = saveBodies.length;
+ reportEnabled.closest('.ldr-boolean-property').click();
+ await flushPromises();
+ expect(reportEnabled.checked).toBe(true);
+ expect(saveBodies.slice(saveCountBeforeWrapperClick)).toEqual([{
+ 'report.options': {
+ limit: 3,
+ enabled: true,
+ mode: 'ITERATION',
+ label: 'brief',
+ },
+ }]);
+ expect(saveBodies.some(body => Object.hasOwn(
+ body,
+ 'report.options_enabled',
+ ))).toBe(false);
+
+ // The first response has not acknowledged false when the control returns
+ // to the original true value. Both intents must reach the server.
+ const beforeReversal = saveBodies.length;
+ reportEnabled.closest('.ldr-boolean-property').click();
+ reportEnabled.closest('.ldr-boolean-property').click();
+ await flushPromises(40);
+ expect(saveBodies.slice(beforeReversal).map(body => body['report.options'].enabled))
+ .toEqual([false, true]);
+ expect(settings['report.options'].value.enabled).toBe(true);
+ expect(reportEnabled.checked).toBe(true);
+
+ const reportLimit = document.getElementById('setting-report-options_limit');
+ reportLimit.value = '5';
+ reportLimit.dispatchEvent(new Event('input', { bubbles: true }));
+ reportLimit.dispatchEvent(new Event('blur', { bubbles: true }));
+ await flushPromises();
+ expect(saveBodies).toContainEqual({
+ 'report.options': {
+ limit: 5,
+ enabled: true,
+ mode: 'ITERATION',
+ label: 'brief',
+ },
+ });
+ expect(saveBodies.some(body => Object.hasOwn(
+ body,
+ 'report.options_limit',
+ ))).toBe(false);
+
+ const settingsSearch = document.getElementById('settings-search');
+ settingsSearch.value = 'egress scope';
+ settingsSearch.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(251);
+ expect(document.getElementById('setting-policy-egress_scope')).not.toBeNull();
+ expect(document.getElementById('setting-notifications-service_url')).toBeNull();
+
+ settingsSearch.value = '';
+ settingsSearch.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(251);
+ expect(document.getElementById('setting-notifications-service_url')).not.toBeNull();
+
+ document.querySelector('[data-tab="search"]').click();
+ await vi.advanceTimersByTimeAsync(101);
+ const scope = document.getElementById('setting-policy-egress_scope');
+ const embeddingsLocal = document.getElementById('setting-embeddings-require_local');
+ expect(scope).not.toBeNull();
+ expect(embeddingsLocal).not.toBeNull();
+
+ scope.value = 'private_only';
+ scope.dispatchEvent(new Event('change', { bubbles: true }));
+ await flushPromises();
+ expect(embeddingsLocal.checked).toBe(true);
+ expect(embeddingsLocal.disabled).toBe(true);
+ expect(document.getElementById(
+ 'setting-embeddings-require_local_hidden_fallback',
+ ).disabled).toBe(true);
+ expect(saveBodies).toContainEqual({ 'policy.egress_scope': 'private_only' });
+
+ scope.value = 'adaptive';
+ scope.dispatchEvent(new Event('change', { bubbles: true }));
+ await flushPromises();
+ expect(embeddingsLocal.checked).toBe(false);
+ expect(embeddingsLocal.disabled).toBe(false);
+
+ const confirmMock = vi.fn().mockReturnValue(false);
+ vi.stubGlobal('confirm', confirmMock);
+ document.getElementById('reset-to-defaults-button').click();
+ expect(fetchMock.mock.calls.some(([url]) => (
+ url === URLS.SETTINGS_API.RESET_TO_DEFAULTS
+ ))).toBe(false);
+
+ // Use the component's DOM fallback to prove a FastAPI detail remains
+ // inert when the destructive operation fails.
+ Object.defineProperty(window, 'ui', {
+ value: null,
+ writable: true,
+ configurable: true,
+ });
+ resetShouldFail = true;
+ confirmMock.mockReturnValue(true);
+ document.getElementById('reset-to-defaults-button').click();
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ URLS.SETTINGS_API.RESET_TO_DEFAULTS,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(document.getElementById('settings-alert').textContent).toContain(
+ '<img src=x onerror=alert(1)> reset denied',
+ );
+ expect(document.getElementById('settings-alert').querySelector('img')).toBeNull();
+
+ fixCorruptedSettings = true;
+ document.getElementById('fix-corrupted-button').click();
+ await flushPromises();
+ expect(fetchMock).toHaveBeenCalledWith(
+ URLS.SETTINGS_API.FIX_CORRUPTED_SETTINGS,
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(document.getElementById('settings-alert').textContent).toContain(
+ 'No corrupted settings were found.',
+ );
+});
diff --git a/tests/js/components/settings-fetch-error-handling.test.js b/tests/js/components/settings-fetch-error-handling.test.js
index 34a4d3e092..3ceda5ba0e 100644
--- a/tests/js/components/settings-fetch-error-handling.test.js
+++ b/tests/js/components/settings-fetch-error-handling.test.js
@@ -57,8 +57,8 @@ describe('settings request error handling', () => {
];
const excludedPatterns = [
'const response = await fetch(URLS.SETTINGS_API.OLLAMA_STATUS, {',
- 'window.modelProvidersRequestInProgress = fetch(url)',
- 'window.searchEnginesRequestInProgress = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)',
+ 'const request = fetch(url)',
+ 'const request = fetch(URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES)',
];
const handledCalls = SETTINGS_SOURCE.match(
/window\.api\.fetchWithErrorHandling\(/g,
diff --git a/tests/js/components/settings-refresh-ownership-runtime.test.js b/tests/js/components/settings-refresh-ownership-runtime.test.js
new file mode 100644
index 0000000000..fb3919be36
--- /dev/null
+++ b/tests/js/components/settings-refresh-ownership-runtime.test.js
@@ -0,0 +1,280 @@
+/**
+ * Runtime ownership contracts for settings discovery refreshes. Forced
+ * refreshes may overlap, so only the newest response may update dropdown data
+ * or release the shared in-flight promise.
+ */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+const flushPromises = async (turns = 16) => {
+ for (let turn = 0; turn < turns; turn += 1) await Promise.resolve();
+};
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function setting(overrides) {
+ return {
+ category: 'general',
+ description: '',
+ editable: true,
+ max_value: null,
+ min_value: null,
+ options: null,
+ step: null,
+ visible: true,
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.ui;
+ delete window.modelProvidersRequestInProgress;
+ delete window.searchEnginesRequestInProgress;
+ delete window.modelDropdownsInitialized;
+ delete window.searchEngineDropdownInitialized;
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+ delete window.matchMedia;
+ document.head.querySelector('[name="csrf-token"]')?.remove();
+ document.getElementById('settings-dynamic-styles')?.remove();
+ document.body.replaceChildren();
+});
+
+it('keeps the newest overlapping model and search refresh results', async () => {
+ vi.useFakeTimers();
+ document.head.insertAdjacentHTML(
+ 'beforeend',
+ '<meta name="csrf-token" content="csrf-refresh-ownership">',
+ );
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <input id="settings-search">
+ <button type="button" class="ldr-settings-tab active" data-tab="all">All</button>
+ <div id="settings-alert"></div>
+ <div id="settings-content"></div>
+ </form>
+ `;
+
+ const settings = {
+ 'llm.provider': setting({
+ category: 'llm_general',
+ name: 'Provider',
+ type: 'LLM',
+ ui_element: 'select',
+ value: 'ollama',
+ }),
+ 'llm.model': setting({
+ category: 'llm_general',
+ name: 'Model',
+ type: 'LLM',
+ ui_element: 'select',
+ value: 'baseline-model',
+ }),
+ 'search.tool': setting({
+ category: 'search_general',
+ name: 'Search Tool',
+ type: 'SEARCH',
+ ui_element: 'select',
+ value: 'baseline-engine',
+ }),
+ };
+ const baselineModels = {
+ providers: {
+ ollama_models: [{ value: 'baseline-model', label: 'Baseline model' }],
+ },
+ provider_options: [{ value: 'ollama', label: 'Ollama' }],
+ };
+ const baselineEngines = {
+ engine_options: [{ value: 'baseline-engine', label: 'Baseline engine' }],
+ };
+ const modelRefreshes = [];
+ const searchRefreshes = [];
+ let captureSearchRefreshes = false;
+ let currentModels = baselineModels;
+ let currentEngines = baselineEngines;
+
+ const fetchMock = vi.fn((url) => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(jsonResponse({ status: 'success', settings }));
+ }
+ if (url === '/settings/api/data-location') {
+ return Promise.resolve(jsonResponse({
+ data_directory: '/tmp/ldr',
+ security_notice: { encrypted: false },
+ }));
+ }
+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
+ return Promise.resolve(jsonResponse({ enabled: false, count: 0, backups: [] }));
+ }
+ if (url === `${URLS.SETTINGS_API.AVAILABLE_MODELS}?force_refresh=true`) {
+ const request = deferred();
+ modelRefreshes.push(request);
+ return request.promise;
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ return Promise.resolve(jsonResponse(currentModels));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
+ if (captureSearchRefreshes) {
+ const request = deferred();
+ searchRefreshes.push(request);
+ return request.promise;
+ }
+ return Promise.resolve(jsonResponse(currentEngines));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ window.ui = { showAlert: vi.fn(), showMessage: vi.fn() };
+ window.matchMedia = vi.fn(() => ({ matches: false }));
+ window.setupCustomDropdown = vi.fn((input) => ({
+ setValue: vi.fn(value => {
+ input.value = value;
+ }),
+ }));
+ window.updateDropdownOptions = vi.fn();
+
+ await import('@js/components/settings.js');
+ if (document.readyState === 'loading') {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+ await flushPromises();
+ await vi.advanceTimersByTimeAsync(301);
+ await flushPromises();
+
+ // Re-rendering a tab wires the refresh controls after their dynamic HTML
+ // has been inserted.
+ document.querySelector('[data-tab="all"]').click();
+ await vi.advanceTimersByTimeAsync(101);
+ await flushPromises();
+
+ const modelRefreshButton = document.getElementById('llm.model-refresh');
+ expect(modelRefreshButton).not.toBeNull();
+ modelRefreshButton.click();
+ modelRefreshButton.click();
+ expect(modelRefreshes).toHaveLength(2);
+
+ const staleModels = {
+ providers: {
+ stale_models: [{ value: 'stale-model', label: 'Stale model' }],
+ },
+ provider_options: [{ value: 'stale', label: 'Stale provider' }],
+ };
+ const newestModels = {
+ providers: {
+ newest_models: [{ value: 'newest-model', label: 'Newest model' }],
+ },
+ provider_options: [{ value: 'newest', label: 'Newest provider' }],
+ };
+ modelRefreshes[0].resolve(jsonResponse(staleModels));
+ await flushPromises();
+ expect(window.modelProvidersRequestInProgress).not.toBeNull();
+ expect(modelRefreshButton.classList.contains('ldr-loading')).toBe(true);
+
+ currentModels = newestModels;
+ modelRefreshes[1].resolve(jsonResponse(newestModels));
+ await flushPromises();
+ expect(window.modelProvidersRequestInProgress).toBeNull();
+ expect(modelRefreshButton.classList.contains('ldr-loading')).toBe(false);
+
+ const providerSetup = window.setupCustomDropdown.mock.calls
+ .filter(([input]) => input.id === 'llm.provider')
+ .at(-1);
+ expect(providerSetup).toBeDefined();
+ expect(providerSetup[2]()).toEqual([
+ expect.objectContaining({ value: 'newest', label: 'Newest provider' }),
+ ]);
+
+ // Exercise the inverse completion order as well: once the newer request
+ // has rendered, a late stale response must not replace its provider/model
+ // data. The earlier ordering above primarily pins loading-state ownership.
+ modelRefreshButton.click();
+ modelRefreshButton.click();
+ expect(modelRefreshes).toHaveLength(4);
+
+ const inverseNewestModels = {
+ providers: {
+ inverse_newest_models: [
+ { value: 'inverse-newest-model', label: 'Inverse newest model' },
+ ],
+ },
+ provider_options: [
+ { value: 'inverse-newest', label: 'Inverse newest provider' },
+ ],
+ };
+ const inverseStaleModels = {
+ providers: {
+ inverse_stale_models: [
+ { value: 'inverse-stale-model', label: 'Inverse stale model' },
+ ],
+ },
+ provider_options: [
+ { value: 'inverse-stale', label: 'Inverse stale provider' },
+ ],
+ };
+ currentModels = inverseNewestModels;
+ modelRefreshes[3].resolve(jsonResponse(inverseNewestModels));
+ await flushPromises();
+ expect(window.modelProvidersRequestInProgress).toBeNull();
+
+ modelRefreshes[2].resolve(jsonResponse(inverseStaleModels));
+ await flushPromises();
+ const inverseProviderSetup = window.setupCustomDropdown.mock.calls
+ .filter(([input]) => input.id === 'llm.provider')
+ .at(-1);
+ expect(inverseProviderSetup).toBeDefined();
+ expect(inverseProviderSetup[2]()).toEqual([
+ expect.objectContaining({
+ value: 'inverse-newest',
+ label: 'Inverse newest provider',
+ }),
+ ]);
+
+ const searchRefreshButton = document.getElementById('search.tool-refresh');
+ expect(searchRefreshButton).not.toBeNull();
+ captureSearchRefreshes = true;
+ searchRefreshButton.click();
+ searchRefreshButton.click();
+ expect(searchRefreshes).toHaveLength(2);
+
+ const newestEngines = {
+ engine_options: [{ value: 'newest-engine', label: 'Newest engine' }],
+ };
+ const staleEngines = {
+ engine_options: [{ value: 'stale-engine', label: 'Stale engine' }],
+ };
+ currentEngines = newestEngines;
+ searchRefreshes[1].resolve(jsonResponse(newestEngines));
+ await flushPromises();
+ expect(window.searchEnginesRequestInProgress).toBeNull();
+
+ searchRefreshes[0].resolve(jsonResponse(staleEngines));
+ await flushPromises();
+ const searchSetup = window.setupCustomDropdown.mock.calls
+ .filter(([input]) => input.id === 'search.tool')
+ .at(-1);
+ expect(searchSetup).toBeDefined();
+ expect(searchSetup[2]()).toEqual(newestEngines.engine_options);
+});
diff --git a/tests/js/components/settings-reset-ordering.test.js b/tests/js/components/settings-reset-ordering.test.js
new file mode 100644
index 0000000000..c935e43776
--- /dev/null
+++ b/tests/js/components/settings-reset-ordering.test.js
@@ -0,0 +1,100 @@
+/** Reset All must be ordered after edits already accepted by the page. */
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const response = (payload, status = 200) => new Response(JSON.stringify(payload), {
+ status, headers: { 'Content-Type': 'application/json' },
+});
+const submit = () => document.getElementById('settings-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+);
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ vi.spyOn(document, 'readyState', 'get').mockReturnValue('complete');
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <input id="theme" class="ldr-settings-input" name="app.theme" value="first">
+ <input id="locked" disabled>
+ <section id="raw-config" style="display: none">
+ <textarea id="raw_config_editor">{}</textarea>
+ </section>
+ <button id="reset-to-defaults-button" type="button">Reset All</button>
+ <div id="settings-alert"></div>
+ </form>`;
+ window.ui = { showMessage: vi.fn(), showAlert: vi.fn() };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ await import('@js/components/settings.js');
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.ui;
+ document.body.replaceChildren();
+});
+
+it('drains both the in-flight and queued save before committing defaults', async () => {
+ let releaseFirst;
+ const firstResponse = new Promise(resolve => { releaseFirst = resolve; });
+ const calls = [];
+ let serverValue = 'default';
+ const reload = vi.spyOn(window.location, 'reload').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn((url, options) => {
+ if (url === '/settings/reset_to_defaults') {
+ calls.push('RESET');
+ serverValue = 'default';
+ return Promise.resolve(response({ status: 'success' }));
+ }
+ const value = JSON.parse(options.body)['app.theme'];
+ calls.push(`SAVE ${value}`);
+ serverValue = value; // Commit in dispatch order, delay only the response.
+ const result = () => response({ status: 'success', settings: { 'app.theme': { value } } });
+ return value === 'first' ? firstResponse.then(result) : Promise.resolve(result());
+ }));
+
+ submit();
+ document.getElementById('theme').value = 'second';
+ submit();
+ document.getElementById('reset-to-defaults-button').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(calls).toEqual(['SAVE first']);
+ expect(document.getElementById('theme').disabled).toBe(true);
+ expect(document.getElementById('settings-form').inert).toBe(true);
+
+ releaseFirst();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(calls).toEqual(['SAVE first', 'SAVE second', 'RESET']);
+ expect(serverValue).toBe('default');
+ expect(window.ui.showAlert).toHaveBeenCalledWith(
+ 'Settings have been reset to defaults. Reloading page...',
+ 'success', true,
+ );
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(reload).toHaveBeenCalledOnce();
+ expect(serverValue).toBe('default');
+});
+
+it('restores editable controls after reset failure without enabling locked fields', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({ detail: 'Reset unavailable' }, 503))
+ .mockResolvedValueOnce(response({ status: 'success' }));
+ vi.stubGlobal('fetch', fetchMock);
+ document.getElementById('reset-to-defaults-button').click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(document.getElementById('theme').disabled).toBe(false);
+ expect(document.getElementById('settings-form').inert).toBeFalsy();
+ expect(document.getElementById('locked').disabled).toBe(true);
+ expect(document.getElementById('reset-to-defaults-button').disabled).toBe(false);
+ document.getElementById('theme').value = 'after-failure';
+ submit();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)['app.theme']).toBe('after-failure');
+});
diff --git a/tests/js/components/settings-scope-ownership.test.js b/tests/js/components/settings-scope-ownership.test.js
new file mode 100644
index 0000000000..78b6d9fe49
--- /dev/null
+++ b/tests/js/components/settings-scope-ownership.test.js
@@ -0,0 +1,158 @@
+/** Scope's visual override must not discard an in-flight local-only choice. */
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const localKeys = ['llm.require_local_endpoint', 'embeddings.require_local'];
+const response = payload => new Response(JSON.stringify(payload), {
+ status: 200, headers: { 'Content-Type': 'application/json' },
+});
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ vi.spyOn(document, 'readyState', 'get').mockReturnValue('complete');
+ vi.spyOn(window, 'matchMedia').mockReturnValue({ matches: false });
+ window.ui = { showMessage: vi.fn(), showAlert: vi.fn() };
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <div id="settings-alert"></div>
+ <div id="settings-content"></div>
+ <section id="raw-config" style="display: none">
+ <textarea id="raw_config_editor"></textarea>
+ </section>
+ </form>`;
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.ui;
+ delete window.modelProvidersRequestInProgress;
+ delete window.searchEnginesRequestInProgress;
+ delete window.modelDropdownsInitialized;
+ delete window.searchEngineDropdownInitialized;
+ document.body.replaceChildren();
+});
+
+async function mountDashboard(initialValue) {
+ const metadata = {
+ category: 'policy', description: '', editable: true, visible: true,
+ type: 'LLM', ui_element: 'checkbox', value: initialValue,
+ };
+ const settings = Object.fromEntries(localKeys.map(key => [
+ key, { ...metadata, name: key },
+ ]));
+ settings['policy.egress_scope'] = {
+ ...metadata, type: 'SEARCH', name: 'Egress scope', ui_element: 'select',
+ value: 'adaptive', options: [
+ { value: 'adaptive', label: 'Adaptive' },
+ { value: 'private_only', label: 'Private only' },
+ ],
+ };
+ const pending = [];
+ const writes = [];
+ vi.stubGlobal('fetch', vi.fn((url, options = {}) => {
+ if (url === URLS.SETTINGS_API.BASE) {
+ return Promise.resolve(response({ status: 'success', settings }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_MODELS) {
+ return Promise.resolve(response({ providers: {}, provider_options: [] }));
+ }
+ if (url === URLS.SETTINGS_API.AVAILABLE_SEARCH_ENGINES) {
+ return Promise.resolve(response({ engine_options: [] }));
+ }
+ if (url === '/settings/api/data-location') {
+ return Promise.resolve(response({ data_directory: '/tmp/ldr' }));
+ }
+ if (url === URLS.SETTINGS_API.BACKUP_STATUS) {
+ return Promise.resolve(response({ enabled: false, count: 0, backups: [] }));
+ }
+ if (url === URLS.SETTINGS_API.SAVE_ALL_SETTINGS) {
+ const body = JSON.parse(options.body);
+ writes.push(body);
+ const acknowledge = () => {
+ const updated = {};
+ for (const [key, value] of Object.entries(body)) {
+ settings[key] = { ...settings[key], value };
+ updated[key] = settings[key];
+ }
+ return response({ status: 'success', settings: updated });
+ };
+ if (localKeys.some(key => Object.hasOwn(body, key))) {
+ return new Promise(resolveResponse => {
+ pending.push(() => resolveResponse(acknowledge()));
+ });
+ }
+ return Promise.resolve(acknowledge());
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ }));
+ await import('@js/components/settings.js');
+ await vi.advanceTimersByTimeAsync(301);
+ return { settings, pending, writes };
+}
+
+function changeScope(value) {
+ const scope = document.getElementById('setting-policy-egress_scope');
+ scope.value = value;
+ scope.dispatchEvent(new Event('change', { bubbles: true }));
+}
+
+it.each(localKeys.flatMap(key => [false, true].flatMap(initialValue => [
+ { key, initialValue, acknowledgeBeforeUnlock: false },
+ { key, initialValue, acknowledgeBeforeUnlock: true },
+])))('preserves $key from $initialValue (acknowledgement before unlock: $acknowledgeBeforeUnlock)', async ({
+ key, initialValue, acknowledgeBeforeUnlock,
+}) => {
+ const { settings, pending } = await mountDashboard(initialValue);
+ const toggle = document.getElementById(`setting-${key.replaceAll('.', '-')}`);
+ expect(toggle.checked).toBe(initialValue);
+ toggle.click();
+ expect(pending).toHaveLength(1);
+ changeScope('private_only');
+ expect(toggle.checked).toBe(true);
+ expect(toggle.disabled).toBe(true);
+
+ if (acknowledgeBeforeUnlock) {
+ pending.shift()();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(toggle.checked).toBe(true);
+ expect(toggle.disabled).toBe(true);
+ }
+ changeScope('adaptive');
+ expect(toggle.checked).toBe(!initialValue);
+ expect(toggle.disabled).toBe(false);
+ if (!acknowledgeBeforeUnlock) pending.shift()();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(settings[key].value).toBe(!initialValue);
+ expect(toggle.checked).toBe(!initialValue);
+});
+
+it.each(localKeys)('restores the latest queued reversal of %s when leaving a scope lock', async key => {
+ const { settings, pending, writes } = await mountDashboard(false);
+ const toggle = document.getElementById(`setting-${key.replaceAll('.', '-')}`);
+ toggle.click();
+ toggle.click();
+ changeScope('private_only');
+
+ // The first ON is now confirmed, but the queued OFF still owns the control.
+ pending.shift()();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(settings[key].value).toBe(true);
+ expect(pending).toHaveLength(1);
+ changeScope('adaptive');
+ expect(toggle.checked).toBe(false);
+ pending.shift()();
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(writes.filter(body => Object.hasOwn(body, key)).map(body => body[key]))
+ .toEqual([true, false]);
+ expect(settings[key].value).toBe(false);
+ expect(toggle.checked).toBe(false);
+});
diff --git a/tests/js/components/settings-submit-runtime.test.js b/tests/js/components/settings-submit-runtime.test.js
new file mode 100644
index 0000000000..a9b74fb763
--- /dev/null
+++ b/tests/js/components/settings-submit-runtime.test.js
@@ -0,0 +1,590 @@
+/** Runtime contracts for the main settings form's bulk-save path. */
+
+import '@js/config/urls.js';
+import '@js/services/api.js';
+import '@js/utils/alert-helpers.js';
+import '@js/utils/provider-options.js';
+import '@js/utils/value-helpers.js';
+
+const flushPromises = async (turns = 8) => {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+};
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), {
+ status,
+ headers: { 'Content-Type': 'application/json' },
+ });
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
+function resetForm() {
+ const form = document.getElementById('settings-form');
+ form.className = '';
+ const theme = document.getElementById('app-theme');
+ theme.name = 'app.theme';
+ theme.value = 'light';
+ const reportOptions = document.getElementById('report-options');
+ reportOptions.name = 'report.options';
+ reportOptions.value = '{"citations":true}';
+ const enabled = document.getElementById('app-enabled');
+ enabled.name = 'app.enabled';
+ enabled.checked = false;
+ const searchOriginal = document.getElementById('search-options_original');
+ searchOriginal.name = 'search.options_original';
+ searchOriginal.value = '{}';
+ document.getElementById('search-options-limit').value = '3';
+ document.getElementById('search-options-safe').checked = true;
+ document.getElementById('search-options-mode').value = 'ITERATION';
+ document.getElementById('raw-config').style.display = 'block';
+ const rawEditor = document.getElementById('raw_config_editor');
+ rawEditor.removeAttribute('data-modified');
+ rawEditor.value = JSON.stringify({
+ app: { theme: 'dark', extra: 7 },
+ llm: { provider: 'openai' },
+ });
+ window.ui = { showMessage: vi.fn() };
+}
+
+function submitSettingsForm() {
+ document.getElementById('settings-form').dispatchEvent(new Event(
+ 'submit',
+ { bubbles: true, cancelable: true },
+ ));
+}
+
+beforeAll(async () => {
+ document.head.insertAdjacentHTML(
+ 'beforeend',
+ '<meta name="csrf-token" content="csrf-settings-submit">',
+ );
+ document.body.innerHTML = `
+ <form id="settings-form">
+ <button id="toggle-raw-config" type="button">
+ <span id="toggle-text">Hide JSON Configuration</span>
+ </button>
+ <input
+ id="app-theme"
+ class="ldr-settings-input"
+ name="app.theme"
+ value="light"
+ >
+ <textarea
+ id="report-options"
+ class="ldr-settings-textarea"
+ name="report.options"
+ >{"citations":true}</textarea>
+ <input
+ id="app-enabled"
+ class="ldr-settings-checkbox"
+ name="app.enabled"
+ type="checkbox"
+ >
+
+ <input
+ id="search-options_original"
+ name="search.options_original"
+ type="hidden"
+ value="{}"
+ >
+ <input
+ id="search-options-limit"
+ class="ldr-settings-input ldr-json-property-control"
+ data-parent-key="search.options"
+ data-property="limit"
+ value="3"
+ >
+ <input
+ id="search-options-safe"
+ class="ldr-settings-checkbox ldr-json-property-control"
+ data-parent-key="search.options"
+ data-property="safe"
+ type="checkbox"
+ checked
+ >
+ <select
+ id="search-options-mode"
+ class="ldr-settings-select ldr-json-property-control"
+ data-parent-key="search.options"
+ data-property="mode"
+ >
+ <option value="ITERATION" selected>Iteration</option>
+ <option value="NONE">None</option>
+ </select>
+
+ <section id="raw-config" style="display: block">
+ <textarea id="raw_config_editor"></textarea>
+ </section>
+ <div id="settings-alert"></div>
+ </form>
+ `;
+ resetForm();
+
+ const needsDomReady = document.readyState === 'loading';
+ await import('@js/components/settings.js');
+ if (needsDomReady) {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+});
+
+beforeEach(() => {
+ resetForm();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+afterAll(() => {
+ document.querySelector('meta[name="csrf-token"]')?.remove();
+ document.body.replaceChildren();
+ delete window.ui;
+});
+
+it('serializes the real form and sends the FastAPI bulk-save contract', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
+ status: 'success',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ submitSettingsForm();
+ expect(document.getElementById('settings-form').classList)
+ .toContain('ldr-saving');
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/settings/save_all_settings');
+ expect(options).toEqual(expect.objectContaining({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-settings-submit',
+ },
+ signal: expect.any(globalThis.AbortSignal),
+ }));
+ expect(JSON.parse(options.body)).toEqual({
+ 'app.theme': 'dark',
+ 'report.options': { citations: true },
+ 'app.enabled': false,
+ 'search.options': {
+ limit: 3,
+ safe: true,
+ mode: 'ITERATION',
+ },
+ 'app.extra': 7,
+ 'llm.provider': 'openai',
+ });
+ expect(document.getElementById('settings-form').classList)
+ .not.toContain('ldr-saving');
+ expect(document.getElementById('settings-form').classList)
+ .toContain('ldr-save-success');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ '6 settings saved',
+ 'success',
+ 6000,
+ );
+});
+
+it('surfaces a FastAPI detail error and clears the saving state', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
+ detail: 'backend rejected setting',
+ }, 422));
+ vi.stubGlobal('fetch', fetchMock);
+
+ submitSettingsForm();
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error saving settings: backend rejected setting',
+ 'error',
+ 5000,
+ );
+ expect(document.getElementById('settings-form').classList)
+ .not.toContain('ldr-saving');
+ expect(document.getElementById('settings-form').classList)
+ .not.toContain('ldr-save-success');
+});
+
+it('serializes same-key submits so the newest value reaches the server last', async () => {
+ const older = deferred();
+ const newer = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => older.promise)
+ .mockImplementationOnce(() => newer.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'older' },
+ });
+ submitSettingsForm();
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'newer' },
+ });
+ submitSettingsForm();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)['app.theme'])
+ .toBe('older');
+
+ older.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'older' } },
+ }));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)['app.theme'])
+ .toBe('newer');
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+
+ newer.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'newer' } },
+ }));
+ await flushPromises();
+
+ expect(JSON.parse(document.getElementById('raw_config_editor').value))
+ .toEqual(expect.objectContaining({
+ app: expect.objectContaining({ theme: 'newer' }),
+ }));
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+});
+
+it('does not block an unrelated setting behind an in-flight write', async () => {
+ const themeSave = deferred();
+ const reportSave = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => themeSave.promise)
+ .mockImplementationOnce(() => reportSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'parallel-theme' },
+ });
+ document.getElementById('toggle-raw-config').click();
+
+ document.getElementById('app-theme').removeAttribute('name');
+ document.getElementById('app-enabled').removeAttribute('name');
+ document.getElementById('search-options_original').removeAttribute('name');
+ document.getElementById('report-options').value = '{"citations":false}';
+ submitSettingsForm();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ 'app.theme': 'parallel-theme',
+ });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
+ 'report.options': { citations: false },
+ });
+
+ reportSave.resolve(jsonResponse({
+ status: 'success',
+ settings: {
+ 'report.options': { value: { citations: false } },
+ },
+ }));
+ await flushPromises();
+ themeSave.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'parallel-theme' } },
+ }));
+ await flushPromises();
+
+ expect(window.ui.showMessage).toHaveBeenCalledTimes(2);
+});
+
+it('preserves a dirty known raw key while an unrelated save settles', async () => {
+ const unrelatedSave = deferred();
+ const settingsSnapshot = {
+ 'app.theme': {
+ value: 'server-theme',
+ name: 'Theme',
+ ui_element: 'text',
+ },
+ 'report.options': {
+ value: { citations: true },
+ name: 'Report options',
+ ui_element: 'textarea',
+ },
+ 'app.enabled': { value: false, name: 'Enabled' },
+ 'search.options': { value: {}, name: 'Search options' },
+ 'app.extra': { value: 7, name: 'Extra' },
+ 'llm.provider': { value: 'openai', name: 'Provider' },
+ };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ settings: settingsSnapshot,
+ }))
+ .mockImplementationOnce(() => unrelatedSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ // Prime the real settings cache/editor, then start a report-only save
+ // while the raw editor is hidden.
+ submitSettingsForm();
+ await flushPromises();
+ window.ui.showMessage.mockClear();
+ document.getElementById('raw-config').style.display = 'none';
+ document.getElementById('app-theme').removeAttribute('name');
+ document.getElementById('app-enabled').removeAttribute('name');
+ document.getElementById('search-options_original').removeAttribute('name');
+ document.getElementById('report-options').value = '{"citations":false}';
+ submitSettingsForm();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
+ 'report.options': { citations: false },
+ });
+
+ // Open and edit the real raw control before the unrelated response lands.
+ document.getElementById('toggle-raw-config').click();
+ const rawEditor = document.getElementById('raw_config_editor');
+ const dirtyConfig = JSON.parse(rawEditor.value);
+ dirtyConfig.app.theme = 'unsaved-raw-theme';
+ rawEditor.value = JSON.stringify(dirtyConfig);
+ rawEditor.dispatchEvent(new Event('input', { bubbles: true }));
+ expect(rawEditor.getAttribute('data-modified')).toBe('true');
+
+ unrelatedSave.resolve(jsonResponse({
+ status: 'success',
+ settings: {
+ ...settingsSnapshot,
+ 'report.options': {
+ value: { citations: false },
+ name: 'Report options',
+ ui_element: 'textarea',
+ },
+ },
+ }));
+ await flushPromises();
+
+ expect(JSON.parse(rawEditor.value)).toEqual(expect.objectContaining({
+ app: expect.objectContaining({ theme: 'unsaved-raw-theme' }),
+ report: expect.objectContaining({
+ options: { citations: false },
+ }),
+ }));
+ expect(rawEditor.getAttribute('data-modified')).toBe('true');
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+});
+
+it('keeps a full-form save authoritative over an older raw-editor save', async () => {
+ const olderRawSave = deferred();
+ const newerFormSave = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderRawSave.promise)
+ .mockImplementationOnce(() => newerFormSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'raw-older' },
+ });
+ document.getElementById('toggle-raw-config').click();
+ expect(document.getElementById('raw-config').style.display).toBe('none');
+
+ document.getElementById('app-theme').value = 'form-newer';
+ submitSettingsForm();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ 'app.theme': 'raw-older',
+ });
+
+ olderRawSave.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'raw-older' } },
+ }));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)['app.theme'])
+ .toBe('form-newer');
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+
+ newerFormSave.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'form-newer' } },
+ }));
+ await flushPromises();
+
+ document.getElementById('toggle-raw-config').click();
+ expect(JSON.parse(document.getElementById('raw_config_editor').value))
+ .toEqual(expect.objectContaining({
+ app: expect.objectContaining({ theme: 'form-newer' }),
+ }));
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+});
+
+it('retains the confirmed value when a later queued save fails', async () => {
+ const savedRequest = deferred();
+ const rejectedRequest = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => savedRequest.promise)
+ .mockImplementationOnce(() => rejectedRequest.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'confirmed-theme' },
+ });
+ document.getElementById('toggle-raw-config').click();
+ document.getElementById('app-theme').value = 'rejected-theme';
+ submitSettingsForm();
+ expect(fetchMock).toHaveBeenCalledOnce();
+
+ savedRequest.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'confirmed-theme' } },
+ }));
+ await flushPromises();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+ expect(document.getElementById('app-theme').value).toBe('rejected-theme');
+
+ rejectedRequest.resolve(jsonResponse({ detail: 'Save rejected' }, 422));
+ await flushPromises();
+
+ document.getElementById('toggle-raw-config').click();
+ expect(JSON.parse(document.getElementById('raw_config_editor').value).app.theme)
+ .toBe('confirmed-theme');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error saving settings: Save rejected', 'error', 5000,
+ );
+ expect(document.getElementById('settings-form').classList)
+ .not.toContain('ldr-saving');
+});
+
+it('merges keys still owned by an older bulk save without replacing a newer overlap', async () => {
+ const olderBulkSave = deferred();
+ const newerSingleSave = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderBulkSave.promise)
+ .mockImplementationOnce(() => newerSingleSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: {
+ theme: 'bulk-older',
+ extra: 'bulk-only',
+ },
+ });
+ document.getElementById('toggle-raw-config').click();
+ document.getElementById('toggle-raw-config').click();
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'single-newer' },
+ });
+ document.getElementById('toggle-raw-config').click();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({
+ 'app.theme': 'bulk-older',
+ 'app.extra': 'bulk-only',
+ });
+
+ olderBulkSave.resolve(jsonResponse({
+ status: 'success',
+ settings: {
+ 'app.theme': { value: 'bulk-older' },
+ 'app.extra': { value: 'bulk-only' },
+ },
+ }));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
+ 'app.theme': 'single-newer',
+ });
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+ expect(window.ui.showMessage).toHaveBeenLastCalledWith(
+ expect.stringMatching(/^Extra: .* → .*bulk-only/),
+ 'success',
+ 6000,
+ );
+
+ newerSingleSave.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'single-newer' } },
+ }));
+ await flushPromises();
+
+ expect(window.ui.showMessage).toHaveBeenCalledTimes(2);
+ expect(window.ui.showMessage).toHaveBeenLastCalledWith(
+ expect.stringMatching(/^Theme: .* → .*single-newer/),
+ 'success',
+ 6000,
+ );
+ expect(window.ui.showMessage.mock.calls.flat().join(' '))
+ .not.toContain('bulk-older');
+
+ document.getElementById('toggle-raw-config').click();
+ expect(JSON.parse(document.getElementById('raw_config_editor').value))
+ .toEqual(expect.objectContaining({
+ app: expect.objectContaining({
+ theme: 'single-newer',
+ extra: 'bulk-only',
+ }),
+ }));
+});
+
+it('keeps a newer success state when an older same-key request rejects', async () => {
+ const olderSave = deferred();
+ const newerSave = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderSave.promise)
+ .mockImplementationOnce(() => newerSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'older-rejected' },
+ });
+ submitSettingsForm();
+ document.getElementById('raw_config_editor').value = JSON.stringify({
+ app: { theme: 'newer-saved' },
+ });
+ submitSettingsForm();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ olderSave.reject(new Error('older request failed'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)['app.theme'])
+ .toBe('newer-saved');
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+
+ newerSave.resolve(jsonResponse({
+ status: 'success',
+ settings: { 'app.theme': { value: 'newer-saved' } },
+ }));
+ await flushPromises();
+
+ const form = document.getElementById('settings-form');
+ expect(window.ui.showMessage).toHaveBeenLastCalledWith(
+ '4 settings saved',
+ 'success',
+ 6000,
+ );
+
+ expect(form.classList).not.toContain('ldr-saving');
+ expect(form.classList).toContain('ldr-save-success');
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+ expect(JSON.parse(document.getElementById('raw_config_editor').value))
+ .toEqual(expect.objectContaining({
+ app: expect.objectContaining({ theme: 'newer-saved' }),
+ }));
+});
diff --git a/tests/js/components/settings-sync-runtime.test.js b/tests/js/components/settings-sync-runtime.test.js
new file mode 100644
index 0000000000..691ffd5881
--- /dev/null
+++ b/tests/js/components/settings-sync-runtime.test.js
@@ -0,0 +1,355 @@
+/**
+ * Runtime contracts for the menu-to-settings bridge loaded by base.html.
+ *
+ * This module writes directly to the FastAPI single-setting route rather
+ * than going through services/api.js, so exercising the real change handler
+ * is the only way to bind its method, CSRF header, body, and response flow.
+ */
+
+const flushPromises = async (turns = 16) => {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+};
+
+async function loadSettingsSync() {
+ const addEventListener = vi.spyOn(document, 'addEventListener');
+ await import('@js/components/settings_sync.js');
+ const registration = addEventListener.mock.calls.find(
+ ([eventName]) => eventName === 'DOMContentLoaded',
+ );
+ addEventListener.mockRestore();
+ const handler = registration[1];
+ document.removeEventListener('DOMContentLoaded', handler);
+ handler();
+}
+
+function successfulResponse(data = { status: 'success' }) {
+ return new Response(JSON.stringify(data), { status: 200 });
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ document.body.innerHTML = `
+ <input id="model_hidden" value="qwen3">
+ <select id="model_provider">
+ <option value="ollama" selected>Ollama</option>
+ </select>
+ <input id="search_engine_hidden" value="searxng">
+ <input id="iterations" value="3">
+ <input id="questions_per_iteration" value="4">
+ <select id="strategy">
+ <option value="source-based" selected>Source based</option>
+ </select>
+ <input id="ollama_url" value="http://ollama:11434">
+ <input id="custom_endpoint" value="https://llm.example/v1">
+ <select id="theme-select">
+ <option value="dark" selected>Dark</option>
+ </select>
+ `;
+
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-current') };
+ window.displayWarnings = vi.fn();
+ window.refetchSettingsAndUpdateWarnings = vi.fn();
+ window.ui = { showMessage: vi.fn() };
+ vi.stubGlobal('requestIdleCallback', vi.fn(callback => callback()));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.displayWarnings;
+ delete window.refetchSettingsAndUpdateWarnings;
+ delete window.ui;
+ delete window.themeService;
+ document.body.replaceChildren();
+});
+
+it('persists a provider change through the FastAPI setting route and refreshes warnings', async () => {
+ const warnings = [{ type: 'provider', message: 'Local provider selected' }];
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ status: 'success',
+ warnings,
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+
+ document.getElementById('model_provider').dispatchEvent(new Event('change'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/llm.provider', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-current',
+ },
+ body: JSON.stringify({ value: 'ollama' }),
+ });
+ expect(window.displayWarnings).toHaveBeenCalledWith(warnings);
+ expect(window.refetchSettingsAndUpdateWarnings).toHaveBeenCalledOnce();
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'provider updated successfully',
+ 'success',
+ );
+});
+
+it('surfaces a rejected FastAPI setting write without reporting success', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(
+ '{"detail":"unsupported search engine"}',
+ { status: 422, statusText: 'Unprocessable Entity' },
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+
+ document.getElementById('search_engine_hidden').dispatchEvent(
+ new Event('change'),
+ );
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/search.tool',
+ expect.objectContaining({ method: 'PUT' }),
+ );
+ expect(window.displayWarnings).not.toHaveBeenCalled();
+ expect(window.refetchSettingsAndUpdateWarnings).not.toHaveBeenCalled();
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating search.tool: unsupported search engine',
+ 'error',
+ );
+});
+
+it('maps every menu control to its individual FastAPI setting route', async () => {
+ const fetchMock = vi.fn().mockImplementation(() =>
+ Promise.resolve(successfulResponse()));
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+
+ const controls = [
+ ['model_hidden', 'llm.model', 'qwen3'],
+ ['iterations', 'search.iterations', '3'],
+ ['questions_per_iteration', 'search.questions_per_iteration', '4'],
+ ['strategy', 'search.search_strategy', 'source-based'],
+ ['ollama_url', 'llm.ollama.url', 'http://ollama:11434'],
+ ['custom_endpoint', 'llm.openai_endpoint.url', 'https://llm.example/v1'],
+ ];
+ for (const [id] of controls) {
+ document.getElementById(id).dispatchEvent(new Event('change'));
+ }
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(controls.length);
+ controls.forEach(([id, key, value], index) => {
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ index + 1,
+ `/settings/api/${key}`,
+ expect.objectContaining({
+ method: 'PUT',
+ body: JSON.stringify({ value }),
+ }),
+ );
+ expect(document.getElementById(id).value).toBe(value);
+ });
+ expect(window.refetchSettingsAndUpdateWarnings).toHaveBeenCalledTimes(3);
+});
+
+it('delegates theme changes to the theme service without a duplicate write', async () => {
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ window.themeService = { setTheme: vi.fn() };
+ await loadSettingsSync();
+
+ document.getElementById('theme-select').dispatchEvent(new Event('change'));
+
+ expect(window.themeService.setTheme).toHaveBeenCalledWith('dark', true);
+ expect(fetchMock).not.toHaveBeenCalled();
+});
+
+it('falls back to the setting route when the theme service is unavailable', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(successfulResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+
+ document.getElementById('theme-select').dispatchEvent(new Event('change'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/app.theme', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-current',
+ },
+ body: JSON.stringify({ value: 'dark' }),
+ });
+});
+
+it('saves changed URL inputs once on blur and remembers the saved value', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(successfulResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+ const ollamaUrl = document.getElementById('ollama_url');
+
+ ollamaUrl.dispatchEvent(new Event('blur'));
+ ollamaUrl.dispatchEvent(new Event('blur'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/llm.ollama.url',
+ expect.objectContaining({
+ body: JSON.stringify({ value: 'http://ollama:11434' }),
+ }),
+ );
+ expect(ollamaUrl.getAttribute('data-last-saved'))
+ .toBe('http://ollama:11434');
+
+ ollamaUrl.value = '';
+ ollamaUrl.dispatchEvent(new Event('blur'));
+ expect(fetchMock).toHaveBeenCalledOnce();
+});
+
+it.each([
+ [
+ 'Ollama URL',
+ 'ollama_url',
+ 'llm.ollama.url',
+ 'http://ollama-new.example:11434',
+ ],
+ [
+ 'custom endpoint URL',
+ 'custom_endpoint',
+ 'llm.openai_endpoint.url',
+ 'https://gateway-new.example/v1',
+ ],
+])('saves an edited %s once across change followed by blur', async (
+ _label,
+ inputId,
+ settingKey,
+ value,
+) => {
+ const fetchMock = vi.fn().mockResolvedValue(successfulResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+ const input = document.getElementById(inputId);
+ input.value = value;
+
+ // This is the event order emitted when an edited text input loses focus.
+ input.dispatchEvent(new Event('change'));
+ input.dispatchEvent(new Event('blur'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(`/settings/api/${settingKey}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-current',
+ },
+ body: JSON.stringify({ value }),
+ });
+ expect(input.getAttribute('data-last-saved')).toBe(value);
+});
+
+it('releases URL deduplication after a rejected save so blur can retry', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ detail: 'endpoint is temporarily unavailable',
+ }), { status: 503 }))
+ .mockResolvedValueOnce(successfulResponse());
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+ const input = document.getElementById('custom_endpoint');
+ input.value = 'https://retry.example/v1';
+
+ input.dispatchEvent(new Event('change'));
+ input.dispatchEvent(new Event('blur'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(input.hasAttribute('data-last-saved')).toBe(false);
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Error updating llm.openai_endpoint.url: ' +
+ 'endpoint is temporarily unavailable',
+ 'error',
+ );
+
+ input.dispatchEvent(new Event('blur'));
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(input.getAttribute('data-last-saved'))
+ .toBe('https://retry.example/v1');
+});
+
+it('serializes same-key writes while unrelated settings save concurrently', async () => {
+ let resolveFirstModelSave;
+ const firstModelSave = new Promise(resolve => {
+ resolveFirstModelSave = resolve;
+ });
+ const fetchMock = vi.fn((url, options) => {
+ const { value } = JSON.parse(options.body);
+ if (url === '/settings/api/llm.model' && value === 'qwen3') {
+ return firstModelSave;
+ }
+ return Promise.resolve(successfulResponse());
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ await loadSettingsSync();
+
+ const model = document.getElementById('model_hidden');
+ model.dispatchEvent(new Event('change'));
+ model.value = 'llama3.3';
+ model.dispatchEvent(new Event('change'));
+ document.getElementById('model_provider').dispatchEvent(
+ new Event('change'),
+ );
+ await flushPromises();
+
+ // The newer model value waits for the older model PUT to settle, but the
+ // independent provider key is not held behind that queue.
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 1,
+ '/settings/api/llm.model',
+ expect.objectContaining({
+ body: JSON.stringify({ value: 'qwen3' }),
+ }),
+ );
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 2,
+ '/settings/api/llm.provider',
+ expect.objectContaining({
+ body: JSON.stringify({ value: 'ollama' }),
+ }),
+ );
+
+ resolveFirstModelSave(successfulResponse());
+ await flushPromises(16);
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 3,
+ '/settings/api/llm.model',
+ expect.objectContaining({
+ body: JSON.stringify({ value: 'llama3.3' }),
+ }),
+ );
+});
+
+it('uses the animation-frame bootstrap when idle callbacks are unavailable', async () => {
+ vi.stubGlobal('requestIdleCallback', undefined);
+ const animationFrame = vi.fn(callback => callback());
+ vi.stubGlobal('requestAnimationFrame', animationFrame);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(successfulResponse()));
+
+ await loadSettingsSync();
+ expect(animationFrame).toHaveBeenCalledOnce();
+
+ document.getElementById('model_hidden').dispatchEvent(new Event('change'));
+ await flushPromises();
+ expect(fetch).toHaveBeenCalledWith(
+ '/settings/api/llm.model',
+ expect.objectContaining({ method: 'PUT' }),
+ );
+});
diff --git a/tests/js/components/storage-mode-modal-runtime.test.js b/tests/js/components/storage-mode-modal-runtime.test.js
new file mode 100644
index 0000000000..b5d3c00728
--- /dev/null
+++ b/tests/js/components/storage-mode-modal-runtime.test.js
@@ -0,0 +1,129 @@
+/** Runtime FastAPI contract for the shared storage-mode modal. */
+
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/components/storage_mode_modal.html',
+);
+
+function renderModal({ selected = true } = {}) {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-storage">';
+ document.body.innerHTML = `
+ <div id="storage-mode-modal" style="display: flex">
+ <input name="storage_mode" type="radio" value="database">
+ <button id="storage-mode-confirm-btn"><i class="fas fa-save"></i> Save</button>
+ </div>
+ `;
+ document.querySelector('input[name="storage_mode"]').checked = selected;
+}
+
+function compileModal(locationStub = { reload: vi.fn() }) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'showStorageModeModal',
+ 'closeStorageModeModal',
+ 'confirmStorageModeChange',
+ ],
+ dependencies: { location: locationStub },
+ returnExpression: `({
+ showStorageModeModal,
+ closeStorageModeModal,
+ confirmStorageModeChange,
+ })`,
+ });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('requires a storage mode before sending a settings mutation', async () => {
+ renderModal({ selected: false });
+ const alertMock = vi.fn();
+ const fetchMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compileModal().confirmStorageModeChange();
+
+ expect(alertMock).toHaveBeenCalledWith('Please select a storage mode');
+ expect(fetchMock).not.toHaveBeenCalled();
+});
+
+it('POSTs the selected storage setting with CSRF and reloads on success', async () => {
+ renderModal();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'success' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const locationStub = { reload: vi.fn() };
+
+ await compileModal(locationStub).confirmStorageModeChange();
+
+ expect(fetchMock).toHaveBeenCalledWith('/settings/save_all_settings', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-storage',
+ },
+ body: JSON.stringify({
+ 'research_library.pdf_storage_mode': 'database',
+ }),
+ });
+ expect(document.getElementById('storage-mode-modal').style.display)
+ .toBe('none');
+ expect(locationStub.reload).toHaveBeenCalledOnce();
+});
+
+it('restores the storage action after an HTTP failure', async () => {
+ renderModal();
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 403,
+ }));
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const button = document.getElementById('storage-mode-confirm-btn');
+ const originalContent = button.innerHTML;
+
+ await compileModal().confirmStorageModeChange();
+
+ expect(error).toHaveBeenCalled();
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to update PDF storage mode. Please try again or use the Settings page.',
+ );
+ expect(button.disabled).toBe(false);
+ expect(button.innerHTML).toBe(originalContent);
+});
+
+it('treats an HTTP-200 rejected settings envelope as a failed mutation', async () => {
+ renderModal();
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'error',
+ message: 'storage backend unavailable',
+ }),
+ }));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await compileModal().confirmStorageModeChange();
+
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to update PDF storage mode. Please try again or use the Settings page.',
+ );
+ expect(document.getElementById('storage-mode-modal').style.display)
+ .toBe('flex');
+ expect(document.getElementById('storage-mode-confirm-btn').disabled)
+ .toBe(false);
+});
diff --git a/tests/js/components/subscription-manager-actions-runtime.test.js b/tests/js/components/subscription-manager-actions-runtime.test.js
new file mode 100644
index 0000000000..032fb77b7e
--- /dev/null
+++ b/tests/js/components/subscription-manager-actions-runtime.test.js
@@ -0,0 +1,200 @@
+/** Live delegated-action and edit-save contracts for SubscriptionManager. */
+
+import '@js/security/xss-protection.js';
+import '@js/components/subscription-manager.js';
+
+let manager;
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
+function subscription(id, overrides = {}) {
+ return {
+ id,
+ query_or_topic: `Topic ${id}`,
+ refresh_interval_minutes: 60,
+ next_refresh: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
+ folder: 'Inbox',
+ status: 'active',
+ notes: 'Original notes',
+ ...overrides,
+ };
+}
+
+function setSubscriptions(...items) {
+ manager.subscriptions = { Inbox: items };
+ manager.folders = [
+ { id: 'inbox', name: 'Inbox' },
+ { id: 'archive', name: 'Archive' },
+ ];
+}
+
+function installBootstrapModal() {
+ const instances = [];
+ class Modal {
+ constructor(element) {
+ this.element = element;
+ this.show = vi.fn();
+ this.hide = vi.fn();
+ instances.push(this);
+ }
+ }
+ vi.stubGlobal('bootstrap', { Modal });
+ return instances;
+}
+
+beforeAll(() => {
+ if (!window.subscriptionManager) {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+ manager = window.subscriptionManager;
+});
+
+beforeEach(() => {
+ document.body.innerHTML = '<div id="subscriptions-list"></div>';
+ manager.subscriptions = {};
+ manager.folders = [];
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('routes nested action-icon clicks to the owning subscription buttons', () => {
+ const item = subscription('nested-3299');
+ setSubscriptions(item);
+ // eslint-disable-next-line no-unsanitized/property -- checked-in renderer escapes the fixed fixture
+ document.getElementById('subscriptions-list').innerHTML =
+ manager.renderSubscriptionCard(item);
+ const editSpy = vi.spyOn(manager, 'editSubscription').mockResolvedValue();
+ const pauseSpy = vi.spyOn(manager, 'toggleSubscriptionStatus').mockResolvedValue();
+ const deleteSpy = vi.spyOn(manager, 'deleteSubscription').mockResolvedValue();
+
+ document.querySelector('.edit-subscription-btn i').click();
+ document.querySelector('.pause-subscription-btn i').click();
+ document.querySelector('.delete-subscription-btn i').click();
+
+ expect(editSpy).toHaveBeenCalledOnce();
+ expect(editSpy).toHaveBeenCalledWith('nested-3299');
+ expect(pauseSpy).toHaveBeenCalledOnce();
+ expect(pauseSpy).toHaveBeenCalledWith('nested-3299');
+ expect(deleteSpy).toHaveBeenCalledOnce();
+ expect(deleteSpy).toHaveBeenCalledWith('nested-3299');
+});
+
+it('keeps failed edits open and unchanged while guarding repeated saves', async () => {
+ setSubscriptions(subscription('failed-save'));
+ const modalInstances = installBootstrapModal();
+ const pendingUpdate = deferred();
+ const fetchMock = vi.fn(() => pendingUpdate.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(manager, 'getCSRFToken').mockReturnValue('csrf-edit');
+ vi.spyOn(manager, 'loadSubscriptionData').mockResolvedValue();
+ const showSuccessSpy = vi.spyOn(manager, 'showSuccess').mockImplementation(() => {});
+ const showErrorSpy = vi.spyOn(manager, 'showError').mockImplementation(() => {});
+
+ await manager.editSubscription('failed-save');
+ const modalElement = document.getElementById('editSubscriptionModal');
+ const saveButton = document.getElementById('save-subscription-edit');
+ document.getElementById('edit-frequency').value = '180';
+ document.getElementById('edit-folder').value = 'Archive';
+ document.getElementById('edit-notes').value = 'Keep these edits';
+
+ saveButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ saveButton.dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(saveButton.disabled).toBe(true);
+ expect(modalInstances[0].hide).not.toHaveBeenCalled();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/news/api/subscription/subscriptions/failed-save');
+ expect(options.method).toBe('PUT');
+ expect(JSON.parse(options.body)).toEqual({
+ refresh_interval_minutes: 180,
+ folder: 'Archive',
+ notes: 'Keep these edits',
+ });
+
+ pendingUpdate.resolve({ ok: false, status: 422 });
+ await vi.waitFor(() => {
+ expect(saveButton.disabled).toBe(false);
+ });
+
+ expect(document.getElementById('editSubscriptionModal')).toBe(modalElement);
+ expect(document.getElementById('edit-frequency').value).toBe('180');
+ expect(document.getElementById('edit-folder').value).toBe('Archive');
+ expect(document.getElementById('edit-notes').value).toBe('Keep these edits');
+ expect(modalInstances[0].hide).not.toHaveBeenCalled();
+ expect(showErrorSpy).toHaveBeenCalledWith('Failed to update subscription');
+ expect(showSuccessSpy).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+});
+
+it('closes the owned edit modal only after a successful PUT', async () => {
+ setSubscriptions(subscription('successful-save'));
+ const modalInstances = installBootstrapModal();
+ const pendingUpdate = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => pendingUpdate.promise));
+ vi.spyOn(manager, 'getCSRFToken').mockReturnValue('csrf-edit');
+ vi.spyOn(manager, 'loadSubscriptionData').mockResolvedValue();
+ vi.spyOn(manager, 'showSuccess').mockImplementation(() => {});
+ vi.spyOn(manager, 'showError').mockImplementation(() => {});
+
+ await manager.editSubscription('successful-save');
+ const saveButton = document.getElementById('save-subscription-edit');
+ saveButton.click();
+
+ expect(saveButton.disabled).toBe(true);
+ expect(modalInstances[0].hide).not.toHaveBeenCalled();
+
+ pendingUpdate.resolve({ ok: true, status: 200 });
+ await vi.waitFor(() => {
+ expect(modalInstances[0].hide).toHaveBeenCalledOnce();
+ });
+
+ expect(manager.showSuccess).toHaveBeenCalledWith('Subscription updated');
+ expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
+ expect(manager.showError).not.toHaveBeenCalled();
+});
+
+it('does not let an older save completion hide a newly opened edit modal', async () => {
+ setSubscriptions(
+ subscription('older-edit'),
+ subscription('newer-edit', { notes: 'New modal notes' }),
+ );
+ const modalInstances = installBootstrapModal();
+ const olderUpdate = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => olderUpdate.promise));
+ vi.spyOn(manager, 'getCSRFToken').mockReturnValue('csrf-edit');
+ vi.spyOn(manager, 'loadSubscriptionData').mockResolvedValue();
+ vi.spyOn(manager, 'showSuccess').mockImplementation(() => {});
+
+ await manager.editSubscription('older-edit');
+ document.getElementById('save-subscription-edit').click();
+ await manager.editSubscription('newer-edit');
+ const newerModal = document.getElementById('editSubscriptionModal');
+
+ olderUpdate.resolve({ ok: true, status: 200 });
+ await vi.waitFor(() => {
+ expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
+ });
+
+ expect(modalInstances).toHaveLength(2);
+ expect(modalInstances[0].hide).not.toHaveBeenCalled();
+ expect(modalInstances[1].hide).not.toHaveBeenCalled();
+ expect(document.getElementById('editSubscriptionModal')).toBe(newerModal);
+ expect(document.getElementById('edit-notes').value).toBe('New modal notes');
+});
diff --git a/tests/js/components/subscription-manager-delete-url.test.js b/tests/js/components/subscription-manager-delete-url.test.js
index 077321604b..7e174a3d14 100644
--- a/tests/js/components/subscription-manager-delete-url.test.js
+++ b/tests/js/components/subscription-manager-delete-url.test.js
@@ -52,6 +52,7 @@ describe('subscriptionManager.deleteSubscription', () => {
expect(options.method).toBe('DELETE');
expect(options.headers['X-CSRFToken']).toBe('tok');
expect(manager.showSuccess).toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
});
it('does not fetch when the confirm dialog is declined', async () => {
@@ -65,5 +66,194 @@ describe('subscriptionManager.deleteSubscription', () => {
await manager.deleteSubscription('sub-123');
expect(manager.showError).toHaveBeenCalled();
expect(manager.showSuccess).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+ });
+
+ it('does not report success or refresh after a transport failure', async () => {
+ fetchMock.mockRejectedValue(new Error('network unavailable'));
+
+ await manager.deleteSubscription('sub-123');
+
+ expect(manager.showError).toHaveBeenCalledWith(
+ 'Error deleting subscription'
+ );
+ expect(manager.showSuccess).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+ });
+});
+
+describe('subscriptionManager.updateSubscription', () => {
+ let fetchMock;
+
+ beforeEach(() => {
+ fetchMock = vi.fn().mockResolvedValue({ ok: true });
+ globalThis.fetch = fetchMock;
+ vi.spyOn(manager, 'loadSubscriptionData').mockResolvedValue(undefined);
+ vi.spyOn(manager, 'showSuccess').mockImplementation(() => {});
+ vi.spyOn(manager, 'showError').mockImplementation(() => {});
+ vi.spyOn(manager, 'getCSRFToken').mockReturnValue('update-token');
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ });
+
+ it('keeps PUT on the nested subscription route and refreshes after success', async () => {
+ const updates = {
+ refresh_interval_minutes: 120,
+ folder: 'papers',
+ notes: 'Track releases',
+ };
+
+ await manager.updateSubscription('sub-3299', updates);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscription/subscriptions/sub-3299',
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'update-token',
+ },
+ body: JSON.stringify(updates),
+ },
+ );
+ expect(manager.showSuccess).toHaveBeenCalledWith(
+ 'Subscription updated',
+ );
+ expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
+ expect(manager.showError).not.toHaveBeenCalled();
+ });
+
+ it('does not report success or refresh after a rejected update', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 422 });
+
+ await manager.updateSubscription('sub-3299', { status: 'paused' });
+
+ expect(manager.showError).toHaveBeenCalledWith(
+ 'Failed to update subscription',
+ );
+ expect(manager.showSuccess).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+ });
+
+ it('does not report success or refresh after an update transport failure', async () => {
+ fetchMock.mockRejectedValue(new Error('connection reset'));
+
+ await manager.updateSubscription('sub-3299', { status: 'active' });
+
+ expect(manager.showError).toHaveBeenCalledWith(
+ 'Error updating subscription',
+ );
+ expect(manager.showSuccess).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+ });
+});
+
+describe('subscriptionManager folder and status actions', () => {
+ let fetchMock;
+
+ beforeEach(() => {
+ fetchMock = vi.fn();
+ globalThis.fetch = fetchMock;
+ vi.spyOn(manager, 'loadSubscriptionData').mockResolvedValue(undefined);
+ vi.spyOn(manager, 'showSuccess').mockImplementation(() => {});
+ vi.spyOn(manager, 'showError').mockImplementation(() => {});
+ vi.spyOn(manager, 'getCSRFToken').mockReturnValue('folder-token');
+ manager.subscriptions = {
+ Research: [{ id: 'active-sub', status: 'active' }],
+ Paused: [{ id: 'paused-sub', status: 'paused' }],
+ };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.prompt;
+ document.body.replaceChildren();
+ });
+
+ it('derives pause and resume mutations from the owned subscription', async () => {
+ const update = vi.spyOn(manager, 'updateSubscription')
+ .mockResolvedValue(true);
+
+ await manager.toggleSubscriptionStatus('active-sub');
+ await manager.toggleSubscriptionStatus('paused-sub');
+ await manager.toggleSubscriptionStatus('missing-sub');
+
+ expect(update.mock.calls).toEqual([
+ ['active-sub', { status: 'paused' }],
+ ['paused-sub', { status: 'active' }],
+ ]);
+ });
+
+ it('switches only the selected folder tab before rendering its cards', () => {
+ document.body.innerHTML = `
+ <div id="folderTabs">
+ <button class="nav-link active" data-folder="all"></button>
+ <button class="nav-link" data-folder="Research"></button>
+ </div>
+ `;
+ const render = vi.spyOn(manager, 'renderSubscriptions')
+ .mockImplementation(() => {});
+
+ manager.switchFolder('Research');
+
+ expect(manager.currentFolder).toBe('Research');
+ expect(document.querySelector('[data-folder="all"]').classList)
+ .not.toContain('active');
+ expect(document.querySelector('[data-folder="Research"]').classList)
+ .toContain('active');
+ expect(render).toHaveBeenCalledOnce();
+ });
+
+ it('creates a folder with CSRF and reloads only after success', async () => {
+ fetchMock.mockResolvedValue({ ok: true });
+
+ await manager.createFolder('Migration', '#123456', '🚀');
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscription/folders', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'folder-token',
+ },
+ body: JSON.stringify({
+ name: 'Migration',
+ color: '#123456',
+ icon: '🚀',
+ }),
+ });
+ expect(manager.showSuccess).toHaveBeenCalledWith('Folder created');
+ expect(manager.loadSubscriptionData).toHaveBeenCalledOnce();
+ });
+
+ it('surfaces FastAPI detail from a rejected folder create', async () => {
+ fetchMock.mockResolvedValue({
+ ok: false,
+ json: vi.fn().mockResolvedValue({
+ detail: 'A folder with this name already exists',
+ }),
+ });
+
+ await manager.createFolder('Migration');
+
+ expect(manager.showError).toHaveBeenCalledWith(
+ 'A folder with this name already exists',
+ );
+ expect(manager.showSuccess).not.toHaveBeenCalled();
+ expect(manager.loadSubscriptionData).not.toHaveBeenCalled();
+ });
+
+ it('uses the prompted folder name and ignores a cancelled prompt', () => {
+ const create = vi.spyOn(manager, 'createFolder').mockResolvedValue();
+ window.prompt = vi.fn()
+ .mockReturnValueOnce('Prompted folder')
+ .mockReturnValueOnce('');
+
+ manager.showCreateFolderDialog();
+ manager.showCreateFolderDialog();
+
+ expect(create).toHaveBeenCalledOnce();
+ expect(create).toHaveBeenCalledWith('Prompted folder');
});
});
diff --git a/tests/js/components/subscription-manager-load-data.test.js b/tests/js/components/subscription-manager-load-data.test.js
new file mode 100644
index 0000000000..2da77f84a7
--- /dev/null
+++ b/tests/js/components/subscription-manager-load-data.test.js
@@ -0,0 +1,325 @@
+/** Endpoint and stale-response contracts for SubscriptionManager loading. */
+
+import '@js/security/xss-protection.js';
+import '@js/components/subscription-manager.js';
+
+let manager;
+
+function response(payload, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
+function mountSubscriptionUi() {
+ document.body.innerHTML = `
+ <span id="total-subscriptions"></span>
+ <span id="active-subscriptions"></span>
+ <span id="total-folders"></span>
+ <span id="next-refresh-time"></span>
+ <ul id="folderTabs">
+ <li><button class="nav-link" data-folder="all">All</button></li>
+ <li><button class="nav-link" data-folder="Unfiled">Unfiled</button></li>
+ <li><button id="create-folder-btn">Create</button></li>
+ </ul>
+ <div id="subscriptions-list"></div>
+ `;
+ manager.subscriptions = {};
+ manager.folders = [];
+ manager.currentFolder = 'all';
+}
+
+function organizedSubscription(id, query, folder) {
+ return {
+ [folder]: [{
+ id,
+ query_or_topic: query,
+ refresh_interval_minutes: 60,
+ next_refresh: new Date(Date.now() + 60 * 60 * 1000).toISOString(),
+ folder,
+ status: 'active',
+ notes: '',
+ }],
+ };
+}
+
+beforeAll(() => {
+ if (!window.subscriptionManager) {
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ }
+ manager = window.subscriptionManager;
+});
+
+beforeEach(() => {
+ mountSubscriptionUi();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('loads stats, folders, and organized subscriptions in endpoint order', async () => {
+ const stats = {
+ total_subscriptions: 2,
+ active_subscriptions: 1,
+ total_folders: 1,
+ };
+ const folders = [{
+ id: 'folder-1',
+ name: 'Research',
+ icon: '📚',
+ item_count: 1,
+ }];
+ const subscriptions = organizedSubscription(
+ 'subscription-1',
+ 'FastAPI migration',
+ 'Research',
+ );
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response(stats))
+ .mockResolvedValueOnce(response(folders))
+ .mockResolvedValueOnce(response(subscriptions));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await manager.loadSubscriptionData();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/subscription/stats',
+ '/news/api/subscription/folders',
+ '/news/api/subscription/subscriptions/organized',
+ ]);
+ expect(manager.folders).toEqual(folders);
+ expect(manager.subscriptions).toEqual(subscriptions);
+ expect(document.getElementById('total-subscriptions').textContent).toBe('2');
+ expect(document.getElementById('active-subscriptions').textContent).toBe('1');
+ expect(document.getElementById('total-folders').textContent).toBe('1');
+ expect(document.querySelector('[data-folder="Research"]').textContent)
+ .toContain('Research');
+ expect(document.querySelector('[data-subscription-id="subscription-1"]')
+ .textContent).toContain('FastAPI migration');
+});
+
+it('does not let an older modal load overwrite a newer response', async () => {
+ const firstStats = deferred();
+ let statsCalls = 0;
+ let folderCalls = 0;
+ let organizedCalls = 0;
+ const newestFolders = [{
+ id: 'folder-new',
+ name: 'Newest',
+ icon: 'N',
+ item_count: 1,
+ }];
+ const newestSubscriptions = organizedSubscription(
+ 'subscription-new',
+ 'Newest subscription',
+ 'Newest',
+ );
+ const fetchMock = vi.fn(url => {
+ if (url === '/news/api/subscription/stats') {
+ statsCalls += 1;
+ if (statsCalls === 1) return firstStats.promise;
+ return Promise.resolve(response({
+ total_subscriptions: 9,
+ active_subscriptions: 8,
+ total_folders: 1,
+ }));
+ }
+ if (url === '/news/api/subscription/folders') {
+ folderCalls += 1;
+ return Promise.resolve(response(folderCalls === 1
+ ? newestFolders
+ : [{ id: 'folder-old', name: 'Old', item_count: 1 }]));
+ }
+ if (url === '/news/api/subscription/subscriptions/organized') {
+ organizedCalls += 1;
+ return Promise.resolve(response(organizedCalls === 1
+ ? newestSubscriptions
+ : organizedSubscription(
+ 'subscription-old',
+ 'Old subscription',
+ 'Old',
+ )));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = manager.loadSubscriptionData();
+ const newerLoad = manager.loadSubscriptionData();
+ await newerLoad;
+
+ firstStats.resolve(response({
+ total_subscriptions: 1,
+ active_subscriptions: 1,
+ total_folders: 1,
+ }));
+ await olderLoad;
+
+ expect(manager.folders).toEqual(newestFolders);
+ expect(manager.subscriptions).toEqual(newestSubscriptions);
+ expect(document.getElementById('total-subscriptions').textContent).toBe('9');
+ expect(document.querySelector('[data-subscription-id="subscription-new"]'))
+ .not.toBeNull();
+ expect(document.querySelector('[data-subscription-id="subscription-old"]'))
+ .toBeNull();
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+});
+
+it('rejects an older organized payload after its final JSON await', async () => {
+ const olderOrganizedJson = deferred();
+ const newestFolders = [{
+ id: 'folder-newest',
+ name: 'Newest',
+ icon: 'N',
+ item_count: 1,
+ }];
+ const newestSubscriptions = organizedSubscription(
+ 'subscription-newest',
+ 'Newest final payload',
+ 'Newest',
+ );
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ total_subscriptions: 1,
+ active_subscriptions: 1,
+ total_folders: 1,
+ }))
+ .mockResolvedValueOnce(response([{
+ id: 'folder-older',
+ name: 'Older',
+ item_count: 1,
+ }]))
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn(() => olderOrganizedJson.promise),
+ })
+ .mockResolvedValueOnce(response({
+ total_subscriptions: 9,
+ active_subscriptions: 8,
+ total_folders: 1,
+ }))
+ .mockResolvedValueOnce(response(newestFolders))
+ .mockResolvedValueOnce(response(newestSubscriptions));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = manager.loadSubscriptionData();
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+
+ const newerLoad = manager.loadSubscriptionData();
+ await newerLoad;
+ olderOrganizedJson.resolve(organizedSubscription(
+ 'subscription-older',
+ 'Stale final payload',
+ 'Older',
+ ));
+ await olderLoad;
+
+ expect(fetchMock).toHaveBeenCalledTimes(6);
+ expect(manager.folders).toEqual(newestFolders);
+ expect(manager.subscriptions).toEqual(newestSubscriptions);
+ expect(document.getElementById('total-subscriptions').textContent).toBe('9');
+ expect(document.querySelector('[data-subscription-id="subscription-newest"]'))
+ .not.toBeNull();
+ expect(document.querySelector('[data-subscription-id="subscription-older"]'))
+ .toBeNull();
+});
+
+it('suppresses an older load rejection after a newer load succeeds', async () => {
+ const olderStats = deferred();
+ const newestFolders = [{
+ id: 'folder-current',
+ name: 'Current',
+ icon: 'C',
+ item_count: 1,
+ }];
+ const newestSubscriptions = organizedSubscription(
+ 'subscription-current',
+ 'Current subscription',
+ 'Current',
+ );
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderStats.promise)
+ .mockResolvedValueOnce(response({
+ total_subscriptions: 4,
+ active_subscriptions: 3,
+ total_folders: 1,
+ }))
+ .mockResolvedValueOnce(response(newestFolders))
+ .mockResolvedValueOnce(response(newestSubscriptions));
+ vi.stubGlobal('fetch', fetchMock);
+ const showErrorSpy = vi.spyOn(manager, 'showError');
+
+ const olderLoad = manager.loadSubscriptionData();
+ const newerLoad = manager.loadSubscriptionData();
+ await newerLoad;
+
+ olderStats.reject(new Error('older stats request failed'));
+ await olderLoad;
+
+ expect(showErrorSpy).not.toHaveBeenCalled();
+ expect(manager.folders).toEqual(newestFolders);
+ expect(manager.subscriptions).toEqual(newestSubscriptions);
+ expect(document.getElementById('total-subscriptions').textContent).toBe('4');
+ expect(document.querySelector('[data-subscription-id="subscription-current"]'))
+ .not.toBeNull();
+ expect(document.getElementById('subscriptions-list').textContent)
+ .not.toContain('Failed to load subscriptions');
+});
+
+it('replaces the spinner when organized subscriptions returns non-ok', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ total_subscriptions: 2,
+ active_subscriptions: 1,
+ total_folders: 1,
+ }))
+ .mockResolvedValueOnce(response([{
+ id: 'folder-recoverable',
+ name: 'Recoverable',
+ item_count: 0,
+ }]))
+ .mockResolvedValueOnce(response({
+ detail: 'subscription backend unavailable',
+ }, false, 503));
+ vi.stubGlobal('fetch', fetchMock);
+ const showAlertMock = vi.fn();
+ vi.stubGlobal('showAlert', showAlertMock);
+
+ await manager.loadSubscriptionData();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/subscription/stats',
+ '/news/api/subscription/folders',
+ '/news/api/subscription/subscriptions/organized',
+ ]);
+ expect(showAlertMock).toHaveBeenCalledWith(
+ 'Failed to load subscriptions',
+ 'error',
+ );
+ const list = document.getElementById('subscriptions-list');
+ expect(list.querySelector('.spinner-border')).toBeNull();
+ expect(list.querySelector('[role="alert"]')?.textContent)
+ .toBe('Failed to load subscriptions. Please try again.');
+ expect(manager.subscriptions).toEqual({});
+});
diff --git a/tests/js/config/urls.test.js b/tests/js/config/urls.test.js
index 6ea7bdfa1f..8334c78375 100644
--- a/tests/js/config/urls.test.js
+++ b/tests/js/config/urls.test.js
@@ -108,18 +108,89 @@ describe('URLBuilder', () => {
`${URLS.PAGES.JOURNAL_QUALITY}?research_id=abc%20123`
);
});
+
+ it.each([
+ ['resultsPage', ['research-1'], '/results/research-1'],
+ ['detailsPage', ['research-1'], '/details/research-1'],
+ ['documentPage', ['doc-1'], '/library/document/doc-1'],
+ ['researchDetails', ['research-1'], '/api/research/research-1'],
+ ['researchLogsExport', ['research-1'], '/api/research/research-1/logs/export'],
+ ['researchReport', ['research-1'], '/api/report/research-1'],
+ ['historyDetails', ['research-1'], '/history/details/research-1'],
+ ['historyLogs', ['research-1'], '/history/logs/research-1'],
+ ['markdownExport', ['research-1'], '/history/markdown/research-1'],
+ ['historyReport', ['research-1'], '/history/report/research-1'],
+ ['historyMarkdown', ['research-1'], '/history/markdown/research-1'],
+ ['historyLogCount', ['research-1'], '/history/log_count/research-1'],
+ ['updateSetting', ['llm.model'], '/settings/api/llm.model'],
+ ['deleteSetting', ['llm.model'], '/settings/api/llm.model'],
+ ['researchTimelineMetrics', ['research-1'], '/metrics/api/metrics/research/research-1/timeline'],
+ ['researchSearchMetrics', ['research-1'], '/metrics/api/metrics/research/research-1/search'],
+ ['getRating', ['research-1'], '/metrics/api/ratings/research-1'],
+ ['saveRating', ['research-1'], '/metrics/api/ratings/research-1'],
+ ['researchCosts', ['research-1'], '/metrics/api/research-costs/research-1'],
+ ])('%s maps to its canonical migrated route', (method, args, expected) => {
+ expect(URLBuilder[method](...args)).toBe(expected);
+ });
});
describe('extractResearchIdFromPattern', () => {
- // We can't easily change window.location.pathname in happy-dom,
- // but we can verify the regex pattern construction works for the
- // current path (which is "/" by default → no match).
- it('returns null when pattern not in current path', () => {
+ const originalLocation = window.location;
+
+ function setPath(pathname) {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...originalLocation, pathname },
+ });
+ }
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: originalLocation,
+ });
+ });
+
+ it.each([
+ ['/results/8f98e166-bf06-4de4-ae65-fb8e790a16e4', 'results', '8f98e166-bf06-4de4-ae65-fb8e790a16e4'],
+ ['/details/research-abc-123', 'details', 'research-abc-123'],
+ ['/progress/42', 'progress', '42'],
+ ])('extracts migrated string IDs from %s', (pathname, pattern, expected) => {
+ setPath(pathname);
+
+ expect(URLBuilder.extractResearchIdFromPattern(pattern)).toBe(expected);
+ });
+
+ it('does not extract an ID for a different page route', () => {
+ setPath('/history/research-abc-123');
+
expect(URLBuilder.extractResearchIdFromPattern('results')).toBeNull();
});
});
describe('extractResearchId', () => {
+ const originalLocation = window.location;
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: originalLocation,
+ });
+ });
+
+ it.each([
+ ['/results/101', '101'],
+ ['/details/202', '202'],
+ ['/progress/303', '303'],
+ ])('extracts a numeric ID from %s', (pathname, expected) => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...originalLocation, pathname },
+ });
+
+ expect(URLBuilder.extractResearchId()).toBe(expected);
+ });
+
it('returns null when no ID pattern matches current path', () => {
// Default happy-dom path is "/"
expect(URLBuilder.extractResearchId()).toBeNull();
@@ -127,10 +198,33 @@ describe('URLBuilder', () => {
});
describe('getCurrentPageType', () => {
- it('returns a valid page type for the current path', () => {
- const validTypes = ['home', 'results', 'details', 'progress',
- 'history', 'settings', 'metrics', 'unknown'];
- expect(validTypes).toContain(URLBuilder.getCurrentPageType());
+ const originalLocation = window.location;
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: originalLocation,
+ });
+ });
+
+ it.each([
+ ['/', 'home'],
+ ['/index', 'home'],
+ ['/home', 'home'],
+ ['/results/research-1', 'results'],
+ ['/details/research-1', 'details'],
+ ['/progress/research-1', 'progress'],
+ ['/history/', 'history'],
+ ['/settings/', 'settings'],
+ ['/metrics/costs', 'metrics'],
+ ['/library/', 'unknown'],
+ ])('classifies %s as %s', (pathname, expected) => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { ...originalLocation, pathname },
+ });
+
+ expect(URLBuilder.getCurrentPageType()).toBe(expected);
});
});
});
diff --git a/tests/js/deletion/delete-modules.test.js b/tests/js/deletion/delete-modules.test.js
index 968cd07f25..597556459a 100644
--- a/tests/js/deletion/delete-modules.test.js
+++ b/tests/js/deletion/delete-modules.test.js
@@ -138,6 +138,64 @@ describe('DeleteConfirmation execution', () => {
}
});
+ it('runs directly exactly once when confirmations are explicitly disabled', async () => {
+ const { modalInstance, cleanup } = setupModalDom();
+ const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue({
+ ok: true,
+ json: async () => ({ value: false }),
+ });
+
+ try {
+ const action = vi.fn(async () => 'deleted');
+
+ await expect(realConfirmAndRun(
+ { action: 'deleteDocument', onConfirm: action },
+ action,
+ )).resolves.toBe('deleted');
+
+ expect(action).toHaveBeenCalledOnce();
+ expect(modalInstance.show).not.toHaveBeenCalled();
+ } finally {
+ fetchSpy.mockRestore();
+ cleanup();
+ }
+ });
+
+ it.each([
+ [
+ 'a rejected settings lookup',
+ () => Promise.reject(new Error('settings unavailable')),
+ ],
+ [
+ 'a non-ok settings response',
+ () => Promise.resolve({ ok: false }),
+ ],
+ ])('fails closed after %s', async (_case, settingsResult) => {
+ const { modal, modalInstance, cleanup } = setupModalDom({
+ autoEmitHidden: false,
+ });
+ const fetchSpy = vi.spyOn(globalThis, 'fetch')
+ .mockImplementation(settingsResult);
+
+ try {
+ const action = vi.fn();
+ const confirmation = realConfirmAndRun(
+ { action: 'deleteDocument' },
+ action,
+ );
+
+ await vi.waitFor(() => expect(modalInstance.show).toHaveBeenCalledOnce());
+ expect(action).not.toHaveBeenCalled();
+
+ modal.dispatchEvent(new Event('hidden.bs.modal'));
+ await expect(confirmation).resolves.toBeNull();
+ expect(action).not.toHaveBeenCalled();
+ } finally {
+ fetchSpy.mockRestore();
+ cleanup();
+ }
+ });
+
it('consumes confirm callback on rapid double-click and clears cancel callback before modal hides', async () => {
const { modal, confirmButton, cleanup } = setupModalDom({ autoEmitHidden: false });
@@ -221,10 +279,7 @@ beforeEach(() => {
window.DeleteConfirmation.confirmAndRun.mockClear();
});
-// Flush pending microtasks. delete_manager's skipConfirm path calls
-// confirmOptions.onConfirm() WITHOUT awaiting it, so test callers need
-// to wait for the inner async work to settle. This is a small wart in
-// the source — flushPromises() is the standard workaround.
+// Flush pending browser work used by notification callbacks.
const flushPromises = () => new Promise(resolve => setTimeout(resolve, 0));
describe('DeleteManager.formatBytes', () => {
@@ -285,6 +340,27 @@ describe('DeleteManager.deleteDocument', () => {
expect(window.api.fetchWithErrorHandling.mock.calls[0][1].method).toBe('DELETE');
});
+ it('owns the skipped-confirmation request until its callback completes', async () => {
+ let finishDelete;
+ window.api.fetchWithErrorHandling.mockImplementationOnce(() =>
+ new Promise(resolve => {
+ finishDelete = resolve;
+ }));
+ const onSuccess = vi.fn();
+
+ const deletion = DM.deleteDocument('doc-owned', {
+ skipConfirm: true,
+ onSuccess,
+ });
+ await Promise.resolve();
+ expect(onSuccess).not.toHaveBeenCalled();
+
+ finishDelete({ success: true });
+ await deletion;
+
+ expect(onSuccess).toHaveBeenCalledWith({ success: true });
+ });
+
it('calls onSuccess callback with API result on success', async () => {
const onSuccess = vi.fn();
const apiResult = { success: true, deleted_id: 'doc-789' };
@@ -507,6 +583,86 @@ describe('DeleteManager.bulkRemoveFromCollection', () => {
});
});
+describe('DeleteManager destructive-operation failures', () => {
+ it.each([
+ [
+ 'blob deletion',
+ options => DM.deleteDocumentBlob('doc-failure', options),
+ 'Failed to remove PDF: ',
+ ],
+ [
+ 'single collection removal',
+ options => DM.removeFromCollection('doc-failure', 'collection-failure', options),
+ 'Failed to remove: ',
+ ],
+ [
+ 'collection index deletion',
+ options => DM.deleteCollectionIndex('collection-failure', options),
+ 'Failed to delete index: ',
+ ],
+ [
+ 'bulk document deletion',
+ options => DM.bulkDeleteDocuments(['doc-failure'], options),
+ 'Bulk delete failed: ',
+ ],
+ [
+ 'bulk blob deletion',
+ options => DM.bulkDeleteBlobs(['doc-failure'], options),
+ 'Failed to remove PDFs: ',
+ ],
+ [
+ 'bulk collection removal',
+ options => DM.bulkRemoveFromCollection(
+ ['doc-failure'],
+ 'collection-failure',
+ options,
+ ),
+ 'Failed to remove documents: ',
+ ],
+ ])('reports %s failure without calling success', async (
+ _operation,
+ invoke,
+ notificationPrefix,
+ ) => {
+ const onSuccess = vi.fn();
+ const onError = vi.fn();
+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({
+ success: false,
+ error: 'Backend rejected the destructive operation',
+ });
+
+ await invoke({ skipConfirm: true, onSuccess, onError });
+
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(onError).toHaveBeenCalledOnce();
+ expect(onError.mock.calls[0][0].message)
+ .toBe('Backend rejected the destructive operation');
+ expect(window.showToast).toHaveBeenLastCalledWith(
+ `${notificationPrefix}Backend rejected the destructive operation`,
+ 'error',
+ );
+ });
+
+ it('distinguishes unlink-only bulk removal from permanent deletion', async () => {
+ window.api.fetchWithErrorHandling.mockResolvedValueOnce({
+ success: true,
+ unlinked: 2,
+ deleted: 0,
+ });
+
+ await DM.bulkRemoveFromCollection(
+ ['doc-one', 'doc-two'],
+ 'collection-one',
+ { skipConfirm: true },
+ );
+
+ expect(window.showToast).toHaveBeenLastCalledWith(
+ 'Removed 2 document(s) from collection',
+ 'success',
+ );
+ });
+});
+
describe('DeleteManager confirmation flow', () => {
it('skipConfirm: true bypasses DeleteConfirmation.confirmAndRun', async () => {
window.api.fetchWithErrorHandling.mockResolvedValueOnce({ success: true });
@@ -539,4 +695,185 @@ describe('DeleteManager confirmation flow', () => {
// confirmAndRun was still called → user still gets the dialog
expect(window.DeleteConfirmation.confirmAndRun).toHaveBeenCalled();
});
+
+ it('builds a complete document-impact preview before confirmation', async () => {
+ window.api.fetchWithErrorHandling
+ .mockResolvedValueOnce({
+ success: true,
+ title: 'Migration source',
+ has_blob: true,
+ blob_size: 2048,
+ has_text: true,
+ chunks_count: 12,
+ collections_count: 3,
+ })
+ .mockResolvedValueOnce({ success: true });
+
+ await DM.deleteDocument('doc-preview');
+
+ const [options] = window.DeleteConfirmation.confirmAndRun.mock.calls[0];
+ expect(options.title).toBe('Delete "Migration source"?');
+ expect(options.details).toEqual([
+ 'PDF file (2 KB)',
+ 'Extracted text content',
+ '12 RAG index chunks',
+ 'Links to 3 collection(s)',
+ ]);
+ });
+
+ it('builds a collection-impact preview from the migrated endpoint', async () => {
+ window.api.fetchWithErrorHandling
+ .mockResolvedValueOnce({
+ success: true,
+ name: 'Owned collection',
+ documents_count: 4,
+ chunks_count: 25,
+ folders_count: 2,
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ documents_unlinked: 4,
+ chunks_deleted: 25,
+ });
+
+ await DM.deleteCollection('collection-preview');
+
+ expect(window.api.fetchWithErrorHandling).toHaveBeenNthCalledWith(
+ 1,
+ '/library/api/collections/collection-preview/preview',
+ { method: 'GET' },
+ );
+ const [options] = window.DeleteConfirmation.confirmAndRun.mock.calls[0];
+ expect(options.title).toBe('Delete "Owned collection"?');
+ expect(options.details).toEqual([
+ '4 document(s) will be unlinked',
+ '25 RAG index chunks',
+ '2 linked folder(s)',
+ ]);
+ });
+
+ it('requests a bulk-delete impact preview before destructive confirmation', async () => {
+ window.api.fetchWithErrorHandling
+ .mockResolvedValueOnce({
+ success: true,
+ documents_with_blobs: 2,
+ total_blob_size: 4096,
+ total_chunks: 18,
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ deleted: 2,
+ total: 2,
+ total_bytes_freed: 4096,
+ });
+
+ await DM.bulkDeleteDocuments(['first', 'second']);
+
+ expect(window.api.fetchWithErrorHandling).toHaveBeenNthCalledWith(
+ 1,
+ '/library/api/documents/preview',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ document_ids: ['first', 'second'],
+ operation: 'delete',
+ }),
+ },
+ );
+ const [options] = window.DeleteConfirmation.confirmAndRun.mock.calls[0];
+ expect(options.details).toEqual([
+ '2 PDF file(s) (4 KB)',
+ '18 RAG index chunks',
+ ]);
+ });
+
+ it('requests blob-only impact without claiming extracted text is removed', async () => {
+ window.api.fetchWithErrorHandling
+ .mockResolvedValueOnce({
+ success: true,
+ documents_with_blobs: 3,
+ total_blob_size: 6144,
+ })
+ .mockResolvedValueOnce({
+ success: true,
+ deleted: 3,
+ total_bytes_freed: 6144,
+ });
+
+ await DM.bulkDeleteBlobs(['one', 'two', 'three']);
+
+ expect(window.api.fetchWithErrorHandling).toHaveBeenNthCalledWith(
+ 1,
+ '/library/api/documents/preview',
+ {
+ method: 'POST',
+ body: JSON.stringify({
+ document_ids: ['one', 'two', 'three'],
+ operation: 'delete_blobs',
+ }),
+ },
+ );
+ const [options] = window.DeleteConfirmation.confirmAndRun.mock.calls[0];
+ expect(options.details).toEqual([
+ '3 PDF file(s)',
+ '6 KB will be freed',
+ ]);
+ });
+});
+
+describe('DeleteManager notification fallback', () => {
+ let originalShowToast;
+
+ beforeEach(() => {
+ originalShowToast = window.showToast;
+ delete window.showToast;
+ window.LdrAlertHelpers = {
+ mapAlertType: vi.fn(type => (
+ type === 'error' ? 'danger' : type
+ )),
+ };
+ window.escapeHtml = value => String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;');
+ });
+
+ afterEach(() => {
+ window.showToast = originalShowToast;
+ delete window.bootstrap;
+ delete window.LdrAlertHelpers;
+ delete window.escapeHtml;
+ document.querySelector('.ldr-toast-container')?.remove();
+ });
+
+ it('escapes a backend message in the Bootstrap toast and removes it when hidden', () => {
+ const show = vi.fn();
+ window.bootstrap = {
+ Toast: vi.fn(function Toast() {
+ return { show };
+ }),
+ };
+ const payload = '<img src=x onerror="window.pwned=true">';
+
+ DM.showNotification('error', payload);
+
+ const toast = document.querySelector('.ldr-toast-container .toast');
+ expect(toast.classList.contains('bg-danger')).toBe(true);
+ expect(toast.querySelector('.toast-body').textContent).toBe(payload);
+ expect(toast.querySelector('img')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ expect(show).toHaveBeenCalledOnce();
+
+ toast.dispatchEvent(new Event('hidden.bs.toast'));
+ expect(toast.isConnected).toBe(false);
+ });
+
+ it('logs a bounded fallback when no toast implementation is loaded', () => {
+ const log = vi.spyOn(SafeLogger, 'log').mockImplementation(() => {});
+
+ DM.showNotification('warning', 'Migration warning');
+
+ expect(log).toHaveBeenCalledWith('[WARNING] Migration warning');
+ log.mockRestore();
+ });
});
diff --git a/tests/js/embedding-settings-runtime.test.js b/tests/js/embedding-settings-runtime.test.js
new file mode 100644
index 0000000000..65b994dd43
--- /dev/null
+++ b/tests/js/embedding-settings-runtime.test.js
@@ -0,0 +1,802 @@
+/**
+ * Runtime coverage for the embedding-settings page's FastAPI contracts.
+ *
+ * This page owns several direct requests and previously had no executable
+ * Vitest import. Use the checked-in template as the DOM fixture so the test
+ * exercises the same element graph and initialization order as the browser.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../src/local_deep_research/web/templates/pages/embedding_settings.html',
+);
+
+const MODELS = {
+ success: true,
+ provider_options: [{
+ value: 'sentence_transformers',
+ label: 'Sentence Transformers',
+ available: true,
+ }],
+ providers: {
+ sentence_transformers: [
+ {
+ value: 'model-old',
+ label: 'Old model - Existing default',
+ is_embedding: true,
+ },
+ {
+ value: 'model-new',
+ label: 'New model - Migration candidate',
+ is_embedding: true,
+ },
+ ],
+ },
+};
+
+const SETTINGS = {
+ success: true,
+ settings: {
+ embedding_provider: 'sentence_transformers',
+ embedding_model: 'model-old',
+ chunk_size: 640,
+ chunk_overlap: 80,
+ splitter_type: 'recursive',
+ distance_metric: 'cosine',
+ index_type: 'flat',
+ normalize_vectors: true,
+ text_separators: ['\\n\\n', ' '],
+ },
+};
+
+function catalogRacePayload(betaModel) {
+ return {
+ success: true,
+ provider_options: [
+ {
+ value: 'sentence_transformers',
+ label: 'Sentence Transformers',
+ available: true,
+ },
+ {
+ value: 'catalog-alpha',
+ label: 'Catalog Alpha',
+ available: true,
+ },
+ {
+ value: 'catalog-beta',
+ label: 'Catalog Beta',
+ available: true,
+ },
+ ],
+ providers: {
+ sentence_transformers: MODELS.providers.sentence_transformers,
+ 'catalog-alpha': [{
+ value: 'alpha-initial-model',
+ label: 'Alpha initial model',
+ is_embedding: true,
+ }],
+ 'catalog-beta': [{
+ value: betaModel,
+ label: betaModel,
+ is_embedding: true,
+ }],
+ },
+ };
+}
+
+const INITIAL_CATALOG = catalogRacePayload('beta-initial-model');
+const NEWEST_CATALOG = catalogRacePayload('beta-newest-model');
+const STALE_CATALOG = catalogRacePayload('beta-stale-fallback-model');
+
+const OPENAI_MODELS = {
+ success: true,
+ provider_options: [
+ {
+ value: 'openai',
+ label: 'OpenAI / Compatible',
+ available: true,
+ },
+ {
+ value: 'ollama',
+ label: 'Ollama',
+ available: true,
+ },
+ ],
+ providers: {
+ openai: [{
+ value: 'text-embedding-3-small',
+ label: 'text-embedding-3-small',
+ is_embedding: true,
+ }],
+ ollama: [{
+ value: 'nomic-embed-text',
+ label: 'nomic-embed-text',
+ is_embedding: true,
+ }],
+ },
+};
+
+const OPENAI_SETTINGS = {
+ success: true,
+ settings: {
+ ...SETTINGS.settings,
+ embedding_provider: 'openai',
+ embedding_model: 'text-embedding-3-small',
+ },
+};
+
+let documentListeners = [];
+
+function jsonResponse(body, status = 200) {
+ return new Response(JSON.stringify(body), { status });
+}
+
+function installFetch(modelPutResponse = () => (
+ Promise.resolve(jsonResponse({ status: 'success' }))
+)) {
+ return vi.fn((url, options = {}) => {
+ if (url === '/library/api/rag/models') {
+ return Promise.resolve(jsonResponse(MODELS));
+ }
+ if (url === '/library/api/rag/settings') {
+ return Promise.resolve(jsonResponse(SETTINGS));
+ }
+ if (url === '/settings/api/embeddings.ollama.url') {
+ return Promise.resolve(jsonResponse({ value: 'http://ollama:11434' }));
+ }
+ if (url === '/settings/api/embeddings.ollama.num_ctx') {
+ return Promise.resolve(jsonResponse({ value: 16384 }));
+ }
+ if (
+ url === '/settings/api/local_search_embedding_model'
+ && options.method === 'PUT'
+ ) {
+ return modelPutResponse(options);
+ }
+ if (url.startsWith('/settings/api/') && options.method === 'PUT') {
+ return Promise.resolve(jsonResponse({ status: 'success' }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+function deferred() {
+ let resolveDeferred;
+ let rejectDeferred;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolveDeferred = resolvePromise;
+ rejectDeferred = rejectPromise;
+ });
+ return {
+ promise,
+ resolve: resolveDeferred,
+ reject: rejectDeferred,
+ };
+}
+
+async function flushPromises(turns = 8) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+function installCatalogRaceFetch(loadOlderCatalog) {
+ let modelGetCount = 0;
+ return vi.fn((url, options = {}) => {
+ if (url === '/library/api/rag/models') {
+ modelGetCount += 1;
+ if (modelGetCount === 1) {
+ return Promise.resolve(jsonResponse(INITIAL_CATALOG));
+ }
+ if (modelGetCount === 2) return loadOlderCatalog();
+ if (modelGetCount === 3) {
+ return Promise.resolve(jsonResponse(NEWEST_CATALOG));
+ }
+ throw new Error(`Unexpected models request ${modelGetCount}`);
+ }
+ if (url === '/library/api/rag/settings') {
+ return Promise.resolve(jsonResponse(SETTINGS));
+ }
+ if (url === '/settings/api/embeddings.ollama.url') {
+ return Promise.resolve(jsonResponse({ value: 'http://ollama:11434' }));
+ }
+ if (url === '/settings/api/embeddings.ollama.num_ctx') {
+ return Promise.resolve(jsonResponse({ value: 16384 }));
+ }
+ if (url.startsWith('/settings/api/') && options.method === 'PUT') {
+ return Promise.resolve(jsonResponse({ status: 'success' }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+async function startCatalogRace(fetchMock) {
+ await loadPage(fetchMock);
+ const provider = document.getElementById('embedding-provider');
+ provider.value = 'catalog-alpha';
+ provider.dispatchEvent(new Event('change'));
+ provider.value = 'catalog-beta';
+ provider.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ const modelGets = fetchMock.mock.calls.filter(([url]) => (
+ url === '/library/api/rag/models'
+ ));
+ expect(modelGets).toHaveLength(3);
+ });
+ await vi.waitFor(() => {
+ expect(document.getElementById('embedding-model').value)
+ .toBe('beta-newest-model');
+ });
+}
+
+function savedModelValues(fetchMock) {
+ return fetchMock.mock.calls
+ .filter(([url, options = {}]) => (
+ url === '/settings/api/local_search_embedding_model' &&
+ options.method === 'PUT'
+ ))
+ .map(([, options]) => JSON.parse(options.body).value);
+}
+
+function installOpenAIFetch(batchSizeResponse = () => jsonResponse({ value: 8 })) {
+ let batchSizeGetCount = 0;
+ return vi.fn((url, options = {}) => {
+ if (url === '/library/api/rag/models') {
+ return Promise.resolve(jsonResponse(OPENAI_MODELS));
+ }
+ if (url === '/library/api/rag/settings') {
+ return Promise.resolve(jsonResponse(OPENAI_SETTINGS));
+ }
+ if (url === '/settings/api/embeddings.ollama.url') {
+ return Promise.resolve(jsonResponse({ value: 'http://ollama:11434' }));
+ }
+ if (url === '/settings/api/embeddings.ollama.num_ctx') {
+ return Promise.resolve(jsonResponse({ value: 16384 }));
+ }
+ if (url === '/settings/api/embeddings.openai.chunk_size') {
+ if (options.method === 'PUT') {
+ return Promise.resolve(jsonResponse({ status: 'success' }));
+ }
+ batchSizeGetCount += 1;
+ return Promise.resolve(batchSizeResponse(batchSizeGetCount));
+ }
+ if (url.startsWith('/settings/api/') && options.method === 'PUT') {
+ return Promise.resolve(jsonResponse({ status: 'success' }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+}
+
+async function loadPage(fetchMock) {
+ vi.stubGlobal('safeFetchWithAuth', fetchMock);
+ await import('@js/embedding_settings.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(document.getElementById('embedding-model').value)
+ .toBe('model-old');
+ });
+}
+
+async function loadOpenAIPage(fetchMock, expectedBatchSize = '8') {
+ vi.stubGlobal('safeFetchWithAuth', fetchMock);
+ await import('@js/embedding_settings.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(document.getElementById('embedding-provider').value)
+ .toBe('openai');
+ expect(document.getElementById('openai-embedding-batch-size').value)
+ .toBe(expectedBatchSize);
+ expect(document.getElementById('openai-embedding-batch-size-group').hidden)
+ .toBe(false);
+ });
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ documentListeners = [];
+ const addDocumentListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture
+ document.body.innerHTML = readFileSync(TEMPLATE_PATH, 'utf8');
+ vi.stubGlobal('LDR_CONSTANTS', {
+ DEFAULT_LOCAL_SEARCH_TEXT_SEPARATORS: ['\\n\\n', '\\n', ' '],
+ });
+ vi.stubGlobal('escapeHtml', value => String(value));
+ window.escapeHtml = value => String(value);
+ window.XSSProtection = { escapeHtml: value => String(value) };
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-embedding') };
+ window.ui = { showMessage: vi.fn() };
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.escapeHtml;
+ delete window.XSSProtection;
+ delete window.api;
+ delete window.ui;
+ document.body.replaceChildren();
+});
+
+it('hydrates the real form from the migrated models and settings endpoints', async () => {
+ const fetchMock = installFetch();
+ await loadPage(fetchMock);
+
+ expect(fetchMock.mock.calls.slice(0, 4).map(([url]) => url)).toEqual([
+ '/library/api/rag/models',
+ '/library/api/rag/settings',
+ '/settings/api/embeddings.ollama.url',
+ '/settings/api/embeddings.ollama.num_ctx',
+ ]);
+ expect(document.getElementById('embedding-provider').value)
+ .toBe('sentence_transformers');
+ expect(Array.from(
+ document.getElementById('embedding-model').options,
+ option => option.value,
+ )).toEqual(['model-old', 'model-new']);
+ expect(document.getElementById('chunk-size').value).toBe('640');
+ expect(document.getElementById('chunk-overlap').value).toBe('80');
+ expect(document.getElementById('normalize-vectors').checked).toBe(true);
+ expect(document.getElementById('ollama-url').value)
+ .toBe('http://ollama:11434');
+ expect(document.getElementById('ollama-num-ctx').value).toBe('16384');
+});
+
+it('ignores an older model catalog before reading its response body', async () => {
+ const olderRequest = deferred();
+ const olderResponse = {
+ ok: true,
+ json: vi.fn().mockResolvedValue(STALE_CATALOG),
+ };
+ const fetchMock = installCatalogRaceFetch(() => olderRequest.promise);
+
+ await startCatalogRace(fetchMock);
+ await vi.waitFor(() => {
+ expect(savedModelValues(fetchMock)).toContain('beta-newest-model');
+ });
+ olderRequest.resolve(olderResponse);
+ await flushPromises();
+
+ expect(olderResponse.json).not.toHaveBeenCalled();
+ expect(document.getElementById('embedding-model').value)
+ .toBe('beta-newest-model');
+ expect(Array.from(
+ document.getElementById('embedding-model').options,
+ option => option.value,
+ )).toEqual(['beta-newest-model']);
+ expect(savedModelValues(fetchMock))
+ .not.toContain('beta-stale-fallback-model');
+});
+
+it('ignores an older model catalog whose JSON body finishes last', async () => {
+ const olderBody = deferred();
+ const olderResponse = {
+ ok: true,
+ json: vi.fn(() => olderBody.promise),
+ };
+ const fetchMock = installCatalogRaceFetch(
+ () => Promise.resolve(olderResponse),
+ );
+
+ await startCatalogRace(fetchMock);
+ expect(olderResponse.json).toHaveBeenCalledOnce();
+ await vi.waitFor(() => {
+ expect(savedModelValues(fetchMock)).toContain('beta-newest-model');
+ });
+ olderBody.resolve(STALE_CATALOG);
+ await flushPromises();
+
+ expect(document.getElementById('embedding-model').value)
+ .toBe('beta-newest-model');
+ expect(Array.from(
+ document.getElementById('embedding-model').options,
+ option => option.value,
+ )).toEqual(['beta-newest-model']);
+ expect(savedModelValues(fetchMock))
+ .not.toContain('beta-stale-fallback-model');
+});
+
+it('does not show an error from an older model catalog request', async () => {
+ const olderRequest = deferred();
+ const fetchMock = installCatalogRaceFetch(() => olderRequest.promise);
+
+ await startCatalogRace(fetchMock);
+ await vi.waitFor(() => {
+ expect(savedModelValues(fetchMock)).toContain('beta-newest-model');
+ });
+ olderRequest.reject(new Error('obsolete model catalog failed'));
+ await flushPromises();
+
+ expect(document.querySelector('.ldr-alert-danger')).toBeNull();
+ expect(document.getElementById('embedding-model').value)
+ .toBe('beta-newest-model');
+ expect(savedModelValues(fetchMock))
+ .not.toContain('beta-stale-fallback-model');
+});
+
+it('persists a model change through the single-setting FastAPI route', async () => {
+ const fetchMock = installFetch();
+ await loadPage(fetchMock);
+
+ const model = document.getElementById('embedding-model');
+ model.value = 'model-new';
+ model.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/local_search_embedding_model',
+ expect.objectContaining({ method: 'PUT' }),
+ );
+ });
+ const [, options] = fetchMock.mock.calls.find(
+ ([url]) => url === '/settings/api/local_search_embedding_model',
+ );
+ expect(options.headers).toEqual({
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-embedding',
+ });
+ expect(JSON.parse(options.body)).toEqual({ value: 'model-new' });
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Embedding model: model-old → model-new',
+ 'success',
+ 6000,
+ );
+ });
+});
+
+it('persists the remaining embedding controls through their dotted settings routes', async () => {
+ const fetchMock = installFetch();
+ await loadPage(fetchMock);
+
+ const changes = [
+ ['chunk-size', '880', 'blur'],
+ ['chunk-overlap', '120', 'blur'],
+ ['splitter-type', 'token', 'change'],
+ ['distance-metric', 'l2', 'change'],
+ ['index-type', 'hnsw', 'change'],
+ ['ollama-num-ctx', '32768', 'blur'],
+ ];
+ for (const [id, value, eventType] of changes) {
+ const element = document.getElementById(id);
+ element.value = value;
+ element.dispatchEvent(new Event(eventType));
+ }
+ const normalize = document.getElementById('normalize-vectors');
+ normalize.checked = false;
+ normalize.dispatchEvent(new Event('change'));
+ const separators = document.getElementById('text-separators');
+ separators.value = JSON.stringify(['\\n\\n', '---']);
+ separators.dispatchEvent(new Event('blur'));
+ const ollamaUrl = document.getElementById('ollama-url');
+ ollamaUrl.value = 'http://ollama-new:11434';
+ ollamaUrl.dispatchEvent(new Event('blur'));
+
+ const expected = new Map([
+ ['local_search_chunk_size', 880],
+ ['local_search_chunk_overlap', 120],
+ ['local_search_splitter_type', 'token'],
+ ['local_search_distance_metric', 'l2'],
+ ['local_search_index_type', 'hnsw'],
+ ['local_search_normalize_vectors', false],
+ ['local_search_text_separators', ['\\n\\n', '---']],
+ ['embeddings.ollama.num_ctx', 32768],
+ ['embeddings.ollama.url', 'http://ollama-new:11434'],
+ ]);
+ await vi.waitFor(() => {
+ const puts = fetchMock.mock.calls.filter(([, request = {}]) => (
+ request.method === 'PUT'
+ ));
+ expect(puts).toHaveLength(expected.size);
+ });
+
+ for (const [key, value] of expected) {
+ expect(fetchMock).toHaveBeenCalledWith(`/settings/api/${key}`, {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-embedding',
+ },
+ body: JSON.stringify({ value }),
+ });
+ }
+});
+
+it('rejects out-of-range chunk and Ollama context values before fetch', async () => {
+ const fetchMock = installFetch();
+ await loadPage(fetchMock);
+
+ for (const [id, value] of [
+ ['chunk-size', '99'],
+ ['chunk-overlap', '1001'],
+ ['ollama-num-ctx', '511'],
+ ]) {
+ const element = document.getElementById(id);
+ element.value = value;
+ element.dispatchEvent(new Event('blur'));
+ }
+ await Promise.resolve();
+
+ const puts = fetchMock.mock.calls.filter(([, request = {}]) => (
+ request.method === 'PUT'
+ ));
+ expect(puts).toHaveLength(0);
+});
+
+it('serializes rapid model changes, including a return to the stored value', async () => {
+ const olderSave = deferred();
+ const newerSave = deferred();
+ let putCount = 0;
+ const fetchMock = installFetch(() => {
+ putCount += 1;
+ return putCount === 1 ? olderSave.promise : newerSave.promise;
+ });
+ await loadPage(fetchMock);
+
+ const model = document.getElementById('embedding-model');
+ model.value = 'model-new';
+ model.dispatchEvent(new Event('change'));
+ model.value = 'model-old';
+ model.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ const puts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/local_search_embedding_model' &&
+ request.method === 'PUT'
+ ));
+ expect(puts).toHaveLength(1);
+ expect(JSON.parse(puts[0][1].body)).toEqual({ value: 'model-new' });
+ });
+
+ olderSave.resolve(jsonResponse({ status: 'success' }));
+ await vi.waitFor(() => {
+ const puts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/local_search_embedding_model' &&
+ request.method === 'PUT'
+ ));
+ expect(puts).toHaveLength(2);
+ expect(JSON.parse(puts[1][1].body)).toEqual({ value: 'model-old' });
+ });
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+
+ newerSave.resolve(jsonResponse({ status: 'success' }));
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+ });
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Embedding model: model-new → model-old',
+ 'success',
+ 6000,
+ );
+});
+
+it('retries a failed rollback from the committed stale-success baseline', async () => {
+ const saveToNew = deferred();
+ const failedRollback = deferred();
+ const retriedRollback = deferred();
+ const saves = [saveToNew, failedRollback, retriedRollback];
+ let putCount = 0;
+ const fetchMock = installFetch(() => {
+ const save = saves[putCount];
+ putCount += 1;
+ return save.promise;
+ });
+ await loadPage(fetchMock);
+
+ const model = document.getElementById('embedding-model');
+ model.value = 'model-new';
+ model.dispatchEvent(new Event('change'));
+ model.value = 'model-old';
+ model.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => expect(putCount).toBe(1));
+ saveToNew.resolve(jsonResponse({ status: 'success' }));
+ await vi.waitFor(() => expect(putCount).toBe(2));
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+
+ failedRollback.resolve(jsonResponse({
+ error: 'rollback rejected',
+ }, 500));
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Failed to save Embedding model: rollback rejected',
+ 'error',
+ );
+ });
+ window.ui.showMessage.mockClear();
+
+ // The form is already back on model-old. The successful stale first PUT
+ // nevertheless committed model-new, so this retry must not be skipped as
+ // an apparent no-op against the original page-load value.
+ model.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => expect(putCount).toBe(3));
+
+ const puts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/local_search_embedding_model' &&
+ request.method === 'PUT'
+ ));
+ expect(puts.map(([, request]) => JSON.parse(request.body))).toEqual([
+ { value: 'model-new' },
+ { value: 'model-old' },
+ { value: 'model-old' },
+ ]);
+
+ retriedRollback.resolve(jsonResponse({ status: 'success' }));
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Embedding model: model-new → model-old',
+ 'success',
+ 6000,
+ );
+ });
+});
+
+it('hydrates and saves the OpenAI request batch size through its dotted key', async () => {
+ const fetchMock = installOpenAIFetch();
+ await loadOpenAIPage(fetchMock);
+
+ const batchSize = document.getElementById('openai-embedding-batch-size');
+ batchSize.value = '13';
+ batchSize.dispatchEvent(new Event('input'));
+ batchSize.dispatchEvent(new Event('blur'));
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/embeddings.openai.chunk_size',
+ expect.objectContaining({ method: 'PUT' }),
+ );
+ });
+ const [, options] = fetchMock.mock.calls.find(([url, request = {}]) => (
+ url === '/settings/api/embeddings.openai.chunk_size' &&
+ request.method === 'PUT'
+ ));
+ expect(options.headers).toEqual({
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-embedding',
+ });
+ expect(JSON.parse(options.body)).toEqual({ value: 13 });
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Embedding request batch size: 8 → 13',
+ 'success',
+ 6000,
+ );
+ });
+});
+
+it.each([
+ ['zero', '0'],
+ ['a fraction', '1.5'],
+ ['an empty value', ''],
+])('rejects %s for the OpenAI request batch size without issuing a PUT', async (_label, value) => {
+ const fetchMock = installOpenAIFetch();
+ await loadOpenAIPage(fetchMock);
+ const batchSize = document.getElementById('openai-embedding-batch-size');
+
+ batchSize.value = value;
+ batchSize.dispatchEvent(new Event('input'));
+ batchSize.dispatchEvent(new Event('blur'));
+ await Promise.resolve();
+
+ const batchSizePuts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/embeddings.openai.chunk_size' &&
+ request.method === 'PUT'
+ ));
+ expect(batchSizePuts).toHaveLength(0);
+ expect(batchSize.classList.contains('ldr-field-invalid')).toBe(true);
+ expect(batchSize.getAttribute('aria-invalid')).toBe('true');
+ const error = document.getElementById('openai-embedding-batch-size-error');
+ expect(error.style.display).toBe('block');
+ expect(error.textContent).toBe('Enter a whole number of at least 1.');
+});
+
+it.each([
+ ['invalid JSON', '["\\n"'],
+ ['a non-array JSON value', '{"separator":"\\n"}'],
+])('rejects %s for text separators without issuing a PUT', async (_label, value) => {
+ const fetchMock = installFetch();
+ await loadPage(fetchMock);
+ const separators = document.getElementById('text-separators');
+
+ separators.value = value;
+ separators.dispatchEvent(new Event('blur'));
+ await Promise.resolve();
+
+ const separatorPuts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/local_search_text_separators' &&
+ request.method === 'PUT'
+ ));
+ expect(separatorPuts).toHaveLength(0);
+ expect(separators.classList.contains('ldr-field-invalid')).toBe(true);
+ const error = document.getElementById('text-separators-error');
+ expect(error.style.display).toBe('block');
+ expect(error.textContent).toMatch(/JSON array|Invalid JSON format/);
+});
+
+it('does not let late OpenAI hydration overwrite a user edit', async () => {
+ const lateHydration = deferred();
+ const fetchMock = installOpenAIFetch((getCount) => (
+ getCount === 1
+ ? jsonResponse({ value: 8 })
+ : lateHydration.promise
+ ));
+ await loadOpenAIPage(fetchMock);
+
+ const provider = document.getElementById('embedding-provider');
+ provider.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => {
+ const hydrationGets = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/embeddings.openai.chunk_size' &&
+ request.method !== 'PUT'
+ ));
+ expect(hydrationGets).toHaveLength(2);
+ });
+
+ const batchSize = document.getElementById('openai-embedding-batch-size');
+ batchSize.value = '21';
+ batchSize.dispatchEvent(new Event('input'));
+ lateHydration.resolve(jsonResponse({ value: 3 }));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('openai-embedding-batch-size-group').hidden)
+ .toBe(false);
+ });
+ expect(batchSize.value).toBe('21');
+ const batchSizePuts = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/embeddings.openai.chunk_size' &&
+ request.method === 'PUT'
+ ));
+ expect(batchSizePuts).toHaveLength(0);
+});
+
+it('does not let late OpenAI hydration undo a provider switch', async () => {
+ const lateHydration = deferred();
+ const lateJson = vi.fn().mockResolvedValue({ value: 99 });
+ const fetchMock = installOpenAIFetch((getCount) => {
+ if (getCount === 1) return jsonResponse({ value: 8 });
+ return lateHydration.promise;
+ });
+ await loadOpenAIPage(fetchMock);
+
+ const provider = document.getElementById('embedding-provider');
+ provider.dispatchEvent(new Event('change'));
+ await vi.waitFor(() => {
+ const hydrationGets = fetchMock.mock.calls.filter(([url, request = {}]) => (
+ url === '/settings/api/embeddings.openai.chunk_size' &&
+ request.method !== 'PUT'
+ ));
+ expect(hydrationGets).toHaveLength(2);
+ });
+
+ provider.value = 'ollama';
+ provider.dispatchEvent(new Event('change'));
+ expect(document.getElementById('openai-embedding-batch-size-group').hidden)
+ .toBe(true);
+
+ lateHydration.resolve({ ok: true, json: lateJson });
+ await vi.waitFor(() => {
+ expect(lateJson).toHaveBeenCalledOnce();
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(provider.value).toBe('ollama');
+ expect(document.getElementById('openai-embedding-batch-size-group').hidden)
+ .toBe(true);
+ expect(document.getElementById('openai-embedding-batch-size').value)
+ .toBe('8');
+});
diff --git a/tests/js/embedding-test-configuration-runtime.test.js b/tests/js/embedding-test-configuration-runtime.test.js
new file mode 100644
index 0000000000..221b4edd8b
--- /dev/null
+++ b/tests/js/embedding-test-configuration-runtime.test.js
@@ -0,0 +1,140 @@
+/**
+ * Execute the production inline-onclick handler that probes the selected
+ * embedding model. The broader page runtime suite covers bootstrap/save;
+ * this pins the distinct /library/api/rag/test-embedding contract.
+ */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from './helpers/template-harness.js';
+
+const SOURCE_PATH = resolve(
+ __dirname,
+ '../../src/local_deep_research/web/static/js/embedding_settings.js',
+);
+
+function loadTestConfiguration({ safeFetchWithAuth, showError, showSuccess }) {
+ return compileTemplateHarness({
+ templatePath: SOURCE_PATH,
+ functionNames: ['testConfiguration'],
+ dependencies: { safeFetchWithAuth, showError, showSuccess },
+ returnExpression: 'testConfiguration',
+ });
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.api;
+ delete window.XSSProtection;
+ document.body.replaceChildren();
+});
+
+it('POSTs the selected model with CSRF and renders the migrated success envelope', async () => {
+ document.body.innerHTML = `
+ <select id="embedding-provider">
+ <option value="sentence_transformers" selected>Sentence Transformers</option>
+ </select>
+ <select id="embedding-model">
+ <option value="all-MiniLM-L6-v2" selected>MiniLM</option>
+ </select>
+ <button id="test-config-btn"></button>
+ <div id="test-result" style="display: none"></div>
+ `;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-embedding-test') };
+ window.XSSProtection = { escapeHtml: value => String(value) };
+ const safeFetchWithAuth = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({
+ success: true,
+ dimension: 384,
+ response_time_ms: 42,
+ }), { status: 200 }),
+ );
+ const showError = vi.fn();
+ const showSuccess = vi.fn();
+ const testConfiguration = loadTestConfiguration({
+ safeFetchWithAuth,
+ showError,
+ showSuccess,
+ });
+
+ await testConfiguration();
+
+ expect(safeFetchWithAuth).toHaveBeenCalledWith(
+ '/library/api/rag/test-embedding',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-embedding-test',
+ },
+ body: JSON.stringify({
+ provider: 'sentence_transformers',
+ model: 'all-MiniLM-L6-v2',
+ test_text: 'This is a test sentence to verify the embedding model is working correctly.',
+ }),
+ },
+ );
+ expect(document.getElementById('test-result').textContent)
+ .toContain('Test Passed!');
+ expect(document.getElementById('test-result').textContent)
+ .toContain('Embedding dimension: 384');
+ expect(document.getElementById('test-result').textContent)
+ .toContain('Response time: 42ms');
+ expect(document.getElementById('test-config-btn').disabled).toBe(false);
+ expect(showSuccess).toHaveBeenCalledWith('Embedding test passed!');
+ expect(showError).not.toHaveBeenCalled();
+});
+
+it('escapes a failed test envelope and restores the test button', async () => {
+ document.body.innerHTML = `
+ <select id="embedding-provider">
+ <option value="openai" selected>OpenAI</option>
+ </select>
+ <select id="embedding-model">
+ <option value="text-embedding-3-small" selected>Small</option>
+ </select>
+ <button id="test-config-btn"></button>
+ <div id="test-result" style="display: none"></div>
+ `;
+ const payload = '<img src=x onerror="window.__embeddingXss = true">';
+ const escapeHtml = value => String(value).replace(
+ /[&<>"']/g,
+ character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ })[character],
+ );
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-embedding-test') };
+ window.XSSProtection = { escapeHtml };
+ const safeFetchWithAuth = vi.fn().mockResolvedValue(
+ new Response(JSON.stringify({
+ success: false,
+ error: payload,
+ }), { status: 422 }),
+ );
+ const showError = vi.fn();
+ const showSuccess = vi.fn();
+ const testConfiguration = loadTestConfiguration({
+ safeFetchWithAuth,
+ showError,
+ showSuccess,
+ });
+
+ await testConfiguration();
+
+ const result = document.getElementById('test-result');
+ expect(result.style.display).toBe('block');
+ expect(result.querySelector('img')).toBeNull();
+ expect(result.textContent).toContain(payload);
+ expect(window.__embeddingXss).toBeUndefined();
+ expect(showError).toHaveBeenCalledWith(
+ 'Embedding test failed: ' + payload,
+ );
+ expect(showSuccess).not.toHaveBeenCalled();
+ const button = document.getElementById('test-config-btn');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Test Embedding Model');
+});
diff --git a/tests/js/followup.test.js b/tests/js/followup.test.js
index f4e3e1841c..48bd22d826 100644
--- a/tests/js/followup.test.js
+++ b/tests/js/followup.test.js
@@ -11,6 +11,14 @@
* have to be re-derived from the test setup.
*/
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+const FOLLOWUP_TEMPLATE = readFileSync(resolvePath(
+ __dirname,
+ '../../src/local_deep_research/web/static/templates/followup_modal.html',
+), 'utf8');
+
let FollowUpResearch;
beforeAll(async () => {
@@ -31,7 +39,14 @@ function setLocation(pathname, search = '') {
Object.defineProperty(window, 'location', {
configurable: true,
writable: true,
- value: { pathname, search, hash: '', host: 'localhost', protocol: 'http:' },
+ value: {
+ pathname,
+ search,
+ hash: '',
+ href: pathname + search,
+ host: 'localhost',
+ protocol: 'http:',
+ },
});
}
@@ -84,3 +99,500 @@ describe('FollowUpResearch.getResearchIdFromPage', () => {
expect(fr.getResearchIdFromPage()).toBe('from-path');
});
});
+
+describe('FollowUpResearch FastAPI contracts', () => {
+ beforeEach(() => {
+ setLocation('/results/parent-123');
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-followup') };
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.api;
+ delete window.ui;
+ delete window.bootstrap;
+ document.body.innerHTML = '';
+ });
+
+ it('prepares and renders the parent context from the migrated response envelope', async () => {
+ document.body.innerHTML = `
+ <section id="parentContext" style="display: none"></section>
+ <div id="parentSummary"></div>
+ <div id="parentSources"></div>
+ `;
+ globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ parent_summary: 'The original migration report',
+ available_sources: 7,
+ }), { status: 200 }));
+
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ await followup.loadParentContext();
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/followup/prepare',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-followup',
+ },
+ body: JSON.stringify({
+ parent_research_id: 'parent-123',
+ question: 'test',
+ }),
+ },
+ );
+ expect(document.getElementById('parentContext').style.display)
+ .toBe('block');
+ expect(document.getElementById('parentSummary').textContent)
+ .toBe('The original migration report');
+ expect(document.getElementById('parentSources').textContent).toBe('7');
+ });
+
+ it('starts a follow-up with CSRF and consumes the success/research_id envelope', async () => {
+ document.body.innerHTML = `
+ <textarea id="followUpQuestion">What changed?</textarea>
+ <div id="followup-error-container"></div>
+ <div id="followUpModal"></div>
+ `;
+ const modal = { hide: vi.fn() };
+ window.bootstrap = {
+ Modal: { getInstance: vi.fn(() => modal) },
+ };
+ window.ui = {
+ clearInlineError: vi.fn(),
+ showInlineError: vi.fn(),
+ };
+ globalThis.fetch = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ research_id: 'followup-456',
+ }), { status: 200 }));
+
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+ await followup.submitFollowUp();
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/api/followup/start',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-followup',
+ },
+ body: JSON.stringify({
+ parent_research_id: 'parent-123',
+ question: 'What changed?',
+ }),
+ },
+ );
+ expect(modal.hide).toHaveBeenCalledOnce();
+ expect(window.location.href).toBe('/progress/followup-456');
+ expect(window.ui.showInlineError).not.toHaveBeenCalled();
+ });
+});
+
+describe('FollowUpResearch browser lifecycle and failure recovery', () => {
+ beforeEach(() => {
+ setLocation('/results/parent-123');
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-followup') };
+ window.ui = {
+ clearInlineError: vi.fn(),
+ showInlineError: vi.fn(),
+ };
+ window.alert = vi.fn();
+ globalThis.fetch = vi.fn();
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ document.head.querySelector('#followup-modal-styles')?.remove();
+ delete window.api;
+ delete window.ui;
+ delete window.bootstrap;
+ delete window.alert;
+ });
+
+ it('disables the entry point when no research ID owns the page', () => {
+ setLocation('/library');
+ document.body.innerHTML = '<button id="ask-followup-btn"></button>';
+ const followup = new FollowUpResearch();
+ followup.createModal = vi.fn();
+
+ followup.init();
+
+ const button = document.getElementById('ask-followup-btn');
+ expect(button.disabled).toBe(true);
+ expect(button.title).toBe('No research ID available');
+ expect(followup.createModal).toHaveBeenCalledOnce();
+ });
+
+ it('wires the results-page entry point to the owning research instance', () => {
+ document.body.innerHTML = '<button id="ask-followup-btn"></button>';
+ const followup = new FollowUpResearch();
+ followup.createModal = vi.fn();
+ followup.showFollowUpModal = vi.fn();
+
+ followup.init();
+ document.getElementById('ask-followup-btn').click();
+
+ expect(followup.parentResearchId).toBe('parent-123');
+ expect(followup.showFollowUpModal).toHaveBeenCalledOnce();
+ expect(followup.createModal).toHaveBeenCalledOnce();
+ });
+
+ it('loads the checked-in modal template and owns its start and close controls', async () => {
+ document.body.innerHTML = '<button id="ask-followup-btn"></button>';
+ globalThis.fetch.mockResolvedValue({
+ ok: true,
+ text: () => Promise.resolve(FOLLOWUP_TEMPLATE),
+ });
+ const followup = new FollowUpResearch();
+
+ await followup.createModal();
+ followup.modalElement.dispatchEvent(new Event('hidden.bs.modal'));
+ followup.addModalStyles();
+
+ expect(globalThis.fetch)
+ .toHaveBeenCalledWith('/static/templates/followup_modal.html');
+ expect(followup.modalElement.id).toBe('followUpModal');
+ expect(followup.getStartButton())
+ .toBe(followup.modalElement.querySelector('.modal-footer .btn-primary'));
+ expect(followup.getStartButton().getAttribute('onclick'))
+ .toBe('followUpResearch.submitFollowUp()');
+ expect(window.ui.clearInlineError)
+ .toHaveBeenCalledWith('followup-error-container');
+ expect(document.querySelectorAll('#followup-modal-styles')).toHaveLength(1);
+ });
+
+ it('aborts showing after a visible template-load failure', async () => {
+ document.body.innerHTML = '<button id="ask-followup-btn"></button>';
+ globalThis.fetch.mockResolvedValue({ ok: false, status: 503 });
+ const errorSpy = vi.spyOn(SafeLogger, 'error');
+ const followup = new FollowUpResearch();
+
+ await followup.showFollowUpModal();
+
+ const button = document.getElementById('ask-followup-btn');
+ expect(button.disabled).toBe(true);
+ expect(button.title).toBe('Failed to load follow-up modal template');
+ expect(window.alert).toHaveBeenCalledWith(
+ 'Unable to load follow-up interface. Please refresh the page and try again.',
+ );
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error loading follow-up modal template:',
+ expect.objectContaining({ message: 'Failed to load modal template: 503' }),
+ );
+ expect(followup.modalElement).toBeNull();
+ expect(followup.modalLoadPromise).toBeNull();
+ });
+
+ it('adopts an already-rendered modal without fetching a second copy', async () => {
+ document.body.innerHTML = '<div id="followUpModal"></div>';
+ const existing = document.getElementById('followUpModal');
+ const followup = new FollowUpResearch();
+
+ await followup.createModal();
+
+ expect(followup.modalElement).toBe(existing);
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ });
+
+ it('loads parent context before displaying the Bootstrap modal', async () => {
+ document.body.innerHTML = '<div id="followUpModal"></div>';
+ const show = vi.fn();
+ window.bootstrap = {
+ Modal: vi.fn(function Modal() {
+ return { show };
+ }),
+ };
+ const followup = new FollowUpResearch();
+ followup.modalElement = document.getElementById('followUpModal');
+ followup.loadParentContext = vi.fn().mockResolvedValue(undefined);
+
+ await followup.showFollowUpModal();
+
+ expect(followup.loadParentContext).toHaveBeenCalledOnce();
+ expect(window.bootstrap.Modal)
+ .toHaveBeenCalledWith(followup.modalElement);
+ expect(show).toHaveBeenCalledOnce();
+ });
+
+ it('contains a failed parent-context request so the modal remains usable', async () => {
+ document.body.innerHTML = `
+ <section id="parentContext" style="display: none"></section>
+ <div id="parentSummary"></div>
+ <div id="parentSources"></div>
+ `;
+ globalThis.fetch.mockRejectedValue(new Error('context unavailable'));
+ const errorSpy = vi.spyOn(SafeLogger, 'error');
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+
+ await expect(followup.loadParentContext()).resolves.toBeUndefined();
+
+ expect(document.getElementById('parentContext').style.display)
+ .toBe('none');
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error loading parent context:',
+ expect.objectContaining({ message: 'context unavailable' }),
+ );
+ });
+
+ it('shares an eager modal load with an immediate show request', async () => {
+ let finishFetch;
+ globalThis.fetch.mockImplementation(() => new Promise((resolve) => {
+ finishFetch = resolve;
+ }));
+ const show = vi.fn();
+ window.bootstrap = {
+ Modal: vi.fn(function Modal() {
+ return { show };
+ }),
+ };
+ const followup = new FollowUpResearch();
+ followup.loadParentContext = vi.fn().mockResolvedValue(undefined);
+
+ const eagerLoad = followup.createModal();
+ const immediateShow = followup.showFollowUpModal();
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ finishFetch({
+ ok: true,
+ text: () => Promise.resolve(`
+ <div id="followUpModal">
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `),
+ });
+ await Promise.all([eagerLoad, immediateShow]);
+
+ expect(document.querySelectorAll('#followUpModal')).toHaveLength(1);
+ expect(followup.modalElement)
+ .toBe(document.getElementById('followUpModal'));
+ expect(followup.loadParentContext).toHaveBeenCalledOnce();
+ expect(show).toHaveBeenCalledOnce();
+ expect(followup.modalLoadPromise).toBeNull();
+ });
+
+ it('rejects empty questions and missing ownership before calling FastAPI', async () => {
+ document.body.innerHTML = `
+ <textarea id="followUpQuestion"> </textarea>
+ <div id="followup-error-container"></div>
+ `;
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+
+ await followup.submitFollowUp();
+ document.getElementById('followUpQuestion').value = 'What next?';
+ followup.parentResearchId = null;
+ await followup.submitFollowUp();
+
+ expect(globalThis.fetch).not.toHaveBeenCalled();
+ expect(window.ui.showInlineError.mock.calls).toEqual([
+ ['followup-error-container', 'Please enter a follow-up question'],
+ ['followup-error-container', 'No parent research ID available'],
+ ]);
+ });
+
+ it('surfaces a non-2xx response and re-enables the start action for retry', async () => {
+ document.body.innerHTML = `
+ <div id="followUpModal">
+ <textarea id="followUpQuestion">What next?</textarea>
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `;
+ globalThis.fetch.mockResolvedValue(new Response('backend unavailable', {
+ status: 503,
+ statusText: 'Unavailable',
+ }));
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+
+ await followup.submitFollowUp();
+
+ expect(window.ui.showInlineError).toHaveBeenCalledWith(
+ 'followup-error-container',
+ 'Failed to start follow-up research: HTTP error! status: 503',
+ );
+ expect(document.querySelector('.modal-footer .btn-primary').disabled)
+ .toBe(false);
+ expect(followup.submitInProgress).toBe(false);
+ });
+
+ it('surfaces a non-2xx FastAPI error body and keeps the action retryable', async () => {
+ document.body.innerHTML = `
+ <div id="followUpModal">
+ <textarea id="followUpQuestion">What next?</textarea>
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `;
+ globalThis.fetch.mockResolvedValue(new Response(JSON.stringify({
+ success: false,
+ error: 'Server is at research capacity. Please retry shortly.',
+ }), {
+ status: 429,
+ statusText: 'Too Many Requests',
+ }));
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+
+ await followup.submitFollowUp();
+
+ expect(window.ui.showInlineError).toHaveBeenCalledWith(
+ 'followup-error-container',
+ 'Failed to start follow-up research: ' +
+ 'Server is at research capacity. Please retry shortly.',
+ );
+ expect(document.querySelector('.modal-footer .btn-primary').disabled)
+ .toBe(false);
+ expect(followup.submitInProgress).toBe(false);
+ });
+
+ it.each([
+ ['missing', undefined],
+ ['blank', ' '],
+ ['non-finite', Number.POSITIVE_INFINITY],
+ ])('keeps a malformed success with a %s research ID retryable', async (
+ _label,
+ researchId,
+ ) => {
+ document.body.innerHTML = `
+ <div id="followUpModal">
+ <textarea id="followUpQuestion">What next?</textarea>
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `;
+ const modal = { hide: vi.fn() };
+ window.bootstrap = {
+ Modal: { getInstance: vi.fn(() => modal) },
+ };
+ globalThis.fetch.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ research_id: researchId,
+ }),
+ });
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+ const originalLocation = window.location.href;
+
+ await followup.submitFollowUp();
+
+ expect(modal.hide).not.toHaveBeenCalled();
+ expect(window.location.href).toBe(originalLocation);
+ expect(window.ui.showInlineError).toHaveBeenCalledWith(
+ 'followup-error-container',
+ 'Error starting follow-up research: ' +
+ 'Response did not include a valid research ID',
+ );
+ expect(document.querySelector('.modal-footer .btn-primary').disabled)
+ .toBe(false);
+ expect(followup.submitInProgress).toBe(false);
+ });
+
+ it('encodes a valid returned research ID as one progress path segment', async () => {
+ document.body.innerHTML = `
+ <div id="followUpModal">
+ <textarea id="followUpQuestion">What next?</textarea>
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `;
+ const modal = { hide: vi.fn() };
+ window.bootstrap = {
+ Modal: { getInstance: vi.fn(() => modal) },
+ };
+ globalThis.fetch.mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ research_id: 'followup/3299?source=parent',
+ }),
+ });
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+
+ await followup.submitFollowUp();
+
+ expect(modal.hide).toHaveBeenCalledOnce();
+ expect(window.location.href)
+ .toBe('/progress/followup%2F3299%3Fsource%3Dparent');
+ expect(window.ui.showInlineError).not.toHaveBeenCalled();
+ });
+
+ it('owns an in-flight start request so a double-click cannot create two child researches', async () => {
+ document.body.innerHTML = `
+ <div id="followUpModal">
+ <textarea id="followUpQuestion">What next?</textarea>
+ <div class="modal-footer">
+ <button class="btn btn-primary"></button>
+ </div>
+ <div id="followup-error-container"></div>
+ </div>
+ `;
+ let finishRequest;
+ globalThis.fetch.mockImplementationOnce(() => new Promise((resolve) => {
+ finishRequest = resolve;
+ }));
+ const followup = new FollowUpResearch();
+ followup.parentResearchId = 'parent-123';
+ followup.modalElement = document.getElementById('followUpModal');
+
+ const first = followup.submitFollowUp();
+ const duplicate = followup.submitFollowUp();
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ expect(document.querySelector('.modal-footer .btn-primary').disabled)
+ .toBe(true);
+
+ finishRequest(new Response(JSON.stringify({
+ success: false,
+ error: 'parent is no longer available',
+ }), { status: 200 }));
+ await Promise.all([first, duplicate]);
+
+ expect(window.ui.showInlineError).toHaveBeenCalledWith(
+ 'followup-error-container',
+ 'Error starting follow-up research: parent is no longer available',
+ );
+ expect(document.querySelector('.modal-footer .btn-primary').disabled)
+ .toBe(false);
+ expect(followup.submitInProgress).toBe(false);
+
+ globalThis.fetch.mockResolvedValueOnce(new Response(JSON.stringify({
+ success: false,
+ }), { status: 200 }));
+ await followup.submitFollowUp();
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
+ expect(window.ui.showInlineError).toHaveBeenLastCalledWith(
+ 'followup-error-container',
+ 'Error starting follow-up research: Unknown error',
+ );
+ });
+});
diff --git a/tests/js/helpers/template-harness.js b/tests/js/helpers/template-harness.js
new file mode 100644
index 0000000000..a0c7459a4d
--- /dev/null
+++ b/tests/js/helpers/template-harness.js
@@ -0,0 +1,104 @@
+import { readFileSync } from 'node:fs';
+import { tokenizer } from 'acorn';
+
+function findFunctionEnd(source, startIndex) {
+ const tokens = tokenizer(source.slice(startIndex), {
+ ecmaVersion: 'latest',
+ });
+ let parameterDepth = 0;
+ let parametersStarted = false;
+ let parametersClosed = false;
+ let bodyDepth = 0;
+
+ try {
+ for (const token of tokens) {
+ const label = token.type.label;
+
+ if (!parametersStarted) {
+ if (label === '(') {
+ parametersStarted = true;
+ parameterDepth = 1;
+ }
+ continue;
+ }
+
+ if (!parametersClosed) {
+ if (label === '(') parameterDepth += 1;
+ if (label === ')') {
+ parameterDepth -= 1;
+ parametersClosed = parameterDepth === 0;
+ }
+ continue;
+ }
+
+ if (bodyDepth === 0) {
+ if (label !== '{') return -1;
+ bodyDepth = 1;
+ continue;
+ }
+
+ // Acorn emits `${` as one token and its closing interpolation
+ // brace as `}`, so include it in the structural brace depth.
+ if (label === '{' || label === '${') bodyDepth += 1;
+ if (label === '}') {
+ bodyDepth -= 1;
+ if (bodyDepth === 0) return startIndex + token.end;
+ }
+ }
+ } catch (error) {
+ throw new Error('JavaScript block contains invalid syntax', {
+ cause: error,
+ });
+ }
+
+ return -1;
+}
+
+export function extractJavaScriptBlock(source, startIndex) {
+ const functionEnd = findFunctionEnd(source, startIndex);
+ if (functionEnd === -1) {
+ throw new Error('JavaScript block has an unterminated body');
+ }
+ return source.slice(startIndex, functionEnd);
+}
+
+export function extractTemplateFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ try {
+ return extractJavaScriptBlock(source, match.index);
+ } catch (error) {
+ throw new Error(
+ `Function ${name}${error.message.slice('JavaScript block'.length)}`,
+ { cause: error },
+ );
+ }
+}
+
+/**
+ * Compile named functions directly from a checked-in inline template script.
+ * This keeps runtime tests tied to the production browser code instead of a
+ * hand-copied approximation of it.
+ */
+export function compileTemplateHarness({
+ templatePath,
+ functionNames,
+ dependencies = {},
+ preamble = '',
+ returnExpression,
+}) {
+ const template = readFileSync(templatePath, 'utf8');
+ const productionSource = functionNames
+ .map(name => extractTemplateFunction(template, name))
+ .join('\n');
+ const dependencyNames = Object.keys(dependencies);
+ // The generated body consists only of repository-owned template source
+ // plus fixed test declarations, never user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `${preamble}\n${productionSource}\nreturn ${returnExpression};`,
+ );
+ return factory(...Object.values(dependencies));
+}
diff --git a/tests/js/helpers/template-harness.test.js b/tests/js/helpers/template-harness.test.js
new file mode 100644
index 0000000000..bbc0b6555e
--- /dev/null
+++ b/tests/js/helpers/template-harness.test.js
@@ -0,0 +1,115 @@
+import {
+ extractJavaScriptBlock,
+ extractTemplateFunction,
+} from './template-harness.js';
+
+describe('template harness source extraction', () => {
+ it('ignores braces inside strings, comments, regexes, and template text', () => {
+ const source = [
+ 'function target(value) {',
+ " const singleQuoted = '}';",
+ ' const doubleQuoted = "{";',
+ ' const closingBrace = /\\}/u;',
+ ' const characterClass = /[{}]/u;',
+ [' const rendered = `raw } $', '{value ? "{" : "}"}`;']
+ .join(''),
+ ' // } ignored line-comment brace',
+ ' /* { ignored block-comment brace */',
+ ' return {',
+ ' singleQuoted,',
+ ' doubleQuoted,',
+ ' matches: closingBrace.test(value) && characterClass.test(value),',
+ ' rendered,',
+ ' };',
+ '}',
+ 'function afterTarget() { throw new Error("must not be extracted"); }',
+ ].join('\n');
+
+ const extracted = extractTemplateFunction(source, 'target');
+ const target = new Function(`return (${extracted});`)(); // eslint-disable-line no-new-func
+
+ expect(extracted).not.toContain('afterTarget');
+ expect(target('}')).toEqual({
+ singleQuoted: '}',
+ doubleQuoted: '{',
+ matches: true,
+ rendered: 'raw } {',
+ });
+ });
+
+ it('distinguishes division from a following regex literal', () => {
+ const source = [
+ 'function classify(value) {',
+ ' const half = value.length / 2;',
+ ' return /\\}/u.test(value) ? half : 0;',
+ '}',
+ 'const unrelated = "}";',
+ ].join('\n');
+
+ const extracted = extractTemplateFunction(source, 'classify');
+ const classify = new Function(`return (${extracted});`)(); // eslint-disable-line no-new-func
+
+ expect(classify('a}')).toBe(1);
+ expect(classify('ab')).toBe(0);
+ });
+
+ it('extracts anonymous callback blocks with the same lexical rules', () => {
+ const source = 'prefix function() { return `literal }`; }, suffix';
+ const functionIndex = source.indexOf('function');
+
+ expect(extractJavaScriptBlock(source, functionIndex))
+ .toBe('function() { return `literal }`; }');
+ });
+
+ it('skips destructuring and object-default braces in function parameters', () => {
+ const namedSource = [
+ 'function target({ value }, options = {}) {',
+ ' return options.fallback ?? value;',
+ '}',
+ 'const unrelated = {};',
+ ].join('\n');
+ const anonymousSource = [
+ 'prefix function({ value }, options = {}) {',
+ ' return options.fallback ?? value;',
+ '}, suffix',
+ ].join('\n');
+
+ const named = extractTemplateFunction(namedSource, 'target');
+ const anonymous = extractJavaScriptBlock(
+ anonymousSource,
+ anonymousSource.indexOf('function'),
+ );
+
+ expect(new Function(`return (${named});`)()({ value: 3 })) // eslint-disable-line no-new-func
+ .toBe(3);
+ expect(new Function(`return (${anonymous});`)()({ value: 4 })) // eslint-disable-line no-new-func
+ .toBe(4);
+ expect(named).not.toContain('unrelated');
+ });
+
+ it('recognizes regex literals after control-condition parentheses', () => {
+ const source = [
+ 'function containsClosingBrace(value) {',
+ ' if (value) /}/.test(value);',
+ ' return value;',
+ '}',
+ 'const unrelated = "}";',
+ ].join('\n');
+
+ const extracted = extractTemplateFunction(
+ source,
+ 'containsClosingBrace',
+ );
+
+ expect(() => new Function(`return (${extracted});`)()) // eslint-disable-line no-new-func
+ .not.toThrow();
+ expect(extracted).not.toContain('unrelated');
+ });
+
+ it('reports missing and unterminated template functions by name', () => {
+ expect(() => extractTemplateFunction('const value = 1;', 'missing'))
+ .toThrow('Function missing not found in template');
+ expect(() => extractTemplateFunction('function broken() {', 'broken'))
+ .toThrow('Function broken has an unterminated body');
+ });
+});
diff --git a/tests/js/mobile-navigation.test.js b/tests/js/mobile-navigation.test.js
index f492407c86..7c3dbfbe5c 100644
--- a/tests/js/mobile-navigation.test.js
+++ b/tests/js/mobile-navigation.test.js
@@ -171,3 +171,241 @@ describe('MobileNavigation.isCurrentPage', () => {
expect(nav().isCurrentPage({ id: 'news' })).toBe(false);
});
});
+
+describe('MobileNavigation username rendering', () => {
+ afterEach(() => {
+ document.querySelectorAll('.ldr-user-info').forEach(element => element.remove());
+ });
+
+ it('keeps hostile account text inert when building the sheet menu', () => {
+ const userInfo = document.createElement('div');
+ userInfo.className = 'ldr-user-info';
+ userInfo.textContent = 'Alice <img src=x onerror=alert(1)> & "Admin"';
+ document.body.appendChild(userInfo);
+
+ const nav = new MobileNavigation();
+ const username = nav.getUsername();
+ nav.createSheetMenu();
+
+ const userItem = nav.elements.sheet.querySelector('[data-item-id="user"]');
+ expect(username).toContain('Alice');
+ expect(username).not.toMatch(/[<>&"']/);
+ expect(userItem.querySelector('img')).toBeNull();
+ expect(userItem.querySelector('.ldr-mobile-sheet-label').textContent).toBe(
+ username,
+ );
+ });
+});
+
+describe('MobileNavigation interactive lifecycle', () => {
+ let nav;
+ let originalInnerWidth;
+ let animationFrames;
+
+ function setInnerWidth(px) {
+ Object.defineProperty(window, 'innerWidth', {
+ value: px,
+ configurable: true,
+ writable: true,
+ });
+ }
+
+ function flushSheetFrames() {
+ while (animationFrames.length > 0) {
+ animationFrames.shift()();
+ }
+ }
+
+ function touchEvent(type, clientY) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'touches', {
+ value: [{ clientY }],
+ });
+ return event;
+ }
+
+ beforeEach(() => {
+ window.mobileNav?.destroy();
+ delete window.mobileNav;
+ document.body.replaceChildren();
+ document.body.className = '';
+ document.body.style.overflow = '';
+ localStorage.clear();
+ originalInnerWidth = window.innerWidth;
+ animationFrames = [];
+ vi.useFakeTimers();
+ vi.stubGlobal('requestAnimationFrame', vi.fn(callback => {
+ animationFrames.push(callback);
+ return animationFrames.length;
+ }));
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+ });
+
+ afterEach(() => {
+ nav?.destroy();
+ nav = null;
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ Object.defineProperty(window, 'innerWidth', {
+ value: originalInnerWidth,
+ configurable: true,
+ writable: true,
+ });
+ localStorage.clear();
+ document.body.replaceChildren();
+ document.body.className = '';
+ document.body.style.overflow = '';
+ });
+
+ it('opens accessibly and restores the desktop layout after a resize', async () => {
+ setInnerWidth(500);
+ document.body.innerHTML = '<aside class="ldr-sidebar"></aside>';
+ const sidebar = document.querySelector('.ldr-sidebar');
+ nav = new MobileNavigation({
+ enableGestures: false,
+ persistState: false,
+ });
+
+ nav.init();
+
+ expect(nav.initialized).toBe(true);
+ expect(nav.elements.nav.classList).toContain('visible');
+ expect(document.body.classList).toContain('ldr-has-mobile-nav');
+ expect(sidebar.style.display).toBe('none');
+ expect(sidebar.dataset.mobileHidden).toBe('true');
+
+ nav.openSheet();
+ flushSheetFrames();
+
+ const firstItem = nav.getFirstFocusableElement();
+ expect(nav.state.sheetOpen).toBe(true);
+ expect(nav.elements.sheet.classList).toContain('active');
+ expect(nav.elements.sheet.hasAttribute('aria-hidden')).toBe(false);
+ expect(nav.elements.overlay.classList).toContain('active');
+ expect(document.activeElement).toBe(firstItem);
+ expect(nav.elements.nav.querySelector('[data-tab-id="more"]')
+ .getAttribute('aria-expanded')).toBe('true');
+
+ setInnerWidth(900);
+ window.dispatchEvent(new Event('resize'));
+ await vi.advanceTimersByTimeAsync(250);
+
+ expect(nav.state.isVisible).toBe(false);
+ expect(nav.state.sheetOpen).toBe(false);
+ expect(nav.elements.nav.classList).not.toContain('visible');
+ expect(document.body.classList).not.toContain('ldr-has-mobile-nav');
+ expect(document.body.style.overflow).toBe('');
+ expect(sidebar.style.display).toBe('');
+ expect(sidebar.hasAttribute('data-mobile-hidden')).toBe(false);
+
+ await vi.advanceTimersByTimeAsync(350);
+ expect(nav.elements.sheet.style.display).toBe('none');
+ });
+
+ it('traps keyboard focus and returns it to More when Escape closes the sheet', () => {
+ setInnerWidth(500);
+ nav = new MobileNavigation({ persistState: false });
+ nav.init();
+ nav.openSheet();
+ flushSheetFrames();
+ const focusable = nav.getFocusableElements();
+ const first = focusable[0];
+ const last = focusable[focusable.length - 1];
+
+ last.focus();
+ const forwardTab = new KeyboardEvent('keydown', {
+ key: 'Tab',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(forwardTab);
+ expect(forwardTab.defaultPrevented).toBe(true);
+ expect(document.activeElement).toBe(first);
+
+ const backwardTab = new KeyboardEvent('keydown', {
+ key: 'Tab',
+ shiftKey: true,
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(backwardTab);
+ expect(backwardTab.defaultPrevented).toBe(true);
+ expect(document.activeElement).toBe(last);
+
+ const escape = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(escape);
+ const more = nav.elements.nav.querySelector('[data-tab-id="more"]');
+ expect(escape.defaultPrevented).toBe(true);
+ expect(nav.state.sheetOpen).toBe(false);
+ expect(document.activeElement).toBe(more);
+ expect(more.getAttribute('aria-expanded')).toBe('false');
+ });
+
+ it('delegates tab, sheet, and logout actions through safe navigation', () => {
+ setInnerWidth(500);
+ document.body.innerHTML = '<form id="logout-form"></form>';
+ const submit = vi.spyOn(
+ document.getElementById('logout-form'),
+ 'submit',
+ ).mockImplementation(() => {});
+ nav = new MobileNavigation();
+ nav.init();
+
+ nav.elements.nav.querySelector('[data-tab-id="history"] i').click();
+ expect(URLValidator.safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ '/history/',
+ );
+ expect(nav.state.activeTab).toBe('history');
+ expect(JSON.parse(localStorage.getItem('mobileNavState')))
+ .toEqual({ activeTab: 'history' });
+
+ nav.elements.nav.querySelector('[data-tab-id="more"] i').click();
+ expect(nav.state.sheetOpen).toBe(true);
+ nav.elements.sheet.querySelector('[data-item-id="collections"] i')
+ .click();
+ expect(URLValidator.safeAssign).toHaveBeenLastCalledWith(
+ window.location,
+ 'href',
+ '/library/collections',
+ );
+ expect(nav.state.sheetOpen).toBe(false);
+
+ nav.elements.sheet.querySelector('[data-item-id="logout"] i').click();
+ expect(submit).toHaveBeenCalledOnce();
+ });
+
+ it('dismisses only a downward swipe beyond the sheet threshold', () => {
+ setInnerWidth(500);
+ nav = new MobileNavigation({ persistState: false });
+ nav.init();
+ Object.defineProperty(nav.elements.sheet, 'offsetHeight', {
+ value: 500,
+ configurable: true,
+ });
+ nav.openSheet();
+ const handle = nav.elements.sheet.querySelector(
+ '.ldr-mobile-sheet-handle',
+ );
+
+ handle.dispatchEvent(touchEvent('touchstart', 100));
+ handle.dispatchEvent(touchEvent('touchmove', 140));
+ expect(nav.elements.sheet.style.transform).toBe('translateY(40px)');
+ handle.dispatchEvent(touchEvent('touchend', 140));
+ expect(nav.state.sheetOpen).toBe(true);
+ expect(nav.elements.sheet.style.transform).toBe('');
+
+ handle.dispatchEvent(touchEvent('touchstart', 100));
+ handle.dispatchEvent(touchEvent('touchmove', 230));
+ handle.dispatchEvent(touchEvent('touchend', 230));
+ expect(nav.state.sheetOpen).toBe(false);
+ expect(nav.elements.sheet.getAttribute('aria-hidden')).toBe('true');
+ });
+});
diff --git a/tests/js/pages/analytics-loaders-runtime.test.js b/tests/js/pages/analytics-loaders-runtime.test.js
new file mode 100644
index 0000000000..8a77ecca2d
--- /dev/null
+++ b/tests/js/pages/analytics-loaders-runtime.test.js
@@ -0,0 +1,477 @@
+/** Response-envelope contracts for unchanged metrics dashboard consumers. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_DIR = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages',
+);
+
+function extract(file, pattern, name) {
+ const template = readFileSync(resolve(TEMPLATE_DIR, file), 'utf8');
+ const match = template.match(pattern);
+ expect(match, `${name} source block not found`).toBeTruthy();
+ return match[1];
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolveValue, rejectError) => {
+ resolvePromise = resolveValue;
+ rejectPromise = rejectError;
+ });
+ return { promise, reject: rejectPromise, resolve: resolvePromise };
+}
+
+function starReviewCalls() {
+ return Object.fromEntries([
+ 'showLoading',
+ 'showError',
+ 'updateOverallStats',
+ 'updateDoughnutChart',
+ 'updateLLMChart',
+ 'updateSearchEngineChart',
+ 'updateTrendsChart',
+ 'updateRecentRatings',
+ 'updateModeChart',
+ 'updateLLMBreakdownChart',
+ 'updateQualityRadar',
+ 'updateRecentFeedback',
+ 'showContent',
+ 'announceChartStates',
+ ].map(name => [name, vi.fn()]));
+}
+
+function compileStarReviews(calls, registerPeriodChange = false) {
+ const loaderSource = extract(
+ 'star_reviews.html',
+ /(async function loadStarReviews\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Announce the refresh/,
+ 'loadStarReviews()',
+ );
+ const registrationSource = registerPeriodChange
+ ? extract(
+ 'star_reviews.html',
+ /(document\.getElementById\('period-select'\)\.addEventListener\('change', loadStarReviews\);)/,
+ 'period-select change registration',
+ )
+ : '';
+ const declarations = Object.keys(calls)
+ .map(name => `const ${name} = (...args) => calls.${name}(...args);`)
+ .join('\n');
+
+ // Repository-owned production source only; no user-controlled input.
+ return new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ ${declarations}
+ let starReviewsRequestId = 0;
+ ${loaderSource}
+ ${registrationSource}
+ return { loadStarReviews };
+ `)(calls);
+}
+
+function starReviewPayload(period) {
+ return {
+ overall_stats: { avg_rating: period === '7d' ? 4.7 : 3.0, period },
+ llm_ratings: [{ model: period }],
+ search_engine_ratings: [{ engine: period }],
+ rating_trends: [{ date: period }],
+ recent_ratings: [{ period }],
+ mode_ratings: [{ mode: period }],
+ quality_dimensions: { period },
+ recent_feedback: [{ feedback: period }],
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('fans the star-review envelope out to every dashboard consumer', async () => {
+ const calls = starReviewCalls();
+ const { loadStarReviews } = compileStarReviews(calls);
+ document.body.innerHTML = '<select id="period-select"><option value="90d" selected>90 days</option></select>';
+ const payload = {
+ overall_stats: { avg_rating: 4.5 },
+ llm_ratings: [{ model: 'm1' }],
+ search_engine_ratings: [{ engine: 'e1' }],
+ rating_trends: [{ date: '2026-08-31' }],
+ recent_ratings: [{ rating: 5 }],
+ mode_ratings: [{ mode: 'quick' }],
+ quality_dimensions: { accuracy: 4.8 },
+ recent_feedback: [{ feedback: 'useful' }],
+ };
+ const fetchMock = vi.fn().mockResolvedValue(new Response(
+ JSON.stringify(payload),
+ { status: 200 },
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await loadStarReviews();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/star-reviews?period=90d',
+ );
+ expect(calls.updateOverallStats)
+ .toHaveBeenCalledWith(payload.overall_stats);
+ expect(calls.updateDoughnutChart)
+ .toHaveBeenCalledWith(payload.overall_stats);
+ expect(calls.updateLLMChart).toHaveBeenCalledWith(payload.llm_ratings);
+ expect(calls.updateSearchEngineChart)
+ .toHaveBeenCalledWith(payload.search_engine_ratings);
+ expect(calls.updateTrendsChart).toHaveBeenCalledWith(payload.rating_trends);
+ expect(calls.updateRecentRatings)
+ .toHaveBeenCalledWith(payload.recent_ratings);
+ expect(calls.updateModeChart).toHaveBeenCalledWith(payload.mode_ratings);
+ expect(calls.updateLLMBreakdownChart)
+ .toHaveBeenCalledWith(payload.llm_ratings);
+ expect(calls.updateQualityRadar)
+ .toHaveBeenCalledWith(payload.quality_dimensions);
+ expect(calls.updateRecentFeedback)
+ .toHaveBeenCalledWith(payload.recent_feedback);
+ expect(calls.showContent).toHaveBeenCalledOnce();
+ expect(calls.announceChartStates).toHaveBeenCalledOnce();
+ expect(calls.showError).not.toHaveBeenCalled();
+});
+
+it.each([
+ {
+ label: 'HTTP failure',
+ response: {
+ ok: false,
+ status: 503,
+ statusText: 'Unavailable',
+ },
+ expectedError: 'Failed to load star reviews data: HTTP 503: Unavailable',
+ },
+ {
+ label: 'API error envelope',
+ response: new Response(JSON.stringify({
+ error: 'Ratings warehouse is unavailable',
+ })),
+ expectedError: 'Ratings warehouse is unavailable',
+ },
+])('surfaces the current star-review $label', async ({
+ response,
+ expectedError,
+}) => {
+ document.body.innerHTML = `
+ <select id="period-select">
+ <option value="30d" selected>30 days</option>
+ </select>
+ `;
+ const calls = starReviewCalls();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await compileStarReviews(calls).loadStarReviews();
+
+ expect(calls.showError).toHaveBeenCalledOnce();
+ expect(calls.showError).toHaveBeenCalledWith(expectedError);
+ expect(calls.updateOverallStats).not.toHaveBeenCalled();
+ expect(calls.showContent).not.toHaveBeenCalled();
+ expect(calls.announceChartStates).not.toHaveBeenCalled();
+});
+
+it('keeps a late older star-review success from replacing a period change', async () => {
+ document.body.innerHTML = `
+ <select id="period-select">
+ <option value="30d" selected>30 days</option>
+ <option value="7d">7 days</option>
+ </select>
+ `;
+ const calls = starReviewCalls();
+ const runtime = compileStarReviews(calls, true);
+ const olderResponse = deferred();
+ const currentResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => currentResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = runtime.loadStarReviews();
+ const periodSelect = document.getElementById('period-select');
+ periodSelect.value = '7d';
+ periodSelect.dispatchEvent(new Event('change', { bubbles: true }));
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/star-reviews?period=30d',
+ '/metrics/api/star-reviews?period=7d',
+ ]);
+
+ const currentPayload = starReviewPayload('7d');
+ currentResponse.resolve(new Response(JSON.stringify(currentPayload)));
+ await vi.waitFor(() => {
+ expect(calls.updateOverallStats).toHaveBeenCalledWith(
+ currentPayload.overall_stats,
+ );
+ });
+
+ olderResponse.resolve(new Response(JSON.stringify(
+ starReviewPayload('30d'),
+ )));
+ await olderLoad;
+
+ expect(calls.updateOverallStats).toHaveBeenCalledOnce();
+ expect(calls.updateLLMChart).toHaveBeenCalledWith(
+ currentPayload.llm_ratings,
+ );
+ expect(calls.showContent).toHaveBeenCalledOnce();
+ expect(calls.showError).not.toHaveBeenCalled();
+});
+
+it('ignores a stale star-review rejection after the newer period renders', async () => {
+ document.body.innerHTML = `
+ <select id="period-select">
+ <option value="30d" selected>30 days</option>
+ <option value="7d">7 days</option>
+ </select>
+ `;
+ const calls = starReviewCalls();
+ const runtime = compileStarReviews(calls, true);
+ const olderResponse = deferred();
+ const currentResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => currentResponse.promise));
+
+ const olderLoad = runtime.loadStarReviews();
+ const periodSelect = document.getElementById('period-select');
+ periodSelect.value = '7d';
+ periodSelect.dispatchEvent(new Event('change', { bubbles: true }));
+
+ const currentPayload = starReviewPayload('7d');
+ currentResponse.resolve(new Response(JSON.stringify(currentPayload)));
+ await vi.waitFor(() => {
+ expect(calls.showContent).toHaveBeenCalledOnce();
+ });
+
+ olderResponse.reject(new Error('late network failure'));
+ await olderLoad;
+
+ expect(calls.updateOverallStats).toHaveBeenCalledOnce();
+ expect(calls.updateOverallStats).toHaveBeenCalledWith(
+ currentPayload.overall_stats,
+ );
+ expect(calls.showError).not.toHaveBeenCalled();
+ expect(calls.showContent).toHaveBeenCalledOnce();
+});
+
+it('consumes the nested link-analytics data envelope and period', async () => {
+ const loaderSource = extract(
+ 'link_analytics.html',
+ /(async function loadLinkAnalytics\(period = '30d'\)\s*\{[\s\S]*?\n\})\n\nfunction generateCategoryGrid/,
+ 'loadLinkAnalytics()',
+ );
+ const calls = Object.fromEntries([
+ 'generateCategoryGrid',
+ 'updateTopDomainsChart',
+ 'updateDomainDistributionChart',
+ 'updateSourceTypeChart',
+ 'updateTemporalTrendChart',
+ 'updateEnhancedDomainList',
+ ].map(name => [name, vi.fn()]));
+ const declarations = Object.keys(calls)
+ .map(name => `const ${name} = (...args) => calls.${name}(...args);`)
+ .join('\n');
+ // Repository-owned production source only; no user-controlled input.
+ const loadLinkAnalytics = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ ${declarations}
+ let linkAnalyticsRequestId = 0;
+ ${loaderSource}
+ return loadLinkAnalytics;
+ `)(calls);
+ document.body.innerHTML = `
+ <div id="loading"></div><div id="content"></div><div id="error"></div>
+ <div id="total-links"></div><div id="unique-domains"></div>
+ <div id="avg-links"></div><div id="total-researches"></div>
+ `;
+ const data = {
+ total_links: 10,
+ total_unique_domains: 4,
+ avg_links_per_research: 2.5,
+ total_researches: 4,
+ domain_categories: { academic: 3 },
+ top_domains: [{ domain: 'example.org' }],
+ domain_distribution: { example: 2 },
+ temporal_trend: [{ date: '2026-08-31', count: 2 }],
+ domain_metrics: { 'example.org': { usage_count: 2 } },
+ };
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ status: 'success',
+ data,
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await loadLinkAnalytics('7d');
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/link-analytics?period=7d',
+ );
+ expect(document.getElementById('total-links').textContent).toBe('10');
+ expect(document.getElementById('unique-domains').textContent).toBe('4');
+ expect(calls.generateCategoryGrid)
+ .toHaveBeenCalledWith(data.domain_categories);
+ expect(calls.updateTopDomainsChart).toHaveBeenCalledWith(data.top_domains);
+ expect(calls.updateDomainDistributionChart)
+ .toHaveBeenCalledWith(data.domain_distribution);
+ expect(calls.updateSourceTypeChart)
+ .toHaveBeenCalledWith(data.domain_categories);
+ expect(calls.updateTemporalTrendChart)
+ .toHaveBeenCalledWith(data.temporal_trend);
+ expect(calls.updateEnhancedDomainList).toHaveBeenCalledWith(
+ data.top_domains,
+ data.domain_metrics,
+ );
+ expect(document.getElementById('loading').style.display).toBe('none');
+ expect(document.getElementById('content').style.display).toBe('block');
+});
+
+it('keeps the current link-analytics error visible and the content hidden', async () => {
+ const loaderSource = extract(
+ 'link_analytics.html',
+ /(async function loadLinkAnalytics\(period = '30d'\)\s*\{[\s\S]*?\n\})\n\nfunction generateCategoryGrid/,
+ 'loadLinkAnalytics()',
+ );
+ const calls = Object.fromEntries([
+ 'generateCategoryGrid',
+ 'updateTopDomainsChart',
+ 'updateDomainDistributionChart',
+ 'updateSourceTypeChart',
+ 'updateTemporalTrendChart',
+ 'updateEnhancedDomainList',
+ ].map(name => [name, vi.fn()]));
+ const declarations = Object.keys(calls)
+ .map(name => `const ${name} = (...args) => calls.${name}(...args);`)
+ .join('\n');
+ const loadLinkAnalytics = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ ${declarations}
+ let linkAnalyticsRequestId = 0;
+ ${loaderSource}
+ return loadLinkAnalytics;
+ `)(calls);
+ document.body.innerHTML = `
+ <div id="loading"></div><div id="content"></div>
+ <div id="error"></div><div id="total-links"></div>
+ <div id="unique-domains"></div><div id="avg-links"></div>
+ <div id="total-researches"></div>
+ `;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
+ JSON.stringify({
+ status: 'error',
+ message: 'Link metrics index is rebuilding',
+ }),
+ )));
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await loadLinkAnalytics('7d');
+
+ const error = document.getElementById('error');
+ expect(error.textContent)
+ .toBe('Failed to load link analytics data. Please try again later.');
+ expect(error.style.display).toBe('block');
+ expect(document.getElementById('loading').style.display).toBe('none');
+ expect(document.getElementById('content').style.display).toBe('none');
+ for (const consumer of Object.values(calls)) {
+ expect(consumer).not.toHaveBeenCalled();
+ }
+});
+
+it('keeps a late older period response from replacing a real change event', async () => {
+ const loaderSource = extract(
+ 'link_analytics.html',
+ /(async function loadLinkAnalytics\(period = '30d'\)\s*\{[\s\S]*?\n\})\n\nfunction generateCategoryGrid/,
+ 'loadLinkAnalytics()',
+ );
+ const registrationSource = extract(
+ 'link_analytics.html',
+ /(document\.getElementById\('period-select'\)\.addEventListener\('change',[\s\S]*?\n\}\);)/,
+ 'period-select change registration',
+ );
+ const calls = Object.fromEntries([
+ 'generateCategoryGrid',
+ 'updateTopDomainsChart',
+ 'updateDomainDistributionChart',
+ 'updateSourceTypeChart',
+ 'updateTemporalTrendChart',
+ 'updateEnhancedDomainList',
+ ].map(name => [name, vi.fn()]));
+ const declarations = Object.keys(calls)
+ .map(name => `const ${name} = (...args) => calls.${name}(...args);`)
+ .join('\n');
+ document.body.innerHTML = `
+ <select id="period-select">
+ <option value="30d" selected>30 days</option>
+ <option value="7d">7 days</option>
+ </select>
+ <div id="loading"></div><div id="content"></div><div id="error"></div>
+ <div id="total-links"></div><div id="unique-domains"></div>
+ <div id="avg-links"></div><div id="total-researches"></div>
+ `;
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ ${declarations}
+ let linkAnalyticsRequestId = 0;
+ ${loaderSource}
+ ${registrationSource}
+ return { loadLinkAnalytics };
+ `)(calls);
+ const olderResponse = deferred();
+ const newerResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => newerResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = runtime.loadLinkAnalytics('30d');
+ const periodSelect = document.getElementById('period-select');
+ periodSelect.value = '7d';
+ periodSelect.dispatchEvent(new Event('change', { bubbles: true }));
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/link-analytics?period=30d',
+ '/metrics/api/link-analytics?period=7d',
+ ]);
+
+ const newerData = {
+ total_links: 7,
+ total_unique_domains: 3,
+ avg_links_per_research: 2.3,
+ total_researches: 3,
+ domain_categories: { current: 7 },
+ top_domains: [{ domain: 'current.test' }],
+ domain_distribution: { current: 7 },
+ temporal_trend: [{ date: '2026-09-01', count: 7 }],
+ domain_metrics: { 'current.test': { usage_count: 7 } },
+ };
+ newerResponse.resolve(new Response(JSON.stringify({
+ status: 'success',
+ data: newerData,
+ }), { status: 200 }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('total-links').textContent).toBe('7');
+ });
+
+ olderResponse.resolve(new Response(JSON.stringify({
+ status: 'success',
+ data: {
+ ...newerData,
+ total_links: 30,
+ top_domains: [{ domain: 'stale.test' }],
+ },
+ }), { status: 200 }));
+ await olderLoad;
+
+ expect(document.getElementById('total-links').textContent).toBe('7');
+ expect(calls.updateTopDomainsChart).toHaveBeenCalledOnce();
+ expect(calls.updateTopDomainsChart)
+ .toHaveBeenCalledWith([{ domain: 'current.test' }]);
+ expect(document.getElementById('error').style.display).toBe('none');
+ expect(document.getElementById('content').style.display).toBe('block');
+});
diff --git a/tests/js/pages/benchmark-child-loader-ownership.test.js b/tests/js/pages/benchmark-child-loader-ownership.test.js
new file mode 100644
index 0000000000..24c6aa891e
--- /dev/null
+++ b/tests/js/pages/benchmark-child-loader-ownership.test.js
@@ -0,0 +1,398 @@
+/** Ownership contracts for asynchronous loaders nested under benchmark polling. */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function response(payload) {
+ return {
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('does not render recent results requested for a superseded run', async () => {
+ const staleResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => staleResponse.promise));
+ const displayRecentResults = vi.fn();
+ document.body.innerHTML = '<div id="recent-results-container"></div>';
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateRecentResults'],
+ dependencies: { displayRecentResults },
+ preamble: `
+ let currentBenchmarkId = 'run-a';
+ let progressRunGeneration = 1;
+ let recentResultsRequestId = 0;
+ let latestAppliedRecentResultsRequestId = 0;
+ let lastResultsData = null;
+ `,
+ returnExpression: `({
+ updateRecentResults,
+ switchRun: () => {
+ currentBenchmarkId = 'run-b';
+ progressRunGeneration++;
+ },
+ })`,
+ });
+
+ const oldLoad = runtime.updateRecentResults();
+ runtime.switchRun();
+ staleResponse.resolve(response({
+ success: true,
+ results: [{ example_id: 'stale-a' }],
+ }));
+ await oldLoad;
+ await Promise.resolve();
+
+ expect(displayRecentResults).not.toHaveBeenCalled();
+ expect(document.getElementById('recent-results-container').textContent)
+ .toBe('');
+});
+
+it('does not write historical run A points into run B chart objects', async () => {
+ const staleResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => staleResponse.promise));
+ const makeChart = () => ({
+ data: { labels: [], datasets: [{ data: [] }] },
+ update: vi.fn(),
+ });
+ const runAAccuracy = makeChart();
+ const runATiming = makeChart();
+ const runBAccuracy = makeChart();
+ const runBTiming = makeChart();
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadHistoricalChartData'],
+ dependencies: {
+ initialAccuracyChart: runAAccuracy,
+ initialTimingChart: runATiming,
+ },
+ preamble: `
+ let currentBenchmarkId = 'run-a';
+ let progressRunGeneration = 1;
+ let historicalChartRequestId = 0;
+ let accuracyChart = initialAccuracyChart;
+ let timingChart = initialTimingChart;
+ const datasetConfigs = [{ key: 'overall' }];
+ `,
+ returnExpression: `({
+ loadHistoricalChartData,
+ switchRun: (accuracy, timing) => {
+ currentBenchmarkId = 'run-b';
+ progressRunGeneration++;
+ accuracyChart = accuracy;
+ timingChart = timing;
+ },
+ })`,
+ });
+
+ const oldLoad = runtime.loadHistoricalChartData();
+ runtime.switchRun(runBAccuracy, runBTiming);
+ staleResponse.resolve(response({
+ success: true,
+ status: {
+ completed_examples: 4,
+ overall_accuracy: 75,
+ avg_time_per_example: 30,
+ },
+ }));
+ await oldLoad;
+
+ expect(runAAccuracy.data.labels).toEqual([]);
+ expect(runBAccuracy.data.labels).toEqual([]);
+ expect(runBTiming.data.labels).toEqual([]);
+ expect(runBAccuracy.update).not.toHaveBeenCalled();
+ expect(runBTiming.update).not.toHaveBeenCalled();
+});
+
+it('does not publish search quality calculated for a superseded run', async () => {
+ const staleResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => staleResponse.promise));
+ const updateSearchResultsChart = vi.fn();
+ const updateSearchQualityAlert = vi.fn();
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateSearchQualityMonitoring'],
+ dependencies: {
+ updateSearchResultsChart,
+ updateSearchQualityAlert,
+ },
+ preamble: `
+ let currentBenchmarkId = 'run-a';
+ let progressRunGeneration = 1;
+ let searchQualityRequestId = 0;
+ let latestAppliedSearchQualityRequestId = 0;
+ `,
+ returnExpression: `({
+ updateSearchQualityMonitoring,
+ switchRun: () => {
+ currentBenchmarkId = 'run-b';
+ progressRunGeneration++;
+ },
+ })`,
+ });
+
+ const oldLoad = runtime.updateSearchQualityMonitoring();
+ runtime.switchRun();
+ staleResponse.resolve(response({
+ success: true,
+ results: [{ search_result_count: 9 }],
+ }));
+ await oldLoad;
+
+ expect(updateSearchResultsChart).not.toHaveBeenCalled();
+ expect(updateSearchQualityAlert).not.toHaveBeenCalled();
+});
+
+it('keeps newer recent results authoritative within the same run', async () => {
+ const olderResponse = deferred();
+ const newerResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => newerResponse.promise));
+ const displayRecentResults = vi.fn();
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateRecentResults'],
+ dependencies: { displayRecentResults },
+ preamble: `
+ let currentBenchmarkId = 'run-overlap';
+ let progressRunGeneration = 1;
+ let recentResultsRequestId = 0;
+ let latestAppliedRecentResultsRequestId = 0;
+ let lastResultsData = null;
+ `,
+ returnExpression: '({ updateRecentResults })',
+ });
+
+ const olderLoad = runtime.updateRecentResults();
+ const newerLoad = runtime.updateRecentResults();
+ const currentResults = [{ example_id: 'current' }];
+ newerResponse.resolve(response({ success: true, results: currentResults }));
+ await newerLoad;
+ olderResponse.resolve(response({
+ success: true,
+ results: [{ example_id: 'stale' }],
+ }));
+ await olderLoad;
+
+ expect(displayRecentResults).toHaveBeenCalledOnce();
+ expect(displayRecentResults).toHaveBeenCalledWith(currentResults);
+});
+
+it('keeps newer historical chart data authoritative within the same run', async () => {
+ const olderResponse = deferred();
+ const newerResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => newerResponse.promise));
+ const accuracyChart = {
+ data: { labels: [], datasets: [{ data: [] }] },
+ update: vi.fn(),
+ };
+ const timingChart = {
+ data: { labels: [], datasets: [{ data: [] }] },
+ update: vi.fn(),
+ };
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadHistoricalChartData'],
+ dependencies: { initialAccuracyChart: accuracyChart, initialTimingChart: timingChart },
+ preamble: `
+ let currentBenchmarkId = 'run-overlap';
+ let progressRunGeneration = 1;
+ let historicalChartRequestId = 0;
+ let accuracyChart = initialAccuracyChart;
+ let timingChart = initialTimingChart;
+ const datasetConfigs = [{ key: 'overall' }];
+ `,
+ returnExpression: '({ loadHistoricalChartData })',
+ });
+
+ const olderLoad = runtime.loadHistoricalChartData();
+ const newerLoad = runtime.loadHistoricalChartData();
+ newerResponse.resolve(response({
+ success: true,
+ status: {
+ completed_examples: 1,
+ overall_accuracy: 80,
+ avg_time_per_example: 60,
+ },
+ }));
+ await newerLoad;
+ olderResponse.resolve(response({
+ success: true,
+ status: {
+ completed_examples: 2,
+ overall_accuracy: 10,
+ avg_time_per_example: 120,
+ },
+ }));
+ await olderLoad;
+
+ expect(accuracyChart.data.labels).toEqual([1]);
+ expect(accuracyChart.data.datasets[0].data).toEqual([80]);
+ expect(timingChart.data.datasets[0].data).toEqual([1]);
+ expect(accuracyChart.update).toHaveBeenCalledOnce();
+ expect(timingChart.update).toHaveBeenCalledOnce();
+});
+
+it('keeps newer search-quality data authoritative within the same run', async () => {
+ const olderResponse = deferred();
+ const newerResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => newerResponse.promise));
+ const updateSearchResultsChart = vi.fn();
+ const updateSearchQualityAlert = vi.fn();
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateSearchQualityMonitoring'],
+ dependencies: { updateSearchResultsChart, updateSearchQualityAlert },
+ preamble: `
+ let currentBenchmarkId = 'run-overlap';
+ let progressRunGeneration = 1;
+ let searchQualityRequestId = 0;
+ let latestAppliedSearchQualityRequestId = 0;
+ `,
+ returnExpression: '({ updateSearchQualityMonitoring })',
+ });
+
+ const olderLoad = runtime.updateSearchQualityMonitoring();
+ const newerLoad = runtime.updateSearchQualityMonitoring();
+ newerResponse.resolve(response({
+ success: true,
+ results: [{ search_result_count: 9 }],
+ }));
+ await newerLoad;
+ olderResponse.resolve(response({
+ success: true,
+ results: [{ search_result_count: 1 }],
+ }));
+ await olderLoad;
+
+ expect(updateSearchResultsChart).toHaveBeenCalledOnce();
+ expect(updateSearchResultsChart).toHaveBeenCalledWith(9);
+ expect(updateSearchQualityAlert).toHaveBeenCalledOnce();
+ expect(updateSearchQualityAlert).toHaveBeenCalledWith(9);
+});
+
+function pollingChildRuntime(functionName) {
+ const display = vi.fn();
+ const runtime = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [functionName],
+ dependencies: {
+ displayRecentResults: display,
+ updateSearchResultsChart: display,
+ updateSearchQualityAlert: vi.fn(),
+ },
+ preamble: `
+ let currentBenchmarkId = 'slow-results-run';
+ let progressRunGeneration = 1;
+ let recentResultsRequestId = 0;
+ let latestAppliedRecentResultsRequestId = 0;
+ let searchQualityRequestId = 0;
+ let latestAppliedSearchQualityRequestId = 0;
+ let lastResultsData = null;
+ `,
+ returnExpression: `({ load: ${functionName} })`,
+ });
+ return { ...runtime, display };
+}
+
+const pollingChildren = ['updateRecentResults', 'updateSearchQualityMonitoring'];
+
+it.each(pollingChildren)('renders slow, in-order responses in %s while the next read is pending', async functionName => {
+ const pending = [];
+ vi.stubGlobal('fetch', vi.fn(() => new Promise(resolveResponse => {
+ pending.push(resolveResponse);
+ })));
+ const runtime = pollingChildRuntime(functionName);
+ let currentLoad = runtime.load();
+
+ for (let count = 1; count <= 4; count++) {
+ // Model responses slower than the parent's polling cadence: the next
+ // request starts first, but responses still arrive in request order.
+ const nextLoad = runtime.load();
+ const results = [{ search_result_count: count }];
+ pending.shift()(response({ success: true, results }));
+ await currentLoad;
+ expect(runtime.display).toHaveBeenCalledTimes(count);
+ expect(runtime.display).toHaveBeenLastCalledWith(
+ functionName === 'updateRecentResults' ? results : count,
+ );
+ currentLoad = nextLoad;
+ }
+
+ pending.shift()(response({ success: false }));
+ await currentLoad;
+});
+
+it.each(pollingChildren)('does not discard a usable %s response after a newer read fails', async functionName => {
+ const older = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => older.promise)
+ .mockResolvedValueOnce(response({ success: false })));
+ const runtime = pollingChildRuntime(functionName);
+ const oldLoad = runtime.load();
+ await runtime.load();
+ const results = [{ search_result_count: 4 }];
+ older.resolve(response({ success: true, results }));
+ await oldLoad;
+
+ expect(runtime.display).toHaveBeenCalledExactlyOnceWith(
+ functionName === 'updateRecentResults' ? results : 4,
+ );
+});
+
+it.each(pollingChildren)('does not restore older %s data after a newer empty snapshot', async functionName => {
+ const older = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => older.promise)
+ .mockResolvedValueOnce(response({ success: true, results: [] })));
+ const runtime = pollingChildRuntime(functionName);
+ const oldLoad = runtime.load();
+ await runtime.load();
+ runtime.display.mockClear();
+ older.resolve(response({ success: true, results: [{ search_result_count: 9 }] }));
+ await oldLoad;
+
+ expect(runtime.display).not.toHaveBeenCalled();
+});
+
+it('keeps a newer persistence error authoritative over older recent results', async () => {
+ const older = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => older.promise)
+ .mockResolvedValueOnce(response({ persistence_error: { message: 'Results unavailable' } })));
+ document.body.innerHTML = '<div id="recent-results-container"></div>';
+ const runtime = pollingChildRuntime('updateRecentResults');
+ const oldLoad = runtime.load();
+ await runtime.load();
+ older.resolve(response({ success: true, results: [{ search_result_count: 9 }] }));
+ await oldLoad;
+
+ expect(runtime.display).not.toHaveBeenCalled();
+ expect(document.getElementById('recent-results-container').textContent)
+ .toBe('Results unavailable');
+});
diff --git a/tests/js/pages/benchmark-current-settings-runtime.test.js b/tests/js/pages/benchmark-current-settings-runtime.test.js
new file mode 100644
index 0000000000..c3d5b62dd8
--- /dev/null
+++ b/tests/js/pages/benchmark-current-settings-runtime.test.js
@@ -0,0 +1,120 @@
+/** Runtime contracts for benchmark.html's current-settings bootstrap. */
+
+import { resolve as resolvePath } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+const SETTINGS = [
+ ['/settings/api/llm.provider', 'ollama'],
+ ['/settings/api/llm.model', 'qwen3:4b'],
+ ['/settings/api/search.tool', 'searxng'],
+ ['/settings/api/search.iterations', 3],
+ ['/settings/api/search.questions_per_iteration', 4],
+ ['/settings/api/search.search_strategy', 'focused_iteration'],
+ ['/settings/api/benchmark.evaluation.provider', 'openai_endpoint'],
+ ['/settings/api/benchmark.evaluation.model', 'judge-model'],
+ ['/settings/api/benchmark.evaluation.temperature', 0.2],
+ ['/settings/api/benchmark.evaluation.endpoint_url', 'https://judge.test/v1'],
+];
+
+function mountCurrentSettings() {
+ document.body.innerHTML = `
+ <section id="current-settings-display">
+ <span class="ldr-metric-value" id="current-provider"></span>
+ <span class="ldr-metric-value" id="current-model"></span>
+ <span class="ldr-metric-value" id="current-search-tool"></span>
+ <span class="ldr-metric-value" id="current-iterations"></span>
+ <span class="ldr-metric-value" id="current-questions"></span>
+ <span class="ldr-metric-value" id="current-strategy"></span>
+ </section>
+ <div id="context-window-warning" style="display: none"></div>
+ `;
+}
+
+function compileCurrentSettings(dependencies) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadCurrentSettings'],
+ dependencies,
+ returnExpression: '({ loadCurrentSettings })',
+ });
+}
+
+function jsonResponse(value) {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue({ value }),
+ };
+}
+
+beforeEach(() => {
+ mountCurrentSettings();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('hydrates the benchmark summary from every migrated flat setting endpoint', async () => {
+ const values = new Map(SETTINGS);
+ const fetchMock = vi.fn(url => Promise.resolve(jsonResponse(values.get(url))));
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ checkSearchEngineWarnings: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const runtime = compileCurrentSettings(dependencies);
+
+ await runtime.loadCurrentSettings();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual(
+ SETTINGS.map(([url]) => url),
+ );
+ expect(document.getElementById('current-provider').textContent).toBe('OLLAMA');
+ expect(document.getElementById('current-model').textContent).toBe('qwen3:4b');
+ expect(document.getElementById('current-search-tool').textContent).toBe('searxng');
+ expect(document.getElementById('current-iterations').textContent).toBe('3');
+ expect(document.getElementById('current-questions').textContent).toBe('4');
+ expect(document.getElementById('current-strategy').textContent)
+ .toBe('focused-iteration');
+ expect(document.getElementById('context-window-warning').style.display)
+ .toBe('block');
+ expect(dependencies.checkSearchEngineWarnings).toHaveBeenCalledOnce();
+ expect(dependencies.checkSearchEngineWarnings).toHaveBeenCalledWith('searxng');
+ expect(dependencies.showAlert).not.toHaveBeenCalled();
+});
+
+it('renders one coherent recovery state when any settings request rejects', async () => {
+ const fetchMock = vi.fn(url => {
+ if (url === '/settings/api/llm.model') {
+ return Promise.reject(new Error('settings temporarily unavailable'));
+ }
+ return Promise.resolve(jsonResponse('unused'));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ checkSearchEngineWarnings: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const runtime = compileCurrentSettings(dependencies);
+
+ await runtime.loadCurrentSettings();
+
+ expect(fetchMock).toHaveBeenCalledTimes(SETTINGS.length);
+ document.querySelectorAll('#current-settings-display .ldr-metric-value')
+ .forEach(element => expect(element.textContent).toBe('Error loading'));
+ expect(dependencies.checkSearchEngineWarnings).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Could not load current settings. Check console for details.',
+ 'warning',
+ );
+});
diff --git a/tests/js/pages/benchmark-endpoint-runtime.test.js b/tests/js/pages/benchmark-endpoint-runtime.test.js
new file mode 100644
index 0000000000..6d20cf542a
--- /dev/null
+++ b/tests/js/pages/benchmark-endpoint-runtime.test.js
@@ -0,0 +1,469 @@
+/**
+ * Live-template contracts for benchmark endpoints that are not shared with
+ * static page modules: cancellation and evaluation settings/model discovery.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function templateSource() {
+ return readFileSync(TEMPLATE_PATH, 'utf8');
+}
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function extractEvaluationModelLoader(source) {
+ const start = source.indexOf('const loadEvaluationModelsFromAPI =');
+ const end = source.indexOf('\n\nfunction filterModelsForProvider', start);
+ if (start === -1 || end === -1) {
+ throw new Error('Evaluation model loader not found in template');
+ }
+ return source.slice(start, end);
+}
+
+function compileCancellation(dependencies) {
+ const source = extractFunction(templateSource(), 'cancelBenchmark');
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'csrfToken',
+ 'showAlert',
+ 'resetForm',
+ 'clearInterval',
+ `
+ let currentBenchmarkId = 3299;
+ let progressInterval = 77;
+ ${source}
+ return {
+ cancelBenchmark,
+ getProgressInterval: () => progressInterval,
+ };
+ `,
+ );
+ return factory(
+ 'csrf-benchmark',
+ dependencies.showAlert,
+ dependencies.resetForm,
+ dependencies.clearInterval,
+ );
+}
+
+function compileSaveEvaluationSetting(csrfToken) {
+ const source = extractFunction(templateSource(), 'saveEvaluationSetting');
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'csrfToken',
+ `${source}\nreturn saveEvaluationSetting;`,
+ );
+ return factory(csrfToken);
+}
+
+function compileEvaluationModelsHarness() {
+ const source = templateSource();
+ const functions = [
+ 'debounce',
+ 'populateEvaluationProviders',
+ 'setupEvaluationModelDropdown',
+ 'getEvaluationModelOptions',
+ 'refreshEvaluationModels',
+ 'saveEvaluationSetting',
+ ].map(name => extractFunction(source, name)).join('\n');
+ const loader = extractEvaluationModelLoader(source);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ `
+ const csrfToken = 'csrf-benchmark';
+ let EVAL_MODEL_PROVIDERS = [];
+ let evaluationModelsRequestVersion = 0;
+ let evaluationProviderSelect = document.getElementById('evaluation_provider');
+ let evaluationModelInput = document.getElementById('evaluation_model');
+ let evaluationEndpointInput = document.getElementById('evaluation_endpoint_url');
+ ${functions}
+ ${loader}
+ return {
+ loadEvaluationModelsFromAPI,
+ populateEvaluationProviders,
+ setupEvaluationModelDropdown,
+ getEvaluationModelOptions,
+ getProviders: () => EVAL_MODEL_PROVIDERS,
+ };
+ `,
+ );
+ return factory();
+}
+
+function modelsPayload(modelValue, modelLabel = modelValue) {
+ return {
+ provider_options: [
+ { value: 'openai', label: 'OpenAI' },
+ { value: 'ollama', label: 'Ollama' },
+ ],
+ providers: {
+ openai_models: [{ value: modelValue, label: modelLabel }],
+ ollama_models: [{ value: 'nomic-embed-text', label: 'Nomic' }],
+ },
+ };
+}
+
+function deferred() {
+ let resolveDeferred;
+ const promise = new Promise((resolvePromise) => {
+ resolveDeferred = resolvePromise;
+ });
+ return { promise, resolve: resolveDeferred };
+}
+
+function renderEvaluationControls() {
+ document.body.innerHTML = `
+ <select id="evaluation_provider" data-initial-value="openai"></select>
+ <div><input id="evaluation_endpoint_url"></div>
+ <div data-target="evaluation-model-dropdown">
+ <input id="evaluation_model">
+ <input id="evaluation_model_hidden">
+ <div id="evaluation-model-dropdown-list"></div>
+ <button class="refresh-btn"><i></i></button>
+ </div>
+ `;
+ window.setupCustomDropdown = vi.fn(() => ({ setValue: vi.fn() }));
+ window.updateDropdownOptions = vi.fn();
+ window.evaluationModels = {};
+ window.modelsLoading = false;
+}
+
+async function flushPromises() {
+ for (let index = 0; index < 6; index += 1) {
+ await Promise.resolve();
+ }
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.setupCustomDropdown;
+ delete window.updateDropdownOptions;
+ delete window.evaluationModels;
+ delete window.evaluationDropdownInstance;
+ delete window.modelsLoading;
+ document.body.replaceChildren();
+});
+
+it('cancels the active benchmark with CSRF and resets only after success', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ showAlert: vi.fn(),
+ resetForm: vi.fn(),
+ clearInterval: vi.fn(),
+ };
+ const harness = compileCancellation(dependencies);
+
+ harness.cancelBenchmark();
+
+ await vi.waitFor(() => {
+ expect(dependencies.resetForm).toHaveBeenCalledOnce();
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/cancel/3299', {
+ method: 'POST',
+ headers: { 'X-CSRFToken': 'csrf-benchmark' },
+ });
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark cancelled successfully.',
+ 'info',
+ );
+ expect(dependencies.clearInterval).toHaveBeenCalledWith(77);
+ expect(harness.getProgressInterval()).toBeNull();
+});
+
+it('keeps the active benchmark intact when cancellation is rejected', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: 'worker still finalizing',
+ }),
+ }));
+ const dependencies = {
+ showAlert: vi.fn(),
+ resetForm: vi.fn(),
+ clearInterval: vi.fn(),
+ };
+ const harness = compileCancellation(dependencies);
+
+ harness.cancelBenchmark();
+
+ await vi.waitFor(() => {
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Error cancelling benchmark: worker still finalizing',
+ 'error',
+ );
+ });
+ expect(dependencies.resetForm).not.toHaveBeenCalled();
+ expect(dependencies.clearInterval).not.toHaveBeenCalled();
+ expect(harness.getProgressInterval()).toBe(77);
+});
+
+it('saves an evaluation setting with the FastAPI value envelope and CSRF', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ compileSaveEvaluationSetting('csrf-evaluation')(
+ 'benchmark.evaluation.temperature',
+ 0.35,
+ );
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/benchmark.evaluation.temperature',
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-evaluation',
+ },
+ body: JSON.stringify({ value: 0.35 }),
+ },
+ );
+ });
+});
+
+it('loads and force-refreshes evaluation providers and model options', async () => {
+ renderEvaluationControls();
+ vi.useFakeTimers();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ json: vi.fn().mockResolvedValue(modelsPayload('initial-model')),
+ })
+ .mockResolvedValueOnce({
+ json: vi.fn().mockResolvedValue(modelsPayload('fresh-model', 'Fresh Model')),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ harness.loadEvaluationModelsFromAPI();
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(fetchMock.mock.calls[0][0]).toBe('/settings/api/available-models');
+ expect(window.evaluationModels.openai).toEqual([
+ { value: 'initial-model', label: 'initial-model' },
+ ]);
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ expect(fetchMock.mock.calls[1][0])
+ .toBe('/settings/api/available-models?force_refresh=true');
+ expect(harness.getProviders()).toEqual([
+ { value: 'openai', label: 'OpenAI' },
+ { value: 'ollama', label: 'Ollama' },
+ ]);
+ expect(window.evaluationModels.openai).toEqual([
+ { value: 'fresh-model', label: 'Fresh Model' },
+ ]);
+ expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
+ document.getElementById('evaluation_model'),
+ [{ value: 'fresh-model', label: 'Fresh Model' }],
+ );
+ expect(document.querySelector('.refresh-btn i').classList.contains('fa-spin'))
+ .toBe(false);
+});
+
+it('starts the initial model request when an empty dropdown asks for options', async () => {
+ renderEvaluationControls();
+ vi.useFakeTimers();
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue(modelsPayload('initial-model')),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+
+ expect(harness.getEvaluationModelOptions()).toEqual([
+ { value: 'gpt-4o', label: 'GPT-4o' },
+ { value: 'gpt-4', label: 'GPT-4' },
+ { value: 'gpt-3.5-turbo', label: 'GPT-3.5 Turbo' },
+ ]);
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(500);
+ await flushPromises();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/available-models');
+ expect(window.evaluationModels.openai).toEqual([
+ { value: 'initial-model', label: 'initial-model' },
+ ]);
+});
+
+it('does not schedule a fallback request while force refresh is in flight', async () => {
+ renderEvaluationControls();
+ vi.useFakeTimers();
+ const refreshResponse = deferred();
+ const fetchMock = vi.fn().mockReturnValue(refreshResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ document.querySelector('.refresh-btn').click();
+ harness.getEvaluationModelOptions();
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/available-models?force_refresh=true',
+ );
+
+ refreshResponse.resolve({
+ json: vi.fn().mockResolvedValue(modelsPayload('fresh-model')),
+ });
+ await flushPromises();
+});
+
+it('keeps the selected provider while force refresh rebuilds its options', async () => {
+ renderEvaluationControls();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue(modelsPayload('fresh-openai')),
+ }));
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+ const provider = document.getElementById('evaluation_provider');
+ provider.value = 'ollama';
+
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+
+ expect(provider.value).toBe('ollama');
+ expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
+ document.getElementById('evaluation_model'),
+ [{ value: 'nomic-embed-text', label: 'Nomic' }],
+ );
+});
+
+it('does not let a deferred initial model response overwrite a force refresh', async () => {
+ renderEvaluationControls();
+ vi.useFakeTimers();
+ const initialResponse = deferred();
+ const refreshResponse = deferred();
+ const fetchMock = vi.fn((url) => {
+ if (url.endsWith('?force_refresh=true')) return refreshResponse.promise;
+ return initialResponse.promise;
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ harness.loadEvaluationModelsFromAPI();
+ await vi.advanceTimersByTimeAsync(500);
+ document.querySelector('.refresh-btn').click();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ refreshResponse.resolve({
+ json: vi.fn().mockResolvedValue(modelsPayload('fresh-model')),
+ });
+ await flushPromises();
+ expect(window.evaluationModels.openai[0].value).toBe('fresh-model');
+
+ initialResponse.resolve({
+ json: vi.fn().mockResolvedValue(modelsPayload('stale-model')),
+ });
+ await flushPromises();
+
+ expect(window.evaluationModels.openai[0].value).toBe('fresh-model');
+ expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
+ document.getElementById('evaluation_model'),
+ [{ value: 'fresh-model', label: 'fresh-model' }],
+ );
+});
+
+it('keeps the newest result when force-refresh responses finish out of order', async () => {
+ renderEvaluationControls();
+ const firstRefresh = deferred();
+ const secondRefresh = deferred();
+ const fetchMock = vi.fn()
+ .mockReturnValueOnce(firstRefresh.promise)
+ .mockReturnValueOnce(secondRefresh.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ const refreshButton = document.querySelector('.refresh-btn');
+ refreshButton.click();
+ refreshButton.click();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ secondRefresh.resolve({
+ json: vi.fn().mockResolvedValue(modelsPayload('newest-model')),
+ });
+ await flushPromises();
+ expect(window.evaluationModels.openai[0].value).toBe('newest-model');
+ expect(refreshButton.querySelector('i').classList.contains('fa-spin'))
+ .toBe(false);
+
+ firstRefresh.resolve({
+ json: vi.fn().mockResolvedValue(modelsPayload('older-model')),
+ });
+ await flushPromises();
+
+ expect(window.evaluationModels.openai[0].value).toBe('newest-model');
+ expect(window.updateDropdownOptions).toHaveBeenLastCalledWith(
+ document.getElementById('evaluation_model'),
+ [{ value: 'newest-model', label: 'newest-model' }],
+ );
+});
+
+it('cancels the pending debounced load when refresh is requested immediately', async () => {
+ renderEvaluationControls();
+ vi.useFakeTimers();
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue(modelsPayload('manual-model')),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ const harness = compileEvaluationModelsHarness();
+ harness.populateEvaluationProviders();
+ harness.setupEvaluationModelDropdown();
+
+ harness.loadEvaluationModelsFromAPI();
+ document.querySelector('.refresh-btn').click();
+ await flushPromises();
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock.mock.calls[0][0])
+ .toBe('/settings/api/available-models?force_refresh=true');
+ expect(window.evaluationModels.openai[0].value).toBe('manual-model');
+});
diff --git a/tests/js/pages/benchmark-monitoring-runtime.test.js b/tests/js/pages/benchmark-monitoring-runtime.test.js
new file mode 100644
index 0000000000..17e803acd6
--- /dev/null
+++ b/tests/js/pages/benchmark-monitoring-runtime.test.js
@@ -0,0 +1,527 @@
+/** Distinct validation and monitoring contracts in the full benchmark page. */
+
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolvePromiseArgument => {
+ resolvePromise = resolvePromiseArgument;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.socket;
+ document.body.replaceChildren();
+});
+
+it('validates the serialized configuration with CSRF', async () => {
+ const config = {
+ run_name: 'migration validation',
+ datasets_config: { simpleqa: { count: 3, seed: 3299 } },
+ };
+ const showAlert = vi.fn();
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ valid: true, errors: [] }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['validateConfiguration'],
+ dependencies: {
+ getConfigurationData: vi.fn(() => config),
+ showAlert,
+ },
+ preamble: "const csrfToken = 'csrf-benchmark';",
+ returnExpression: '({ validateConfiguration })',
+ });
+
+ harness.validateConfiguration();
+
+ await vi.waitFor(() => {
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Configuration is valid! Ready to start benchmark.',
+ 'success',
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/validate-config', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-benchmark',
+ },
+ body: JSON.stringify(config),
+ });
+});
+
+it('consumes terminal status, refreshes monitoring, and stops polling', async () => {
+ const status = {
+ status: 'completed',
+ completed_examples: 8,
+ total_examples: 8,
+ overall_accuracy: 75,
+ };
+ const dependencies = {
+ updateProgressDisplay: vi.fn(),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true, status }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateBenchmarkProgress'],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'run-3299';
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ let progressInterval = 91;
+ let progressRunGeneration = 1;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ `,
+ returnExpression: `({
+ updateBenchmarkProgress,
+ getProgressInterval: () => progressInterval,
+ })`,
+ });
+
+ harness.updateBenchmarkProgress();
+
+ await vi.waitFor(() => {
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark completed successfully!',
+ 'success',
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/benchmark/api/status/run-3299',
+ );
+ expect(dependencies.updateProgressDisplay).toHaveBeenCalledWith(status);
+ expect(dependencies.updateCurrentQuestion).toHaveBeenCalledWith(status);
+ expect(dependencies.updateRecentResults).toHaveBeenCalledOnce();
+ expect(dependencies.updateCharts).toHaveBeenCalledWith(status);
+ expect(dependencies.updateSearchQualityMonitoring).toHaveBeenCalledOnce();
+ expect(dependencies.updateRateLimitingStatus).toHaveBeenCalledOnce();
+ expect(clearIntervalSpy).toHaveBeenCalledWith(91);
+ expect(harness.getProgressInterval()).toBeNull();
+});
+
+it('keeps a newer benchmark authoritative over an older terminal poll', async () => {
+ vi.useFakeTimers();
+ const staleStatus = deferred();
+ const fetchMock = vi.fn(url => {
+ if (url === '/benchmark/api/status/run-a') return staleStatus.promise;
+ return new Promise(() => {});
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ initializeCharts: vi.fn(),
+ loadHistoricalChartData: vi.fn(),
+ handleDetailedProgress: vi.fn(),
+ updateProgressDisplay: vi.fn(),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ document.body.innerHTML = `
+ <section id="performance-charts-section" style="display: none"></section>
+ `;
+ window.socket = {
+ getSocketInstance: vi.fn(() => ({})),
+ subscribeToResearch: vi.fn(),
+ };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['startProgressTracking', 'updateBenchmarkProgress'],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'run-a';
+ let progressInterval = null;
+ let progressRunGeneration = 0;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ let recentResultsRequestId = 0;
+ let historicalChartRequestId = 0;
+ let searchQualityRequestId = 0;
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ `,
+ returnExpression: `({
+ startProgressTracking,
+ updateBenchmarkProgress,
+ setCurrentBenchmarkId: value => { currentBenchmarkId = value; },
+ getProgressInterval: () => progressInterval,
+ })`,
+ });
+
+ harness.startProgressTracking();
+ const staleRequest = harness.updateBenchmarkProgress();
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/status/run-a');
+
+ harness.setCurrentBenchmarkId('run-b');
+ harness.startProgressTracking();
+ const runBInterval = harness.getProgressInterval();
+ staleStatus.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 4,
+ total_examples: 4,
+ },
+ }),
+ });
+ await staleRequest;
+
+ expect(dependencies.updateProgressDisplay).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).not.toHaveBeenCalled();
+ expect(harness.getProgressInterval()).toBe(runBInterval);
+ clearInterval(runBInterval);
+ delete window.socket;
+ vi.useRealTimers();
+});
+
+it('clears prior-run results and throttle caches when a new run takes ownership', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-01T12:00:20Z'));
+ document.body.innerHTML = `
+ <section id="performance-charts-section" style="display: none"></section>
+ <div id="recent-results-container">
+ <article class="ldr-result-card">stale run A</article>
+ </div>
+ `;
+ window.socket = {};
+ const status = {
+ status: 'in_progress',
+ completed_examples: 1,
+ total_examples: 10,
+ };
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true, status }),
+ }));
+ const dependencies = {
+ initializeCharts: vi.fn(),
+ loadHistoricalChartData: vi.fn(),
+ updateProgressDisplay: vi.fn(),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'startProgressTracking',
+ 'updateBenchmarkProgress',
+ ],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'run-b';
+ let progressInterval = null;
+ let progressRunGeneration = 4;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ let recentResultsRequestId = 0;
+ let historicalChartRequestId = 0;
+ let searchQualityRequestId = 0;
+ let lastResultsUpdate = Date.now();
+ let lastChartsUpdate = Date.now();
+ let lastResultsData = [{ id: 'run-a-result' }];
+ `,
+ returnExpression: `({
+ startProgressTracking,
+ updateBenchmarkProgress,
+ getProgressInterval: () => progressInterval,
+ getLastResultsData: () => lastResultsData,
+ })`,
+ });
+
+ harness.startProgressTracking();
+
+ expect(document.getElementById('recent-results-container').textContent)
+ .toContain('No results yet');
+ expect(document.querySelector('.ldr-result-card')).toBeNull();
+ expect(harness.getLastResultsData()).toBeNull();
+
+ await harness.updateBenchmarkProgress();
+
+ expect(dependencies.updateRecentResults).toHaveBeenCalledOnce();
+ expect(dependencies.updateCharts).toHaveBeenCalledWith(status);
+ clearInterval(harness.getProgressInterval());
+});
+
+it('keeps a newer poll authoritative within the same benchmark run', async () => {
+ const olderStatus = deferred();
+ const newerStatus = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderStatus.promise)
+ .mockImplementationOnce(() => newerStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ updateProgressDisplay: vi.fn(),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateBenchmarkProgress'],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'run-overlap';
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ let progressInterval = 92;
+ let progressRunGeneration = 1;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ `,
+ returnExpression: `({
+ updateBenchmarkProgress,
+ getProgressInterval: () => progressInterval,
+ })`,
+ });
+
+ const olderRequest = harness.updateBenchmarkProgress();
+ const newerRequest = harness.updateBenchmarkProgress();
+
+ const currentStatus = {
+ status: 'in_progress',
+ completed_examples: 7,
+ total_examples: 10,
+ };
+ newerStatus.resolve({
+ json: vi.fn().mockResolvedValue({ success: true, status: currentStatus }),
+ });
+ await newerRequest;
+ expect(dependencies.updateProgressDisplay).toHaveBeenCalledWith(currentStatus);
+
+ olderStatus.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'in_progress',
+ completed_examples: 2,
+ total_examples: 10,
+ },
+ }),
+ });
+ await olderRequest;
+
+ expect(dependencies.updateProgressDisplay).toHaveBeenCalledOnce();
+ expect(dependencies.showAlert).not.toHaveBeenCalled();
+ expect(harness.getProgressInterval()).toBe(92);
+});
+
+it('accepts an older terminal snapshot after a newer nonterminal poll', async () => {
+ const terminalResponse = deferred();
+ const nonterminalResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => terminalResponse.promise)
+ .mockImplementationOnce(() => nonterminalResponse.promise));
+ const dependencies = {
+ updateProgressDisplay: vi.fn(),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateBenchmarkProgress'],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'run-terminal';
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ let progressInterval = 93;
+ let progressRunGeneration = 1;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ `,
+ returnExpression: `({
+ updateBenchmarkProgress,
+ getProgressInterval: () => progressInterval,
+ })`,
+ });
+
+ const terminalLoad = harness.updateBenchmarkProgress();
+ const nonterminalLoad = harness.updateBenchmarkProgress();
+ const runningStatus = {
+ status: 'in_progress',
+ completed_examples: 8,
+ total_examples: 10,
+ };
+ nonterminalResponse.resolve({
+ json: vi.fn().mockResolvedValue({ success: true, status: runningStatus }),
+ });
+ await nonterminalLoad;
+
+ const terminalStatus = {
+ status: 'completed',
+ completed_examples: 10,
+ total_examples: 10,
+ };
+ terminalResponse.resolve({
+ json: vi.fn().mockResolvedValue({ success: true, status: terminalStatus }),
+ });
+ await terminalLoad;
+
+ expect(dependencies.updateProgressDisplay).toHaveBeenLastCalledWith(
+ terminalStatus,
+ );
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark completed successfully!',
+ 'success',
+ );
+ expect(harness.getProgressInterval()).toBeNull();
+});
+
+it('retires the original socket owner when HTTP renders terminal state', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <section id="performance-charts-section" style="display: none"></section>
+ <div id="current-task"></div>
+ `;
+ const subscribeToResearch = vi.fn();
+ const unsubscribeFromResearch = vi.fn();
+ window.socket = {
+ getSocketInstance: vi.fn(() => ({ connected: true })),
+ subscribeToResearch,
+ unsubscribeFromResearch,
+ };
+ const status = {
+ status: 'completed',
+ completed_examples: 5,
+ total_examples: 5,
+ overall_accuracy: 80,
+ };
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true, status }),
+ }));
+ const dependencies = {
+ initializeCharts: vi.fn(),
+ loadHistoricalChartData: vi.fn(),
+ updateProgressDisplay: vi.fn(() => {
+ document.getElementById('current-task').textContent = 'completed';
+ }),
+ updateCurrentQuestion: vi.fn(),
+ updateRecentResults: vi.fn(),
+ updateCharts: vi.fn(),
+ updateSearchQualityMonitoring: vi.fn(),
+ updateRateLimitingStatus: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'handleDetailedProgress',
+ 'startProgressTracking',
+ 'updateBenchmarkProgress',
+ ],
+ dependencies,
+ preamble: `
+ let currentBenchmarkId = 'terminal-run';
+ let progressInterval = null;
+ let progressRunGeneration = 0;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ let recentResultsRequestId = 0;
+ let historicalChartRequestId = 0;
+ let searchQualityRequestId = 0;
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ `,
+ returnExpression: `({
+ startProgressTracking,
+ updateBenchmarkProgress,
+ })`,
+ });
+
+ harness.startProgressTracking();
+ await vi.advanceTimersByTimeAsync(500);
+ const socketCallback = subscribeToResearch.mock.calls[0][1];
+ socketCallback({ status: 'in_progress', message: 'grading' });
+ expect(document.getElementById('current-task').textContent).toBe('grading');
+
+ await harness.updateBenchmarkProgress();
+
+ expect(document.getElementById('current-task').textContent).toBe('completed');
+ expect(unsubscribeFromResearch).toHaveBeenCalledOnce();
+ expect(unsubscribeFromResearch).toHaveBeenCalledWith('terminal-run');
+
+ socketCallback({
+ status: 'in_progress',
+ log_entry: { message: 'late stale work' },
+ });
+ expect(document.getElementById('current-task').textContent).toBe('completed');
+});
+
+it('renders the migrated search-quality warning for SearXNG throttling', async () => {
+ document.body.innerHTML = `
+ <div id="search-status-details">Current status.</div>
+ `;
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ search_quality: [{
+ engine_type: 'SearXNGSearchEngine',
+ status: 'WARNING',
+ success_rate: 72.5,
+ }],
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['updateRateLimitingStatus'],
+ returnExpression: '({ updateRateLimitingStatus })',
+ });
+
+ await harness.updateRateLimitingStatus();
+
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/search-quality');
+ expect(document.getElementById('search-status-details').textContent)
+ .toContain('High rate-limit failures: 27.5% of requests throttled.');
+});
diff --git a/tests/js/pages/benchmark-results-runtime.test.js b/tests/js/pages/benchmark-results-runtime.test.js
new file mode 100644
index 0000000000..00deeeec71
--- /dev/null
+++ b/tests/js/pages/benchmark-results-runtime.test.js
@@ -0,0 +1,307 @@
+/** Runtime FastAPI contracts for benchmark_results.html. */
+
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark_results.html',
+);
+
+function compileHistory(dependencies) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadBenchmarkHistory'],
+ dependencies,
+ preamble: 'let benchmarkRuns = []; let filteredRuns = [];',
+ returnExpression: `({
+ loadBenchmarkHistory,
+ getRuns: () => benchmarkRuns,
+ getFilteredRuns: () => filteredRuns,
+ })`,
+ });
+}
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('loads the benchmark history success envelope into both result sets', async () => {
+ const runs = [{ id: 3299 }, { id: 3300 }];
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true, runs }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = { populateFilters: vi.fn(), displayResults: vi.fn() };
+ const harness = compileHistory(dependencies);
+
+ await harness.loadBenchmarkHistory();
+
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/history');
+ expect(harness.getRuns()).toEqual(runs);
+ expect(harness.getFilteredRuns()).toEqual(runs);
+ expect(harness.getFilteredRuns()).not.toBe(harness.getRuns());
+ expect(dependencies.populateFilters).toHaveBeenCalledOnce();
+ expect(dependencies.displayResults).toHaveBeenCalledOnce();
+});
+
+it('renders the benchmark history error envelope and network failure', async () => {
+ document.body.innerHTML = '<div id="results-container"></div>';
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ json: vi.fn().mockResolvedValue({ success: false }),
+ })
+ .mockRejectedValueOnce(new Error('offline'));
+ vi.stubGlobal('fetch', fetchMock);
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const dependencies = { populateFilters: vi.fn(), displayResults: vi.fn() };
+ const harness = compileHistory(dependencies);
+
+ await harness.loadBenchmarkHistory();
+ expect(document.getElementById('results-container').textContent)
+ .toBe('Error loading benchmark results');
+ await harness.loadBenchmarkHistory();
+
+ expect(error).toHaveBeenCalled();
+ expect(dependencies.displayResults).not.toHaveBeenCalled();
+});
+
+it('DELETEs a benchmark run with CSRF and removes the accepted run locally', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-benchmark">';
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const showAlert = vi.fn();
+ const applyFilters = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['deleteBenchmarkRun'],
+ dependencies: { showAlert, applyFilters },
+ preamble: 'let benchmarkRuns = [{ id: 3299 }, { id: 3300 }];',
+ returnExpression: `({
+ deleteBenchmarkRun,
+ getRuns: () => benchmarkRuns,
+ })`,
+ });
+
+ await harness.deleteBenchmarkRun(3299);
+
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/delete/3299', {
+ method: 'DELETE',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-benchmark',
+ },
+ });
+ expect(harness.getRuns()).toEqual([{ id: 3300 }]);
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Benchmark run deleted successfully!',
+ 'success',
+ );
+ expect(applyFilters).toHaveBeenCalledOnce();
+});
+
+it('keeps local benchmark state when the delete envelope is rejected', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-benchmark">';
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: 'run is still active',
+ }),
+ }));
+ const showAlert = vi.fn();
+ const applyFilters = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['deleteBenchmarkRun'],
+ dependencies: { showAlert, applyFilters },
+ preamble: 'let benchmarkRuns = [{ id: 3299 }];',
+ returnExpression: `({
+ deleteBenchmarkRun,
+ getRuns: () => benchmarkRuns,
+ })`,
+ });
+
+ await harness.deleteBenchmarkRun(3299);
+
+ expect(harness.getRuns()).toEqual([{ id: 3299 }]);
+ expect(applyFilters).not.toHaveBeenCalled();
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Error deleting benchmark run: run is still active',
+ 'error',
+ );
+});
+
+it('POSTs cancellation with CSRF before delegating to deletion', async () => {
+ vi.useFakeTimers();
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-cancel">';
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const showAlert = vi.fn();
+ const deleteBenchmarkRun = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['cancelAndDeleteBenchmarkRun'],
+ dependencies: { showAlert, deleteBenchmarkRun },
+ returnExpression: '({ cancelAndDeleteBenchmarkRun })',
+ });
+
+ const cancellation = harness.cancelAndDeleteBenchmarkRun(3299);
+ await vi.advanceTimersByTimeAsync(1000);
+ await cancellation;
+
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/cancel/3299', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-cancel',
+ },
+ });
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Benchmark cancelled successfully. Deleting...',
+ 'info',
+ );
+ expect(deleteBenchmarkRun).toHaveBeenCalledWith(3299);
+});
+
+it('renders a persistence error as text when detailed results cannot load', async () => {
+ document.body.innerHTML = '<div id="examples-3299"></div>';
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ persistence_error: {
+ message: '<img src=x onerror=alert(1)> write failed',
+ },
+ }),
+ }));
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadExamples'],
+ dependencies: { createExampleCard: vi.fn() },
+ returnExpression: '({ loadExamples })',
+ });
+
+ await harness.loadExamples(3299);
+
+ const container = document.getElementById('examples-3299');
+ expect(container.textContent)
+ .toBe('<img src=x onerror=alert(1)> write failed');
+ expect(container.querySelector('img')).toBeNull();
+});
+
+it('loads detailed results and renders the migrated results envelope', async () => {
+ document.body.innerHTML = '<div id="examples-3299"></div>';
+ const results = [
+ { id: 1, search_result_count: 2 },
+ { id: 2, search_result_count: 6 },
+ ];
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ success: true, results }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const createExampleCard = vi.fn(result => (
+ `<article data-result="${result.id}">Result ${result.id}</article>`
+ ));
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadExamples'],
+ dependencies: { createExampleCard },
+ returnExpression: '({ loadExamples })',
+ });
+
+ await harness.loadExamples(3299);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/benchmark/api/results/3299?limit=50',
+ );
+ const container = document.getElementById('examples-3299');
+ expect(container.textContent).toContain('Avg Search Results');
+ expect(container.textContent).toContain('4.0');
+ expect(container.querySelectorAll('[data-result]')).toHaveLength(2);
+ expect(createExampleCard).toHaveBeenCalledTimes(2);
+});
+
+it('requests settings metadata only for an opted-in benchmark export', async () => {
+ const run = {
+ id: 3299,
+ created_at: '2026-08-01T10:00:00Z',
+ start_time: '2026-08-01T10:00:00Z',
+ ldr_version: '1.10.7',
+ overall_accuracy: 75,
+ completed_examples: 4,
+ total_examples: 4,
+ avg_search_results: 3,
+ avg_processing_time: 30,
+ datasets_config: { simpleqa: { count: 4 } },
+ evaluation_config: {},
+ search_config: {
+ model_name: 'model-a',
+ provider: 'openai',
+ search_tool: 'searxng',
+ search_strategy: 'iterdrag',
+ temperature: 0.2,
+ iterations: 2,
+ questions_per_iteration: 3,
+ },
+ };
+ const settingsSnapshot = { llm: { model: 'model-a' } };
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ metadata: {
+ started_at: run.start_time,
+ ldr_version: run.ldr_version,
+ settings_snapshot: settingsSnapshot,
+ },
+ results: [],
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const createObjectURL = vi.fn(() => 'blob:benchmark-yaml');
+ const revokeObjectURL = vi.fn();
+ const URLStub = class extends window.URL {};
+ Object.defineProperties(URLStub, {
+ createObjectURL: { value: createObjectURL, configurable: true },
+ revokeObjectURL: { value: revokeObjectURL, configurable: true },
+ });
+ vi.stubGlobal('URL', URLStub);
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ const formatSettingsSnapshot = vi.fn(() => 'settings:\n redacted: true\n');
+ const showAlert = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['downloadBenchmarkYAML'],
+ dependencies: {
+ initialRuns: [run],
+ yamlEscape: value => String(value),
+ formatSettingsSnapshot,
+ formatAvgSearchResults: () => '3',
+ formatAvgProcessingTime: () => '30.0s',
+ showAlert,
+ },
+ preamble: 'let benchmarkRuns = initialRuns;',
+ returnExpression: '({ downloadBenchmarkYAML })',
+ });
+
+ await harness.downloadBenchmarkYAML(3299, false, true);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/benchmark/api/results/3299/export?include_settings=1',
+ );
+ expect(formatSettingsSnapshot).toHaveBeenCalledWith(settingsSnapshot);
+ expect(createObjectURL).toHaveBeenCalledWith(expect.any(Blob));
+ expect(revokeObjectURL).toHaveBeenCalledWith('blob:benchmark-yaml');
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Benchmark YAML downloaded successfully.',
+ 'success',
+ );
+});
diff --git a/tests/js/pages/benchmark-runtime-contracts.test.js b/tests/js/pages/benchmark-runtime-contracts.test.js
new file mode 100644
index 0000000000..75435810b2
--- /dev/null
+++ b/tests/js/pages/benchmark-runtime-contracts.test.js
@@ -0,0 +1,356 @@
+/**
+ * Runtime contracts for the full benchmark page's inline FastAPI client.
+ *
+ * This covers configuration serialization, start recovery, and reconnection
+ * using the production functions extracted from the checked-in template.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileBenchmarkClient(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'getConfigurationData',
+ 'startBenchmark',
+ 'checkForRunningBenchmark',
+ ].map(name => extractFunction(template, name)).join('\n');
+ const dependencyNames = Object.keys(dependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'csrfToken',
+ ...dependencyNames,
+ `
+ let currentBenchmarkId = null;
+ let benchmarkIntentGeneration = 0;
+ let benchmarkStartInFlight = false;
+ ${functions}
+ return {
+ getConfigurationData,
+ startBenchmark,
+ checkForRunningBenchmark,
+ getCurrentBenchmarkId: () => currentBenchmarkId,
+ };
+ `,
+ );
+ return factory(
+ 'csrf-benchmark',
+ ...Object.values(dependencies),
+ );
+}
+
+function renderBenchmarkForm() {
+ document.body.innerHTML = `
+ <form id="benchmark-form"></form>
+ <section id="benchmark-progress" style="display: none"></section>
+ <input id="run_name" value="migration sweep">
+ <input id="sampling_seed" value="17">
+ <input id="simpleqa_enabled" type="checkbox" checked>
+ <input id="simpleqa_count" value="4">
+ <input id="xbench_deepsearch_enabled" type="checkbox">
+ <input id="xbench_deepsearch_count" value="99">
+ <input id="browsecomp_enabled" type="checkbox" checked>
+ <input id="browsecomp_count" value="2">
+ `;
+}
+
+function createDependencies() {
+ return {
+ showAlert: vi.fn(),
+ startProgressTracking: vi.fn(),
+ resetForm: vi.fn(),
+ };
+}
+
+beforeEach(() => {
+ renderBenchmarkForm();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('serializes only enabled datasets and applies the shared sampling seed', () => {
+ const harness = compileBenchmarkClient(createDependencies());
+
+ expect(harness.getConfigurationData()).toEqual({
+ run_name: 'migration sweep',
+ datasets_config: {
+ simpleqa: { count: 4, seed: 17 },
+ browsecomp: { count: 2, seed: 17 },
+ },
+ });
+});
+
+it('omits the seed for a fresh random sample', () => {
+ document.getElementById('sampling_seed').value = '';
+
+ expect(compileBenchmarkClient(createDependencies()).getConfigurationData())
+ .toEqual({
+ run_name: 'migration sweep',
+ datasets_config: {
+ simpleqa: { count: 4 },
+ browsecomp: { count: 2 },
+ },
+ });
+});
+
+it('starts a run with the serialized config and tracks the returned run ID', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 3299,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ harness.startBenchmark();
+
+ await vi.waitFor(() => {
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/start', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-benchmark',
+ },
+ body: JSON.stringify({
+ run_name: 'migration sweep',
+ datasets_config: {
+ simpleqa: { count: 4, seed: 17 },
+ browsecomp: { count: 2, seed: 17 },
+ },
+ }),
+ });
+ expect(harness.getCurrentBenchmarkId()).toBe(3299);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark started successfully!',
+ 'success',
+ );
+ expect(document.getElementById('benchmark-form').style.display).toBe('none');
+ expect(document.getElementById('benchmark-progress').style.display)
+ .toBe('block');
+});
+
+it('resets the browser state after a rejected start response', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: 'benchmark worker unavailable',
+ }),
+ }));
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ harness.startBenchmark();
+
+ await vi.waitFor(() => {
+ expect(dependencies.resetForm).toHaveBeenCalledOnce();
+ });
+ expect(dependencies.startProgressTracking).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Error starting benchmark: benchmark worker unavailable',
+ 'error',
+ );
+});
+
+it('reconnects the page to the run reported by the migrated running endpoint', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'existing-12',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ harness.checkForRunningBenchmark();
+
+ await vi.waitFor(() => {
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+ });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/running');
+ expect(harness.getCurrentBenchmarkId()).toBe('existing-12');
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Reconnected to running benchmark #existing-12',
+ 'info',
+ );
+ expect(document.getElementById('benchmark-form').style.display).toBe('none');
+ expect(document.getElementById('benchmark-progress').style.display)
+ .toBe('block');
+});
+
+it('does not let a delayed running probe replace a user-started benchmark', async () => {
+ const runningProbe = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => runningProbe.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'user-run',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ harness.checkForRunningBenchmark();
+ harness.startBenchmark();
+ await vi.waitFor(() => {
+ expect(harness.getCurrentBenchmarkId()).toBe('user-run');
+ });
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+
+ runningProbe.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'stale-running-probe',
+ }),
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(harness.getCurrentBenchmarkId()).toBe('user-run');
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+ expect(dependencies.showAlert).not.toHaveBeenCalledWith(
+ 'Reconnected to running benchmark #stale-running-probe',
+ 'info',
+ );
+});
+
+it.each([
+ {
+ label: 'FastAPI error envelope',
+ response: {
+ ok: false,
+ status: 409,
+ json: vi.fn().mockResolvedValue({
+ error: 'benchmark worker unavailable',
+ }),
+ },
+ expectedError: 'Error starting benchmark: benchmark worker unavailable',
+ },
+ {
+ label: 'FastAPI detail envelope',
+ response: {
+ ok: false,
+ status: 422,
+ json: vi.fn().mockResolvedValue({
+ detail: 'dataset configuration is invalid',
+ }),
+ },
+ expectedError: 'Error starting benchmark: dataset configuration is invalid',
+ },
+ {
+ label: 'FastAPI message envelope',
+ response: {
+ ok: false,
+ status: 503,
+ json: vi.fn().mockResolvedValue({
+ message: 'benchmark queue is paused',
+ }),
+ },
+ expectedError: 'Error starting benchmark: benchmark queue is paused',
+ },
+ {
+ label: 'non-ok success-shaped response',
+ response: {
+ ok: false,
+ status: 503,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'must-not-start',
+ }),
+ },
+ expectedError: 'Error starting benchmark: HTTP 503',
+ },
+ {
+ label: 'success response without a run ID',
+ response: {
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ success: true }),
+ },
+ expectedError: 'Error starting benchmark: response did not include a benchmark run ID',
+ },
+])('rejects a $label', async ({ response, expectedError }) => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ await harness.startBenchmark();
+
+ expect(harness.getCurrentBenchmarkId()).toBeNull();
+ expect(dependencies.startProgressTracking).not.toHaveBeenCalled();
+ expect(dependencies.resetForm).toHaveBeenCalledOnce();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(expectedError, 'error');
+});
+
+it('coalesces duplicate full benchmark submissions while the POST is pending', async () => {
+ const pendingStart = deferred();
+ const fetchMock = vi.fn(() => pendingStart.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileBenchmarkClient(dependencies);
+
+ const firstStart = harness.startBenchmark();
+ const duplicateStart = harness.startBenchmark();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ await duplicateStart;
+ pendingStart.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'single-run',
+ }),
+ });
+ await firstStart;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(harness.getCurrentBenchmarkId()).toBe('single-run');
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/pages/benchmark-simple-config.test.js b/tests/js/pages/benchmark-simple-config.test.js
new file mode 100644
index 0000000000..a2a0f12d21
--- /dev/null
+++ b/tests/js/pages/benchmark-simple-config.test.js
@@ -0,0 +1,105 @@
+/**
+ * Browser contract for the simple benchmark page's settings bootstrap.
+ *
+ * The code lives inline in the Jinja template, so extract and execute the
+ * checked-in functions. This keeps the test bound to the URL and response
+ * shape that the browser actually receives after the FastAPI migration.
+ */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark_simple.html',
+);
+
+function compileConfigLoader() {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['displayConfig', 'loadCurrentConfig'],
+ dependencies: { escapeHtml: value => String(value) },
+ returnExpression: 'loadCurrentConfig',
+ });
+}
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <div id="config-display">
+ <span class="ldr-config-label">Loading...</span>
+ </div>
+ `;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('loads and renders the FastAPI bulk-settings response', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ settings: {
+ 'llm.provider': { value: 'openai_endpoint' },
+ 'llm.model': { value: 'local-model' },
+ 'search.tool': { value: 'searxng' },
+ 'search.iterations': { value: 6 },
+ },
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compileConfigLoader()();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api');
+ const values = Array.from(
+ document.querySelectorAll('.ldr-config-value'),
+ element => element.textContent,
+ );
+ expect(values).toEqual([
+ 'openai_endpoint',
+ 'local-model',
+ 'searxng',
+ '6',
+ ]);
+});
+
+it('uses browser-facing defaults when optional settings are absent', async () => {
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({ settings: {} }),
+ }));
+
+ await compileConfigLoader()();
+
+ const values = Array.from(
+ document.querySelectorAll('.ldr-config-value'),
+ element => element.textContent,
+ );
+ expect(values).toEqual([
+ 'Not configured',
+ 'Not configured',
+ 'searxng',
+ '8',
+ ]);
+});
+
+it('replaces stale configuration with a recoverable loading state on failure', async () => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(new Error('offline')));
+ document.getElementById('config-display').textContent = 'stale provider';
+
+ await compileConfigLoader()();
+
+ const values = Array.from(
+ document.querySelectorAll('.ldr-config-value'),
+ element => element.textContent,
+ );
+ expect(values).toEqual(['Loading...', 'Loading...', 'Loading...', '-']);
+ expect(console.error).toHaveBeenCalledWith(
+ 'Error loading config:',
+ expect.any(Error),
+ );
+});
diff --git a/tests/js/pages/benchmark-simple-runtime.test.js b/tests/js/pages/benchmark-simple-runtime.test.js
new file mode 100644
index 0000000000..a997485194
--- /dev/null
+++ b/tests/js/pages/benchmark-simple-runtime.test.js
@@ -0,0 +1,603 @@
+/**
+ * Runtime contracts for the simple benchmark page's inline start workflow.
+ *
+ * These tests execute the checked-in template function so the FastAPI route,
+ * CSRF header, selected-dataset payload, and recovery behavior stay aligned.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark_simple.html',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileStartBenchmark(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const startBenchmarkSource = extractFunction(template, 'startBenchmark');
+ const dependencyNames = Object.keys(dependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `
+ let currentBenchmarkId = null;
+ ${startBenchmarkSource}
+ return {
+ startBenchmark,
+ getCurrentBenchmarkId: () => currentBenchmarkId,
+ };
+ `,
+ );
+ return factory(...Object.values(dependencies));
+}
+
+function renderBenchmarkSelection() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-3299">';
+ document.body.innerHTML = `
+ <div class="ldr-dataset-option ldr-selected" data-dataset="simpleqa">
+ <input value="3">
+ </div>
+ <div class="ldr-dataset-option ldr-selected" data-dataset="browsecomp">
+ <input value="0">
+ </div>
+ <button id="start-benchmark"></button>
+ `;
+}
+
+function createDependencies() {
+ return {
+ showAlert: vi.fn(),
+ showProgress: vi.fn(),
+ startProgressTracking: vi.fn(),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolvePromiseArgument => {
+ resolvePromise = resolvePromiseArgument;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function compileProgressRuntime(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'startProgressTracking',
+ 'formatBenchmarkAccuracy',
+ 'updateProgress',
+ ]
+ .map(name => extractFunction(template, name))
+ .join('\n');
+ const dependencyNames = Object.keys(dependencies);
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `
+ let currentBenchmarkId = 'run-a';
+ let progressInterval = null;
+ let progressRunGeneration = 0;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalProgressRunGeneration = null;
+ ${functions}
+ return {
+ startProgressTracking,
+ updateProgress,
+ setCurrentBenchmarkId: value => { currentBenchmarkId = value; },
+ getCurrentBenchmarkId: () => currentBenchmarkId,
+ getProgressInterval: () => progressInterval,
+ };
+ `,
+ );
+ return factory(...Object.values(dependencies));
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('starts the selected datasets through the FastAPI simple-benchmark route', async () => {
+ renderBenchmarkSelection();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'run-3299',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileStartBenchmark(dependencies);
+
+ await harness.startBenchmark();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/start-simple', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-3299',
+ },
+ body: JSON.stringify({
+ datasets_config: { simpleqa: { count: 3 } },
+ }),
+ });
+ expect(harness.getCurrentBenchmarkId()).toBe('run-3299');
+ expect(dependencies.showProgress).toHaveBeenCalledOnce();
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark started!',
+ 'success',
+ );
+});
+
+it('does not call the backend when every selected dataset has a zero count', async () => {
+ renderBenchmarkSelection();
+ document.querySelector('[data-dataset="simpleqa"] input').value = '0';
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+
+ await compileStartBenchmark(dependencies).startBenchmark();
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Please select at least one dataset',
+ 'error',
+ );
+ expect(document.getElementById('start-benchmark').disabled).toBe(false);
+});
+
+it('reenables the start action when the backend rejects the configuration', async () => {
+ renderBenchmarkSelection();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: false,
+ error: 'dataset unavailable',
+ }),
+ }));
+ const dependencies = createDependencies();
+
+ await compileStartBenchmark(dependencies).startBenchmark();
+
+ expect(dependencies.showProgress).not.toHaveBeenCalled();
+ expect(dependencies.startProgressTracking).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Error: dataset unavailable',
+ 'error',
+ );
+ expect(document.getElementById('start-benchmark').disabled).toBe(false);
+});
+
+it.each([
+ {
+ label: 'FastAPI error envelope',
+ response: {
+ ok: false,
+ status: 409,
+ json: vi.fn().mockResolvedValue({
+ error: 'benchmark worker unavailable',
+ }),
+ },
+ expectedError: 'Failed to start benchmark: benchmark worker unavailable',
+ },
+ {
+ label: 'FastAPI detail envelope',
+ response: {
+ ok: false,
+ status: 422,
+ json: vi.fn().mockResolvedValue({
+ detail: 'dataset configuration is invalid',
+ }),
+ },
+ expectedError: 'Failed to start benchmark: dataset configuration is invalid',
+ },
+ {
+ label: 'FastAPI message envelope',
+ response: {
+ ok: false,
+ status: 503,
+ json: vi.fn().mockResolvedValue({
+ message: 'benchmark queue is paused',
+ }),
+ },
+ expectedError: 'Failed to start benchmark: benchmark queue is paused',
+ },
+ {
+ label: 'non-ok success-shaped response',
+ response: {
+ ok: false,
+ status: 503,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'must-not-start',
+ }),
+ },
+ expectedError: 'Failed to start benchmark: HTTP 503',
+ },
+ {
+ label: 'success response without a run ID',
+ response: {
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ success: true }),
+ },
+ expectedError: 'Error: response did not include a benchmark run ID',
+ },
+])('rejects a $label from the simple start endpoint', async ({
+ response,
+ expectedError,
+}) => {
+ renderBenchmarkSelection();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
+ const dependencies = createDependencies();
+ const harness = compileStartBenchmark(dependencies);
+
+ await harness.startBenchmark();
+
+ expect(harness.getCurrentBenchmarkId()).toBeNull();
+ expect(dependencies.showProgress).not.toHaveBeenCalled();
+ expect(dependencies.startProgressTracking).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(expectedError, 'error');
+ expect(document.getElementById('start-benchmark').disabled).toBe(false);
+});
+
+it('coalesces duplicate simple starts while the first POST is pending', async () => {
+ renderBenchmarkSelection();
+ const pendingStart = deferred();
+ const fetchMock = vi.fn(() => pendingStart.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const harness = compileStartBenchmark(dependencies);
+
+ const firstStart = harness.startBenchmark();
+ await harness.startBenchmark();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ pendingStart.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ benchmark_run_id: 'simple-single-run',
+ }),
+ });
+ await firstStart;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(harness.getCurrentBenchmarkId()).toBe('simple-single-run');
+ expect(dependencies.startProgressTracking).toHaveBeenCalledOnce();
+});
+
+it('ignores a terminal response from an older run after a newer run starts', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ const staleStatus = deferred();
+ const fetchMock = vi.fn(url => {
+ if (url === '/benchmark/api/status/run-a') return staleStatus.promise;
+ return new Promise(() => {});
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ const staleRequest = harness.startProgressTracking();
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/status/run-a');
+ harness.setCurrentBenchmarkId('run-b');
+ harness.startProgressTracking();
+ const runBInterval = harness.getProgressInterval();
+ expect(fetchMock).toHaveBeenCalledWith('/benchmark/api/status/run-b');
+
+ staleStatus.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 5,
+ total_examples: 5,
+ overall_accuracy: 90,
+ processing_rate: 2,
+ },
+ }),
+ });
+ await staleRequest;
+
+ expect(document.getElementById('progress-fill').style.width).toBe('0%');
+ expect(dependencies.showAlert).not.toHaveBeenCalled();
+ expect(dependencies.hideProgress).not.toHaveBeenCalled();
+ expect(harness.getProgressInterval()).toBe(runBInterval);
+ clearInterval(runBInterval);
+ vi.useRealTimers();
+});
+
+it('ignores an older same-run poll after a newer status renders', async () => {
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ const olderStatus = deferred();
+ const newerStatus = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderStatus.promise)
+ .mockImplementationOnce(() => newerStatus.promise));
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ const olderRequest = harness.startProgressTracking();
+ const newerRequest = harness.updateProgress();
+ const currentStatus = {
+ status: 'in_progress',
+ completed_examples: 6,
+ total_examples: 10,
+ overall_accuracy: 80,
+ processing_rate: 2,
+ };
+ newerStatus.resolve({
+ json: vi.fn().mockResolvedValue({ success: true, status: currentStatus }),
+ });
+ await newerRequest;
+ expect(document.getElementById('progress-fill').style.width).toBe('60%');
+
+ olderStatus.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'in_progress',
+ completed_examples: 2,
+ total_examples: 10,
+ overall_accuracy: 10,
+ processing_rate: 2,
+ },
+ }),
+ });
+ await olderRequest;
+
+ expect(document.getElementById('progress-fill').style.width).toBe('60%');
+ expect(document.getElementById('stat-accuracy').textContent).toBe('80.0%');
+ expect(dependencies.showAlert).not.toHaveBeenCalled();
+ clearInterval(harness.getProgressInterval());
+});
+
+it('accepts an older terminal snapshot after a newer nonterminal poll', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ const terminalResponse = deferred();
+ const nonterminalResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => terminalResponse.promise)
+ .mockImplementationOnce(() => nonterminalResponse.promise));
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ const terminalLoad = harness.updateProgress();
+ const nonterminalLoad = harness.updateProgress();
+ nonterminalResponse.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'in_progress',
+ completed_examples: 8,
+ total_examples: 10,
+ overall_accuracy: 80,
+ processing_rate: 2,
+ },
+ }),
+ });
+ await nonterminalLoad;
+
+ terminalResponse.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 10,
+ total_examples: 10,
+ overall_accuracy: 90,
+ processing_rate: 2,
+ },
+ }),
+ });
+ await terminalLoad;
+
+ expect(document.getElementById('progress-fill').style.width).toBe('100%');
+ expect(document.getElementById('stat-accuracy').textContent).toBe('90.0%');
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark completed! Final accuracy: 90.0%',
+ 'success',
+ );
+ vi.clearAllTimers();
+ vi.useRealTimers();
+});
+
+it('keeps the first applied terminal snapshot authoritative for a run', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ const olderTerminal = deferred();
+ const newerTerminal = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderTerminal.promise)
+ .mockImplementationOnce(() => newerTerminal.promise));
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ const olderLoad = harness.updateProgress();
+ const newerLoad = harness.updateProgress();
+ newerTerminal.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 10,
+ total_examples: 10,
+ overall_accuracy: 92,
+ processing_rate: 2,
+ },
+ }),
+ });
+ await newerLoad;
+
+ olderTerminal.resolve({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'failed',
+ completed_examples: 3,
+ total_examples: 10,
+ overall_accuracy: 20,
+ processing_rate: 1,
+ },
+ }),
+ });
+ await olderLoad;
+
+ expect(document.getElementById('progress-fill').style.width).toBe('100%');
+ expect(document.getElementById('stat-accuracy').textContent).toBe('92.0%');
+ expect(dependencies.showAlert).toHaveBeenCalledOnce();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark completed! Final accuracy: 92.0%',
+ 'success',
+ );
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(dependencies.hideProgress).toHaveBeenCalledOnce();
+});
+
+it('completes and schedules cleanup when final accuracy is unavailable', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 0,
+ total_examples: 0,
+ overall_accuracy: null,
+ processing_rate: 0,
+ },
+ }),
+ }));
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ await harness.updateProgress();
+
+ expect(document.getElementById('stat-accuracy').textContent).toBe('N/A');
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Benchmark completed! Final accuracy: N/A',
+ 'success',
+ );
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(dependencies.hideProgress).toHaveBeenCalledOnce();
+ expect(harness.getCurrentBenchmarkId()).toBeNull();
+});
+
+it('does not let an old terminal cleanup hide a replacement run', async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill" style="width: 0%"></div>
+ <span id="stat-accuracy">--%</span>
+ <span id="stat-completed">0</span>
+ <span id="stat-rate">--</span>
+ <span id="stat-remaining">--</span>
+ `;
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ status: {
+ status: 'completed',
+ completed_examples: 4,
+ total_examples: 4,
+ overall_accuracy: 75,
+ processing_rate: 2,
+ },
+ }),
+ })
+ .mockImplementation(() => new Promise(() => {}));
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ showAlert: vi.fn(),
+ hideProgress: vi.fn(),
+ };
+ const harness = compileProgressRuntime(dependencies);
+
+ await harness.updateProgress();
+ harness.setCurrentBenchmarkId('run-b');
+ harness.startProgressTracking();
+ const replacementInterval = harness.getProgressInterval();
+
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(dependencies.hideProgress).not.toHaveBeenCalled();
+ expect(harness.getCurrentBenchmarkId()).toBe('run-b');
+ expect(harness.getProgressInterval()).toBe(replacementInterval);
+ clearInterval(replacementInterval);
+});
diff --git a/tests/js/pages/benchmark-slow-polling.test.js b/tests/js/pages/benchmark-slow-polling.test.js
new file mode 100644
index 0000000000..4b6b90e623
--- /dev/null
+++ b/tests/js/pages/benchmark-slow-polling.test.js
@@ -0,0 +1,102 @@
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+async function flushPromises() {
+ for (let turn = 0; turn < 20; turn++) await Promise.resolve();
+}
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ delete window.socket;
+ document.body.replaceChildren();
+});
+
+it.each([
+ ['benchmark_simple.html', 2000, 'updateProgress'],
+ ['benchmark.html', 3000, 'updateBenchmarkProgress'],
+])('renders slow, in-order running responses in %s', async (page, interval, updateFunction) => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <div id="progress-fill"></div>
+ <span id="stat-accuracy"></span>
+ <span id="stat-completed"></span>
+ <span id="stat-rate"></span>
+ <span id="stat-remaining"></span>
+ <section id="performance-charts-section"></section>
+ `;
+ const responses = [];
+ vi.stubGlobal('fetch', vi.fn(() => new Promise(resolveResponse => {
+ responses.push(resolveResponse);
+ })));
+ let renderedCount = 0;
+ const noop = () => {};
+ const harness = compileTemplateHarness({
+ templatePath: resolve(__dirname, '../../../src/local_deep_research/web/templates/pages', page),
+ functionNames: [
+ 'startProgressTracking', updateFunction,
+ ...(page === 'benchmark_simple.html' ? ['formatBenchmarkAccuracy'] : []),
+ ],
+ dependencies: {
+ initializeCharts: noop,
+ loadHistoricalChartData: noop,
+ handleDetailedProgress: noop,
+ updateProgressDisplay: status => { renderedCount = status.completed_examples; },
+ updateCurrentQuestion: noop,
+ updateRecentResults: noop,
+ updateCharts: noop,
+ updateSearchQualityMonitoring: noop,
+ updateRateLimitingStatus: noop,
+ showAlert: noop,
+ hideProgress: noop,
+ },
+ preamble: `
+ let currentBenchmarkId = 'slow-run';
+ let progressInterval = null;
+ let progressRunGeneration = 0;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalProgressRunGeneration = null;
+ let terminalBenchmarkRunGeneration = null;
+ let hydratedTerminalBenchmarkRunGeneration = null;
+ let recentResultsRequestId = 0;
+ let historicalChartRequestId = 0;
+ let searchQualityRequestId = 0;
+ let lastResultsUpdate = 0;
+ let lastChartsUpdate = 0;
+ let lastResultsData = null;
+ `,
+ returnExpression: '({ startProgressTracking })',
+ });
+ harness.startProgressTracking();
+ if (page === 'benchmark.html') {
+ // The full page starts its first poll on the interval tick.
+ await vi.advanceTimersByTimeAsync(interval);
+ }
+ expect(responses).toHaveLength(1);
+
+ for (let completed = 1; completed <= 4; completed++) {
+ // Each response takes longer than the interval, so the next request
+ // starts first. Responses still return in request order.
+ await vi.advanceTimersByTimeAsync(interval);
+ expect(responses).toHaveLength(2);
+ responses.shift()({ json: async () => ({
+ success: true,
+ status: {
+ status: 'in_progress', completed_examples: completed,
+ total_examples: 10, overall_accuracy: 50, processing_rate: 1,
+ },
+ }) });
+ await flushPromises();
+ if (page === 'benchmark_simple.html') {
+ expect(document.getElementById('stat-completed').textContent)
+ .toBe(`${completed}/10`);
+ } else {
+ expect(renderedCount).toBe(completed);
+ }
+ }
+ vi.clearAllTimers();
+ responses.shift()({ json: async () => ({ success: false }) });
+ await flushPromises();
+});
diff --git a/tests/js/pages/benchmark-socket-lifecycle.test.js b/tests/js/pages/benchmark-socket-lifecycle.test.js
new file mode 100644
index 0000000000..4f17c142c1
--- /dev/null
+++ b/tests/js/pages/benchmark-socket-lifecycle.test.js
@@ -0,0 +1,205 @@
+/**
+ * Browser contract for the benchmark page's Socket.IO adapter.
+ *
+ * The generic socket-service tests cover room/event names. This test executes
+ * the checked-in inline page functions so the benchmark's run ID, callback
+ * rendering, and teardown cannot drift from that service unnoticed.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import {
+ compileTemplateHarness,
+ extractJavaScriptBlock,
+} from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/benchmark.html',
+);
+
+function extractDOMContentLoadedCallback(source) {
+ const marker = "document.addEventListener('DOMContentLoaded', ";
+ const listenerIndex = source.indexOf(marker);
+ if (listenerIndex === -1) {
+ throw new Error('DOMContentLoaded listener not found in template');
+ }
+
+ const functionIndex = source.indexOf('function', listenerIndex);
+ return extractJavaScriptBlock(source, functionIndex);
+}
+
+function compileDOMContentLoadedHandler(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const callback = extractDOMContentLoadedCallback(template);
+ const dependencyNames = Object.keys(dependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `return (${callback});`,
+ );
+ return factory(...Object.values(dependencies));
+}
+
+function createBenchmarkHarness(runId, dependencies) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'handleDetailedProgress',
+ 'startProgressTracking',
+ 'resetForm',
+ ],
+ dependencies: {
+ runId,
+ initializeCharts: dependencies.initializeCharts,
+ loadHistoricalChartData: dependencies.loadHistoricalChartData,
+ updateBenchmarkProgress: dependencies.updateBenchmarkProgress,
+ },
+ preamble: `
+ let currentBenchmarkId = runId;
+ let progressInterval = null;
+ let progressRunGeneration = 0;
+ let progressStatusRequestId = 0;
+ let latestAppliedProgressStatusRequestId = 0;
+ let terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0;
+ let recentResultsRequestId = 0;
+ let historicalChartRequestId = 0;
+ let searchQualityRequestId = 0;
+ let chartData = {};
+ let recentSearchCounts = [];
+ let searchQualityAlert = false;
+ let accuracyChart = null;
+ let timingChart = null;
+ let searchResultsChart = null;
+ `,
+ returnExpression: `({
+ handleDetailedProgress,
+ startProgressTracking,
+ resetForm,
+ getCurrentBenchmarkId: () => currentBenchmarkId,
+ })`,
+ });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <form id="benchmark-form" style="display: none"></form>
+ <section id="benchmark-progress"></section>
+ <section id="performance-charts-section" style="display: none"></section>
+ <div id="current-task"></div>
+ `;
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ delete window.socket;
+ delete window.modelsLoading;
+ document.body.replaceChildren();
+});
+
+it('subscribes, renders progress, and unsubscribes with the original numeric run ID', async () => {
+ const subscribeToResearch = vi.fn();
+ const unsubscribeFromResearch = vi.fn();
+ window.socket = {
+ init: vi.fn(),
+ getSocketInstance: vi.fn(() => null),
+ subscribeToResearch,
+ unsubscribeFromResearch,
+ };
+
+ const harness = createBenchmarkHarness(42, {
+ initializeCharts: vi.fn(),
+ loadHistoricalChartData: vi.fn(),
+ updateBenchmarkProgress: vi.fn(),
+ });
+
+ harness.startProgressTracking();
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(window.socket.init).toHaveBeenCalledOnce();
+ expect(subscribeToResearch).toHaveBeenCalledTimes(1);
+ expect(subscribeToResearch).toHaveBeenCalledWith(42, expect.any(Function));
+
+ const progressCallback = subscribeToResearch.mock.calls[0][1];
+ progressCallback({
+ status: 'in_progress',
+ message: 'grading',
+ log_entry: {
+ message: 'Example 7: grading',
+ metadata: { example_id: 7 },
+ },
+ });
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Example 7: grading');
+
+ harness.resetForm();
+
+ expect(unsubscribeFromResearch).toHaveBeenCalledTimes(1);
+ expect(unsubscribeFromResearch).toHaveBeenCalledWith(42);
+ expect(harness.getCurrentBenchmarkId()).toBeNull();
+});
+
+it('uses the migrated socket init API at page bootstrap and keeps initializing after a socket failure', () => {
+ const initError = new Error('transport unavailable');
+ window.socket = { init: vi.fn(() => { throw initError; }) };
+ const dependencies = {
+ initializeBenchmarkForm: vi.fn(),
+ initializeEvaluationSettings: vi.fn(),
+ loadCurrentSettings: vi.fn(),
+ updateConfigSummary: vi.fn(),
+ checkForRunningBenchmark: vi.fn(),
+ };
+ const warning = vi.spyOn(console, 'warn').mockImplementation(() => {});
+
+ compileDOMContentLoadedHandler(dependencies)();
+
+ expect(window.socket.init).toHaveBeenCalledOnce();
+ expect(warning).toHaveBeenCalledWith(
+ 'Socket initialization failed, continuing without real-time updates',
+ );
+ for (const dependency of Object.values(dependencies)) {
+ expect(dependency).toHaveBeenCalledOnce();
+ }
+});
+
+it('reuses an existing socket and keeps terminal progress authoritative', async () => {
+ const subscribeToResearch = vi.fn();
+ window.socket = {
+ init: vi.fn(),
+ getSocketInstance: vi.fn(() => ({ connected: true })),
+ subscribeToResearch,
+ unsubscribeFromResearch: vi.fn(),
+ };
+ const harness = createBenchmarkHarness('run-9', {
+ initializeCharts: vi.fn(),
+ loadHistoricalChartData: vi.fn(),
+ updateBenchmarkProgress: vi.fn(),
+ });
+
+ harness.startProgressTracking();
+ await vi.advanceTimersByTimeAsync(500);
+
+ expect(window.socket.init).not.toHaveBeenCalled();
+ const progressCallback = subscribeToResearch.mock.calls[0][1];
+ progressCallback({ message: 'Scoring answer' });
+ expect(document.getElementById('current-task').textContent)
+ .toBe('Scoring answer');
+
+ progressCallback({ status: 'completed' });
+ expect(document.getElementById('current-task').textContent)
+ .toBe('completed');
+
+ progressCallback({
+ status: 'ignored status',
+ message: 'ignored message',
+ log_entry: { message: 'Preferred structured log' },
+ });
+ expect(document.getElementById('current-task').textContent)
+ .toBe('completed');
+});
diff --git a/tests/js/pages/download-all-endpoint-runtime.test.js b/tests/js/pages/download-all-endpoint-runtime.test.js
new file mode 100644
index 0000000000..34377eba20
--- /dev/null
+++ b/tests/js/pages/download-all-endpoint-runtime.test.js
@@ -0,0 +1,676 @@
+/**
+ * Endpoint-level browser contracts for the two inline "download all" clients.
+ * These execute functions extracted from the checked-in Jinja templates.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_DIR = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages',
+);
+const DOWNLOAD_MANAGER_TEMPLATE = resolve(TEMPLATE_DIR, 'download_manager.html');
+const LIBRARY_TEMPLATE = resolve(TEMPLATE_DIR, 'library.html');
+const SSE_UTIL_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/utils/sse-completion.js',
+);
+const QUEUE_URL = '/library/api/queue-all-undownloaded';
+const BULK_URL = '/library/api/download-bulk';
+
+function jsonResponse(payload, { ok = true, status = 200 } = {}) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function loadSSEParser() {
+ const source = readFileSync(SSE_UTIL_PATH, 'utf8');
+ // Repository-owned production utility only; no user-controlled input.
+ return new Function( // eslint-disable-line no-new-func
+ `${source}\nreturn createSSEJsonParser;`,
+ )();
+}
+
+function streamResponse(...events) {
+ const encoded = new globalThis.TextEncoder().encode(events.map(event => (
+ `data: ${JSON.stringify(event)}\n`
+ )).join(''));
+ const read = vi.fn()
+ .mockResolvedValueOnce({ done: false, value: encoded })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ };
+}
+
+function pausableStreamResponse(event, terminalEvent) {
+ let markPaused;
+ let finishStream;
+ const paused = new Promise(resolvePromise => {
+ markPaused = resolvePromise;
+ });
+ const finished = new Promise(resolvePromise => {
+ finishStream = resolvePromise;
+ });
+ const encoded = new globalThis.TextEncoder().encode(
+ `data: ${JSON.stringify(event)}\n`,
+ );
+ const read = vi.fn()
+ .mockResolvedValueOnce({ done: false, value: encoded })
+ .mockImplementationOnce(() => {
+ markPaused();
+ return finished;
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ response: {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ },
+ paused,
+ finish: () => finishStream(terminalEvent ? {
+ done: false,
+ value: new globalThis.TextEncoder().encode(
+ `data: ${JSON.stringify(terminalEvent)}\n`,
+ ),
+ } : { done: true, value: undefined }),
+ };
+}
+
+function emptyStreamResponse() {
+ const read = vi.fn().mockResolvedValue({
+ done: true,
+ value: undefined,
+ });
+ return {
+ response: {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ },
+ read,
+ };
+}
+
+function compileManagerLoadCollections() {
+ return compileTemplateHarness({
+ templatePath: DOWNLOAD_MANAGER_TEMPLATE,
+ functionNames: ['loadCollections'],
+ returnExpression: 'loadCollections',
+ });
+}
+
+function compileManagerDownloadAll({ button, handleSSECompletion }) {
+ return compileTemplateHarness({
+ templatePath: DOWNLOAD_MANAGER_TEMPLATE,
+ functionNames: [
+ 'resetStatusCounts',
+ 'recordStatus',
+ 'updateProgress',
+ 'startBulkDownload',
+ 'downloadAllNew',
+ ],
+ dependencies: {
+ event: { target: button },
+ createSSEJsonParser: loadSSEParser(),
+ handleSSECompletion,
+ },
+ preamble: `
+ let statusCounts = { succeeded: 0, skipped: 0, failed: 0 };
+ let currentDownloadController = null;
+ let currentDownloadRunId = 0;
+ `,
+ returnExpression: `({
+ startBulkDownload,
+ downloadAllNew,
+ getCurrentDownloadController: () => currentDownloadController,
+ })`,
+ });
+}
+
+function compileLibraryDownloadAll({
+ button,
+ handleSSECompletion,
+ showDownloadProgressModal,
+ updateDownloadProgress,
+}) {
+ return compileTemplateHarness({
+ templatePath: LIBRARY_TEMPLATE,
+ functionNames: ['resetDownloadProgress', 'downloadAllNew'],
+ dependencies: {
+ event: { target: button },
+ createSSEJsonParser: loadSSEParser(),
+ handleSSECompletion,
+ showDownloadProgressModal,
+ updateDownloadProgress,
+ },
+ preamble: `
+ let currentDownloadController = null;
+ let currentDownloadRunId = 0;
+ `,
+ returnExpression: `({
+ downloadAllNew,
+ getCurrentDownloadController: () => currentDownloadController,
+ })`,
+ });
+}
+
+function mountManagerDownloadUi() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-download-all">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all</span></button>
+ <div id="download-progress-modal" style="display: none"><h2></h2></div>
+ <div class="ldr-status-breakdown" style="display: none"></div>
+ <span id="succeeded-count">8</span>
+ <span id="skipped-count">8</span>
+ <span id="failed-count">8</span>
+ <div id="overall-progress" style="width: 20%"></div>
+ <span id="current-count">8</span>
+ <span id="total-count">8</span>
+ <div id="download-log">old log</div>
+ `;
+ return document.getElementById('download-all');
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.escapeHtml;
+ delete window.createSSEJsonParser;
+ delete window.handleSSECompletion;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('loads collection options from the list envelope and keeps names inert', async () => {
+ document.body.innerHTML = `
+ <select id="target-collection"><option>Loading…</option></select>
+ `;
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
+ success: true,
+ collections: [
+ { id: 'collection-library', name: 'Library' },
+ { id: 'collection-unsafe', name: '<img src=x onerror=alert(1)>' },
+ ],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compileManagerLoadCollections()();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/library/api/collections/list');
+ const options = [...document.querySelectorAll('#target-collection option')];
+ expect(options.map(option => ({
+ value: option.value,
+ text: option.textContent,
+ selected: option.selected,
+ }))).toEqual([
+ {
+ value: 'collection-library',
+ text: 'Library',
+ selected: true,
+ },
+ {
+ value: 'collection-unsafe',
+ text: '<img src=x onerror=alert(1)>',
+ selected: false,
+ },
+ ]);
+ expect(document.querySelector('#target-collection img')).toBeNull();
+});
+
+it('queues then streams manager downloads while retaining single-run ownership', async () => {
+ const button = mountManagerDownloadUi();
+ window.escapeHtml = vi.fn(value => String(value));
+ vi.stubGlobal('alert', vi.fn());
+ const stream = pausableStreamResponse({
+ progress: 50,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'paper.pdf',
+ }, {
+ complete: true,
+ progress: 100,
+ current: 2,
+ total: 2,
+ status: 'complete',
+ });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 2,
+ research_ids: ['research-1', 'research-2'],
+ }))
+ .mockResolvedValueOnce(stream.response)
+ .mockRejectedValue(new Error('duplicate run should not fetch'));
+ vi.stubGlobal('fetch', fetchMock);
+ const handleSSECompletion = vi.fn(() => false);
+ const runtime = compileManagerDownloadAll({ button, handleSSECompletion });
+
+ const activeRun = runtime.downloadAllNew();
+ await stream.paused;
+
+ expect(button.disabled).toBe(true);
+ expect(runtime.getCurrentDownloadController()).toBeInstanceOf(AbortController);
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ QUEUE_URL,
+ BULK_URL,
+ ]);
+ expect(fetchMock.mock.calls[0][1]).toMatchObject({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-download-all',
+ },
+ });
+ expect(fetchMock.mock.calls[0][1].signal)
+ .toBeInstanceOf(globalThis.AbortSignal);
+ expect(fetchMock.mock.calls[1][1]).toMatchObject({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-download-all',
+ },
+ body: JSON.stringify({
+ research_ids: ['research-1', 'research-2'],
+ }),
+ });
+ expect(fetchMock.mock.calls[1][1].signal)
+ .toBeInstanceOf(globalThis.AbortSignal);
+ expect(document.getElementById('download-progress-modal').style.display)
+ .toBe('block');
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Downloading ALL PDFs');
+ expect(document.getElementById('overall-progress').style.width).toBe('50%');
+ expect(document.getElementById('succeeded-count').textContent).toBe('1');
+ expect(handleSSECompletion).toHaveBeenCalledWith(
+ expect.objectContaining({ file: 'paper.pdf', status: 'success' }),
+ expect.any(Function),
+ expect.any(Function),
+ );
+
+ await runtime.downloadAllNew();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ stream.finish();
+ await activeRun;
+
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Download all');
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('does not let an older queue response reclaim a newer manager run', async () => {
+ const button = mountManagerDownloadUi();
+ window.escapeHtml = vi.fn(value => String(value));
+ vi.stubGlobal('alert', vi.fn());
+ const pendingQueue = deferred();
+ const newerStream = pausableStreamResponse({
+ progress: 40,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'new-owner.pdf',
+ }, {
+ complete: true,
+ progress: 100,
+ current: 2,
+ total: 2,
+ status: 'complete',
+ });
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => pendingQueue.promise)
+ .mockResolvedValueOnce(newerStream.response);
+ vi.stubGlobal('fetch', fetchMock);
+ const handleSSECompletion = vi.fn(() => false);
+ const runtime = compileManagerDownloadAll({ button, handleSSECompletion });
+
+ const olderQueueRun = runtime.downloadAllNew();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ const olderQueueSignal = fetchMock.mock.calls[0][1].signal;
+
+ const newerRun = runtime.startBulkDownload(['new-owner'], 'pdf');
+ await newerStream.paused;
+ const newerSignal = fetchMock.mock.calls[1][1].signal;
+
+ pendingQueue.resolve(jsonResponse({
+ queued: 1,
+ research_ids: ['stale-queued'],
+ }));
+ await olderQueueRun;
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(olderQueueSignal.aborted).toBe(true);
+ expect(newerSignal.aborted).toBe(false);
+ expect(runtime.getCurrentDownloadController()?.signal).toBe(newerSignal);
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Downloading PDFs');
+ expect(document.getElementById('download-log').textContent)
+ .toContain('new-owner.pdf');
+ expect(document.getElementById('download-log').textContent)
+ .not.toContain('stale-queued');
+
+ newerStream.finish();
+ await newerRun;
+});
+
+it('aborts an active manager stream before a download-all queue takes ownership', async () => {
+ const button = mountManagerDownloadUi();
+ const olderResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 0,
+ research_ids: [],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('alert', vi.fn());
+ const runtime = compileManagerDownloadAll({
+ button,
+ handleSSECompletion: vi.fn(),
+ });
+
+ const olderRun = runtime.startBulkDownload(['older-manager-run'], 'pdf');
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ const olderSignal = fetchMock.mock.calls[0][1].signal;
+
+ await runtime.downloadAllNew();
+
+ expect(olderSignal.aborted).toBe(true);
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ BULK_URL,
+ QUEUE_URL,
+ ]);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+
+ olderResponse.resolve(jsonResponse({}));
+ await olderRun;
+});
+
+it('restores the manager action when queueing is rejected', async () => {
+ const button = mountManagerDownloadUi();
+ const originalHtml = button.innerHTML;
+ const alertMock = vi.fn();
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ vi.stubGlobal('alert', alertMock);
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({}, {
+ ok: false,
+ status: 503,
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileManagerDownloadAll({
+ button,
+ handleSSECompletion: vi.fn(),
+ });
+
+ await runtime.downloadAllNew();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock.mock.calls[0][0]).toBe(QUEUE_URL);
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start downloads:',
+ expect.objectContaining({ message: 'HTTP error! status: 503' }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(button.innerHTML).toBe(originalHtml);
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('restores the manager action when the second-stage bulk request is rejected', async () => {
+ const button = mountManagerDownloadUi();
+ const originalHtml = button.innerHTML;
+ const getReader = vi.fn();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 1,
+ research_ids: ['manager-bulk-failure'],
+ }))
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 502,
+ body: { getReader },
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const runtime = compileManagerDownloadAll({ button, handleSSECompletion });
+
+ await runtime.downloadAllNew();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ QUEUE_URL,
+ BULK_URL,
+ ]);
+ expect(getReader).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start downloads:',
+ expect.objectContaining({ message: 'HTTP error! status: 502' }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(button.innerHTML).toBe(originalHtml);
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('reports an empty manager download-all stream and restores its action', async () => {
+ const button = mountManagerDownloadUi();
+ const originalHtml = button.innerHTML;
+ const emptyStream = emptyStreamResponse();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 1,
+ research_ids: ['manager-empty-stream'],
+ }))
+ .mockResolvedValueOnce(emptyStream.response);
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const runtime = compileManagerDownloadAll({ button, handleSSECompletion });
+
+ await runtime.downloadAllNew();
+
+ expect(emptyStream.read).toHaveBeenCalledOnce();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start downloads:',
+ expect.objectContaining({
+ message: 'Download stream ended before completion',
+ }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(button.innerHTML).toBe(originalHtml);
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('uses the library page modal and progress consumer for the same queue handshake', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-library-all">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all new</span></button>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('download-all');
+ const event = {
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ complete: true,
+ };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 1,
+ research_ids: ['library-research'],
+ }))
+ .mockResolvedValueOnce(streamResponse(event));
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('alert', vi.fn());
+ const showDownloadProgressModal = vi.fn();
+ const updateDownloadProgress = vi.fn();
+ const handleSSECompletion = vi.fn(data => data.complete);
+ const runtime = compileLibraryDownloadAll({
+ button,
+ handleSSECompletion,
+ showDownloadProgressModal,
+ updateDownloadProgress,
+ });
+
+ await runtime.downloadAllNew();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ QUEUE_URL,
+ BULK_URL,
+ ]);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({
+ research_ids: ['library-research'],
+ });
+ expect(fetchMock.mock.calls[1][1].headers['X-CSRFToken'])
+ .toBe('csrf-library-all');
+ expect(showDownloadProgressModal).toHaveBeenCalledOnce();
+ expect(updateDownloadProgress).toHaveBeenCalledWith(event);
+ expect(handleSSECompletion).toHaveBeenCalledWith(
+ event,
+ expect.any(Function),
+ expect.any(Function),
+ );
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('restores the library action when the second-stage bulk request is rejected', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-library-all">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all new</span></button>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('download-all');
+ const originalHtml = button.innerHTML;
+ const getReader = vi.fn();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 1,
+ research_ids: ['library-bulk-failure'],
+ }))
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ body: { getReader },
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const updateDownloadProgress = vi.fn();
+ const runtime = compileLibraryDownloadAll({
+ button,
+ handleSSECompletion,
+ showDownloadProgressModal: vi.fn(),
+ updateDownloadProgress,
+ });
+
+ await runtime.downloadAllNew();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ QUEUE_URL,
+ BULK_URL,
+ ]);
+ expect(getReader).not.toHaveBeenCalled();
+ expect(updateDownloadProgress).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start downloads:',
+ expect.objectContaining({ message: 'HTTP error! status: 503' }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(button.innerHTML).toBe(originalHtml);
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
+
+it('reports an empty library download-all stream and restores its action', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-library-all">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all new</span></button>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('download-all');
+ const originalHtml = button.innerHTML;
+ const emptyStream = emptyStreamResponse();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ queued: 1,
+ research_ids: ['library-empty-stream'],
+ }))
+ .mockResolvedValueOnce(emptyStream.response);
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const updateDownloadProgress = vi.fn();
+ const runtime = compileLibraryDownloadAll({
+ button,
+ handleSSECompletion,
+ showDownloadProgressModal: vi.fn(),
+ updateDownloadProgress,
+ });
+
+ await runtime.downloadAllNew();
+
+ expect(emptyStream.read).toHaveBeenCalledOnce();
+ expect(updateDownloadProgress).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start downloads:',
+ expect.objectContaining({
+ message: 'Download stream ended before completion',
+ }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(button.innerHTML).toBe(originalHtml);
+ expect(button.disabled).toBe(false);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+});
diff --git a/tests/js/pages/download-completion-cancellation.test.js b/tests/js/pages/download-completion-cancellation.test.js
new file mode 100644
index 0000000000..92dffa002a
--- /dev/null
+++ b/tests/js/pages/download-completion-cancellation.test.js
@@ -0,0 +1,45 @@
+/** A late Cancel click must preserve an already scheduled SSE completion. */
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+import '@js/utils/sse-completion.js';
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ document.body.innerHTML = '<div id="download-progress-modal" style="display: block"></div>';
+ vi.stubGlobal('alert', vi.fn());
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ delete window.closeProgressModal;
+ document.body.replaceChildren();
+});
+
+it.each(['library', 'download_manager'])(
+ 'keeps the %s completion callback live after a late Cancel click',
+ async page => {
+ const runtime = compileTemplateHarness({
+ templatePath: resolve(
+ __dirname,
+ `../../../src/local_deep_research/web/templates/pages/${page}.html`,
+ ),
+ functionNames: ['cancelDownloads', 'closeProgressModal'],
+ preamble: 'let currentDownloadController = null; let currentDownloadRunId = 1;',
+ returnExpression: '{ cancelDownloads, closeProgressModal, isCurrent: () => currentDownloadRunId === 1 }',
+ });
+ window.closeProgressModal = runtime.closeProgressModal;
+ const onSuccess = vi.fn();
+ window.handleSSECompletion({ complete: true }, onSuccess, runtime.isCurrent);
+
+ runtime.cancelDownloads();
+ expect(document.getElementById('download-progress-modal').style.display).toBe('none');
+ expect(onSuccess).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(onSuccess).toHaveBeenCalledOnce();
+ expect(document.getElementById('download-progress-modal').style.display).toBe('none');
+ expect(vi.getTimerCount()).toBe(0);
+ },
+);
diff --git a/tests/js/pages/download-manager-inline-runtime.test.js b/tests/js/pages/download-manager-inline-runtime.test.js
new file mode 100644
index 0000000000..dc2f253985
--- /dev/null
+++ b/tests/js/pages/download-manager-inline-runtime.test.js
@@ -0,0 +1,484 @@
+/**
+ * Runtime contracts for the download manager's inline bulk-download client.
+ *
+ * The functions are executed from the checked-in Jinja template so route,
+ * payload, CSRF, streaming, status aggregation, and abort behavior cannot
+ * silently drift during the FastAPI migration.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/download_manager.html',
+);
+const SSE_UTIL_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/utils/sse-completion.js',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileBulkDownload(handleSSECompletion) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'resetStatusCounts',
+ 'recordStatus',
+ 'updateProgress',
+ 'updateTextExtractionProgress',
+ 'startBulkDownload',
+ 'downloadAllAsText',
+ 'closeProgressModal',
+ 'cancelDownloads',
+ ].map(name => extractFunction(template, name)).join('\n');
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'handleSSECompletion',
+ 'createSSEJsonParser',
+ `
+ let statusCounts = {succeeded: 0, skipped: 0, failed: 0};
+ let currentDownloadController = null;
+ let currentDownloadRunId = 0;
+ ${functions}
+ return {
+ startBulkDownload,
+ downloadAllAsText,
+ cancelDownloads,
+ getCurrentDownloadController: () => currentDownloadController,
+ };
+ `,
+ );
+ const utilitySource = readFileSync(SSE_UTIL_PATH, 'utf8');
+ const loadParser = new Function( // eslint-disable-line no-new-func
+ `${utilitySource}\nreturn createSSEJsonParser;`,
+ );
+ return factory(handleSSECompletion, loadParser());
+}
+
+function renderDownloadProgress() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-download">';
+ document.body.innerHTML = `
+ <select id="target-collection">
+ <option value="collection-7" selected>Migration docs</option>
+ </select>
+ <button id="extract-all-text"><span>Extract all text</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div class="ldr-status-breakdown" style="display: none"></div>
+ <span id="succeeded-count">9</span>
+ <span id="skipped-count">9</span>
+ <span id="failed-count">9</span>
+ <div id="overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="download-log"></div>
+ `;
+}
+
+function streamingChunks(...chunks) {
+ const reads = chunks.map(chunk => ({
+ done: false,
+ value: new globalThis.TextEncoder().encode(chunk),
+ }));
+ const read = vi.fn();
+ for (const result of reads) read.mockResolvedValueOnce(result);
+ read.mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ };
+}
+
+function streamingResponse(...payloads) {
+ const chunk = payloads.map(payload => (
+ `data: ${JSON.stringify(payload)}\n`
+ )).join('');
+ return streamingChunks(chunk);
+}
+
+function pausableStreamResponse(event) {
+ let finishStream;
+ const pausedRead = new Promise(resolvePromise => {
+ finishStream = resolvePromise;
+ });
+ const read = vi.fn()
+ .mockImplementationOnce(() => pausedRead)
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ response: {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ },
+ finish: () => finishStream({
+ done: false,
+ value: new globalThis.TextEncoder().encode(
+ `data: ${JSON.stringify(event)}\n`,
+ ),
+ }),
+ finishEOF: () => finishStream({
+ done: true,
+ value: undefined,
+ }),
+ };
+}
+
+beforeEach(() => {
+ renderDownloadProgress();
+ window.escapeHtml = vi.fn(value => String(value));
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.escapeHtml;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('posts the selected collection and renders streamed success/skip/failure totals', async () => {
+ const events = [
+ { progress: 25, current: 1, total: 4, status: 'success', file: 'one.pdf' },
+ { progress: 50, current: 2, total: 4, status: 'skipped', file: 'two.pdf', error: 'already stored' },
+ { progress: 75, current: 3, total: 4, status: 'failed', file: 'three.pdf', error: 'timeout' },
+ {
+ complete: true,
+ progress: 100,
+ current: 4,
+ total: 4,
+ status: 'complete',
+ },
+ ];
+ const fetchMock = vi.fn().mockResolvedValue(streamingResponse(...events));
+ vi.stubGlobal('fetch', fetchMock);
+ const handleSSECompletion = vi.fn(data => data.status === 'complete');
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ await harness.startBulkDownload(['research-1', 'research-2'], 'pdf');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/library/api/download-bulk');
+ expect(options).toMatchObject({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-download',
+ },
+ body: JSON.stringify({
+ research_ids: ['research-1', 'research-2'],
+ mode: 'pdf',
+ collection_id: 'collection-7',
+ }),
+ });
+ expect(options.signal).toBeInstanceOf(globalThis.AbortSignal);
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Downloading PDFs');
+ expect(document.getElementById('overall-progress').style.width).toBe('100%');
+ expect(document.getElementById('current-count').textContent).toBe('4');
+ expect(document.getElementById('total-count').textContent).toBe('4');
+ expect(document.getElementById('succeeded-count').textContent).toBe('1');
+ expect(document.getElementById('skipped-count').textContent).toBe('1');
+ expect(document.getElementById('failed-count').textContent).toBe('1');
+ expect(document.querySelector('.ldr-status-breakdown').style.display).toBe('');
+ expect(document.querySelectorAll('#download-log .ldr-download-entry'))
+ .toHaveLength(3);
+ expect(handleSSECompletion).toHaveBeenCalledTimes(4);
+ expect(harness.getCurrentDownloadController()).toBeNull();
+});
+
+it('omits an empty collection and selects the text-only progress title', async () => {
+ document.getElementById('target-collection').value = '';
+ const fetchMock = vi.fn().mockResolvedValue(streamingResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'complete',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compileBulkDownload(vi.fn(() => true))
+ .startBulkDownload(['research-3'], 'text_only');
+
+ const requestBody = JSON.parse(fetchMock.mock.calls[0][1].body);
+ expect(requestBody).toEqual({
+ research_ids: ['research-3'],
+ mode: 'text_only',
+ });
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Extracting Text to Database');
+});
+
+it('processes split progress once and reports EOF without a terminal frame', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(streamingChunks(
+ 'data: {"progress":50,"current":1,"total":2,"status":"suc',
+ 'cess","file":"split.pdf"}\n',
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn(() => false);
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ await harness.startBulkDownload(['research-split'], 'pdf');
+
+ expect(document.querySelectorAll('#download-log .ldr-download-entry'))
+ .toHaveLength(1);
+ expect(document.getElementById('succeeded-count').textContent).toBe('1');
+ expect(handleSSECompletion).toHaveBeenCalledOnce();
+ expect(handleSSECompletion.mock.calls[0][0]).toEqual({
+ progress: 50,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'split.pdf',
+ });
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Download error:',
+ expect.objectContaining({
+ message: 'Download stream ended before completion',
+ }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(harness.getCurrentDownloadController()).toBeNull();
+});
+
+it('surfaces a non-ok bulk response instead of consuming its JSON as SSE', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ detail: 'CSRF token rejected',
+ }), {
+ status: 403,
+ headers: { 'Content-Type': 'application/json' },
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ await harness.startBulkDownload(['research-forbidden'], 'pdf');
+
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Download error:',
+ expect.objectContaining({ message: 'HTTP error! status: 403' }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start downloads. Please try again.',
+ );
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(harness.getCurrentDownloadController()).toBeNull();
+});
+
+it('keeps cancellation bound to a newer text run after an older PDF completes', async () => {
+ const olderPdf = pausableStreamResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ file: 'stale-old.pdf',
+ });
+ const newerText = pausableStreamResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ file: 'cancelled-late.txt',
+ });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(olderPdf.response)
+ .mockResolvedValueOnce(newerText.response);
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const handleSSECompletion = vi.fn(data => data.complete === true);
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ const olderRun = harness.startBulkDownload(['research-pdf'], 'pdf');
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+ const olderSignal = fetchMock.mock.calls[0][1].signal;
+
+ const textButton = document.getElementById('extract-all-text');
+ vi.stubGlobal('event', { target: textButton.querySelector('span') });
+ const newerRun = harness.downloadAllAsText();
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ const newerSignal = fetchMock.mock.calls[1][1].signal;
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Text Extraction to Database');
+ expect(document.getElementById('overall-progress').style.width).toBe('0%');
+
+ olderPdf.finish();
+ await olderRun;
+
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(document.getElementById('overall-progress').style.width).toBe('0%');
+ expect(document.getElementById('download-log').textContent)
+ .not.toContain('stale-old.pdf');
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Text Extraction to Database');
+ expect(olderSignal.aborted).toBe(true);
+ expect(newerSignal.aborted).toBe(false);
+ expect(harness.getCurrentDownloadController()?.signal).toBe(newerSignal);
+
+ const timeoutMock = vi.fn();
+ vi.stubGlobal('setTimeout', timeoutMock);
+ document.getElementById('download-progress-modal').style.display = 'block';
+ harness.cancelDownloads();
+
+ expect(olderSignal.aborted).toBe(true);
+ expect(newerSignal.aborted).toBe(true);
+ expect(harness.getCurrentDownloadController()).toBeNull();
+ expect(timeoutMock).toHaveBeenCalledOnce();
+
+ const cancelledProgress = document.getElementById('overall-progress');
+ expect(cancelledProgress.classList.contains('ldr-cancelled')).toBe(true);
+ cancelledProgress.style.width = '75%';
+ document.getElementById('current-count').textContent = '3';
+ document.getElementById('total-count').textContent = '4';
+
+ const replacementPdf = pausableStreamResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ file: 'replacement.pdf',
+ });
+ fetchMock.mockResolvedValueOnce(replacementPdf.response);
+ const replacementRun = harness.startBulkDownload(['replacement'], 'pdf');
+
+ expect(cancelledProgress.classList.contains('ldr-cancelled')).toBe(false);
+ expect(cancelledProgress.style.width).toBe('0%');
+ expect(document.getElementById('current-count').textContent).toBe('0');
+ expect(document.getElementById('total-count').textContent).toBe('0');
+ expect(document.getElementById('download-log').textContent).toBe('');
+ timeoutMock.mock.calls[0][0]();
+ expect(document.getElementById('download-progress-modal').style.display)
+ .toBe('block');
+
+ newerText.finishEOF();
+ await newerRun;
+
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(alertMock).not.toHaveBeenCalled();
+ expect(document.getElementById('download-log').textContent)
+ .not.toContain('cancelled-late.txt');
+
+ replacementPdf.finish();
+ await replacementRun;
+});
+
+it('streams the dedicated text-extraction endpoint across SSE chunks', async () => {
+ const button = document.getElementById('extract-all-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ const fetchMock = vi.fn().mockResolvedValue(streamingChunks(
+ 'data: {"progress":50,"current":1,"total":2,"status":"suc',
+ 'cess","file":"split.txt"}\n',
+ 'data: {"complete":true,"progress":100,"current":2,"total":2,"status":"complete"}\n',
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const handleSSECompletion = vi.fn(data => data.complete === true);
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ await harness.downloadAllAsText();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/download-all-text',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-download',
+ },
+ body: JSON.stringify({}),
+ signal: expect.any(globalThis.AbortSignal),
+ },
+ );
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Text Extraction to Database');
+ expect(document.getElementById('overall-progress').style.width).toBe('100%');
+ expect(document.getElementById('succeeded-count').textContent).toBe('1');
+ expect(document.querySelectorAll('#download-log .ldr-download-entry'))
+ .toHaveLength(1);
+ expect(handleSSECompletion).toHaveBeenCalledTimes(2);
+ expect(handleSSECompletion.mock.calls[0][0]).toEqual({
+ progress: 50,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'split.txt',
+ });
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Extract all text');
+ expect(harness.getCurrentDownloadController()).toBeNull();
+});
+
+it('reports an empty text-extraction stream and restores its action', async () => {
+ const button = document.getElementById('extract-all-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(streamingChunks()));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const handleSSECompletion = vi.fn();
+ const harness = compileBulkDownload(handleSSECompletion);
+
+ await harness.downloadAllAsText();
+
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start text extraction:',
+ expect.objectContaining({
+ message: 'Text extraction stream ended before completion',
+ }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start text extraction. Please try again.',
+ );
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Extract all text');
+ expect(harness.getCurrentDownloadController()).toBeNull();
+});
+
+it('turns an aborted stream into a visible cancellation entry', async () => {
+ const abortError = new Error('cancelled');
+ abortError.name = 'AbortError';
+ vi.stubGlobal('fetch', vi.fn().mockRejectedValue(abortError));
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ await compileBulkDownload(vi.fn()).startBulkDownload(['research-4']);
+
+ expect(log).toHaveBeenCalledWith('Download cancelled by user');
+ const entry = document.querySelector('#download-log .ldr-cancelled');
+ expect(entry).not.toBeNull();
+ expect(entry.textContent).toContain('Download cancelled by user');
+});
diff --git a/tests/js/pages/journal-quality-download-runtime.test.js b/tests/js/pages/journal-quality-download-runtime.test.js
new file mode 100644
index 0000000000..02dc19ec2e
--- /dev/null
+++ b/tests/js/pages/journal-quality-download-runtime.test.js
@@ -0,0 +1,507 @@
+/**
+ * Runtime contract for the journal-data download action embedded in the
+ * dashboard template. This executes the checked-in handler so its FastAPI
+ * request and the real progress element IDs stay in sync.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/journal_quality.html',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function extractAsyncListener(source, target, eventName) {
+ const signature = `${target}.addEventListener('${eventName}', async () => {`;
+ const start = source.indexOf(signature);
+ if (start === -1) {
+ throw new Error(`${target} ${eventName} listener not found`);
+ }
+
+ const openBrace = source.indexOf('{', start + signature.length - 1);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) {
+ const registrationEnd = source.indexOf(');', index);
+ return source.slice(start, registrationEnd + 2);
+ }
+ }
+ }
+
+ throw new Error(`${target} ${eventName} listener is unterminated`);
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(settle => {
+ resolvePromise = settle;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function loadDownloadHandler({ renderProgress, pollDownloadProgress }) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const source = extractFunction(template, 'downloadJournalData');
+ // Repository-owned production source only; no user-controlled input.
+ return new Function( // eslint-disable-line no-new-func
+ '_renderProgress',
+ '_pollDownloadProgress',
+ `
+ let _ldrProgressTimer = null;
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ ${source}
+ return downloadJournalData;
+ `,
+ )(renderProgress, pollDownloadProgress);
+}
+
+function loadDownloadRuntime(renderProgress) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const pollSource = extractFunction(template, '_pollDownloadProgress');
+ const downloadSource = extractFunction(template, 'downloadJournalData');
+ // Repository-owned production source only; no user-controlled input.
+ return new Function( // eslint-disable-line no-new-func
+ '_renderProgress', `
+ let _ldrProgressTimer = null;
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ ${pollSource}
+ ${downloadSource}
+ return {
+ pollDownloadProgress: _pollDownloadProgress,
+ downloadJournalData,
+ };
+ `,
+ )(renderProgress);
+}
+
+function loadPageOwnershipRuntime({ renderProgress, renderSourcesBanner }) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const productionSource = [
+ extractFunction(template, 'checkDataStatus'),
+ extractFunction(template, '_pollDownloadProgress'),
+ extractFunction(template, 'downloadJournalData'),
+ extractAsyncListener(template, 'document', 'DOMContentLoaded'),
+ extractAsyncListener(template, 'window', 'load'),
+ ].join('\n');
+ let domReadyHandler;
+ let windowLoadHandler;
+ const pageDocument = {
+ addEventListener: vi.fn((eventName, handler) => {
+ if (eventName === 'DOMContentLoaded') domReadyHandler = handler;
+ }),
+ getElementById: id => document.getElementById(id),
+ };
+ const pageWindow = {
+ api: window.api,
+ addEventListener: vi.fn((eventName, handler) => {
+ if (eventName === 'load') windowLoadHandler = handler;
+ }),
+ };
+ // Repository-owned production source and listener registrations only;
+ // the surrounding declarations replace unrelated dashboard consumers.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'document',
+ 'window',
+ '_renderProgress',
+ 'renderSourcesBanner',
+ `
+ let _ldrProgressTimer = null;
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ let thresholdLoaded = false;
+ let userResearchLoaded = false;
+ const loadThreshold = () => {};
+ const loadUserResearchJournals = () => {};
+ ${productionSource}
+ return {
+ checkDataStatus,
+ downloadJournalData,
+ getProgressTimer: () => _ldrProgressTimer,
+ getProgressGeneration: () => _ldrProgressGeneration,
+ };
+ `,
+ )(
+ pageDocument,
+ pageWindow,
+ renderProgress,
+ renderSourcesBanner,
+ );
+
+ return {
+ ...runtime,
+ runDomReady: () => domReadyHandler(),
+ runWindowLoad: () => windowLoadHandler(),
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <button id="ldr-data-download-btn">Download Data</button>
+ <div id="ldr-data-progress-intro">Idle</div>
+ <div id="ldr-data-banner" style="display: none"></div>
+ <span id="ldr-data-banner-text">Owned banner</span>
+ <div id="ldr-loading"></div>
+ <div id="ldr-content" style="display: none"></div>
+ <div id="ldr-tab-your-research" style="display: none"></div>
+ <div id="ldr-tab-global-db"></div>
+ <div id="ldr-tab-how-it-works"></div>
+ `;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-journal') };
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ document.body.replaceChildren();
+});
+
+it('POSTs with CSRF and renders the successful download envelope', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: true,
+ message: 'Reference database installed',
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const renderProgress = vi.fn();
+ const downloadJournalData = loadDownloadHandler({
+ renderProgress,
+ pollDownloadProgress: vi.fn(),
+ });
+
+ await downloadJournalData();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/journal-data/download',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-journal',
+ },
+ body: JSON.stringify({ force: false }),
+ },
+ );
+ expect(renderProgress).toHaveBeenCalledWith({
+ state: 'running',
+ sources: {},
+ db_build: { state: 'pending' },
+ });
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe('[100%] Complete — Reference database installed');
+ expect(document.getElementById('ldr-data-download-btn').disabled)
+ .toBe(true);
+});
+
+it('restores the action and uses the real progress element on API rejection', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ success: false,
+ message: 'OpenAlex download failed',
+ }), { status: 502 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const downloadJournalData = loadDownloadHandler({
+ renderProgress: vi.fn(),
+ pollDownloadProgress: vi.fn(),
+ });
+
+ await downloadJournalData();
+
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe('Error: OpenAlex download failed');
+ const button = document.getElementById('ldr-data-download-btn');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toBe('Retry Download');
+});
+
+it.each([
+ {
+ terminalState: 'completion',
+ result: { success: true, message: 'Reference database installed' },
+ expectedText: '[100%] Complete — Reference database installed',
+ expectedButtonDisabled: true,
+ },
+ {
+ terminalState: 'error',
+ result: { success: false, message: 'OpenAlex download failed' },
+ expectedText: 'Error: OpenAlex download failed',
+ expectedButtonDisabled: false,
+ },
+])('does not let an in-flight poll overwrite POST $terminalState', async ({
+ result,
+ expectedText,
+ expectedButtonDisabled,
+}) => {
+ const postResponse = deferred();
+ const pollJson = deferred();
+ const fetchMock = vi.fn(url => {
+ if (url === '/metrics/api/journal-data/download') {
+ return postResponse.promise;
+ }
+ if (url === '/metrics/api/journal-data/status') {
+ return Promise.resolve({
+ ok: true,
+ json: vi.fn(() => pollJson.promise),
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderProgress = vi.fn();
+ const runtime = loadDownloadRuntime(renderProgress);
+
+ const downloadRun = runtime.downloadJournalData();
+ const stalePoll = runtime.pollDownloadProgress();
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/journal-data/download',
+ '/metrics/api/journal-data/status',
+ ]);
+
+ postResponse.resolve(new Response(JSON.stringify(result), { status: 200 }));
+ await downloadRun;
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe(expectedText);
+
+ pollJson.resolve({
+ download_progress: {
+ state: 'running',
+ sources: { openalex: { state: 'running', percent: 80 } },
+ },
+ });
+ await stalePoll;
+
+ expect(renderProgress).toHaveBeenCalledOnce();
+ expect(renderProgress).toHaveBeenCalledWith({
+ state: 'running',
+ sources: {},
+ db_build: { state: 'pending' },
+ });
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe(expectedText);
+ expect(document.getElementById('ldr-data-download-btn').disabled)
+ .toBe(expectedButtonDisabled);
+});
+
+it('keeps deferred page-load status listeners from stealing download ownership', async () => {
+ const domReadyStatus = deferred();
+ const windowLoadStatus = deferred();
+ const activeDownloadStatus = deferred();
+ const postResponse = deferred();
+ let statusRequestCount = 0;
+ const fetchMock = vi.fn(url => {
+ if (url === '/metrics/api/journal-data/status') {
+ statusRequestCount += 1;
+ if (statusRequestCount === 1) return domReadyStatus.promise;
+ if (statusRequestCount === 2) return windowLoadStatus.promise;
+ return activeDownloadStatus.promise;
+ }
+ if (url === '/metrics/api/journal-data/download') {
+ return postResponse.promise;
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderProgress = vi.fn();
+ const renderSourcesBanner = vi.fn();
+ const runtime = loadPageOwnershipRuntime({
+ renderProgress,
+ renderSourcesBanner,
+ });
+
+ const domReadyRun = runtime.runDomReady();
+ const windowLoadRun = runtime.runWindowLoad();
+ const downloadRun = runtime.downloadJournalData();
+ const activeStatusRun = runtime.checkDataStatus();
+ const ownedProgressTimer = runtime.getProgressTimer();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/journal-data/status',
+ '/metrics/api/journal-data/status',
+ '/metrics/api/journal-data/download',
+ '/metrics/api/journal-data/status',
+ ]);
+ expect(runtime.getProgressGeneration()).toBe(1);
+ expect(ownedProgressTimer).not.toBeNull();
+ expect(vi.getTimerCount()).toBe(1);
+
+ const staleStatus = {
+ available: false,
+ needs_update: false,
+ sources: [{ name: 'Stale source', present: false }],
+ download_progress: {
+ state: 'running',
+ sources: { openalex: { state: 'running', percent: 80 } },
+ },
+ };
+ domReadyStatus.resolve(new Response(JSON.stringify(staleStatus), {
+ status: 200,
+ }));
+ activeDownloadStatus.resolve(new Response(JSON.stringify(staleStatus), {
+ status: 200,
+ }));
+ await Promise.all([domReadyRun, activeStatusRun]);
+
+ expect(runtime.getProgressTimer()).toBe(ownedProgressTimer);
+ expect(vi.getTimerCount()).toBe(1);
+ expect(renderProgress).toHaveBeenCalledOnce();
+ expect(renderProgress).toHaveBeenCalledWith({
+ state: 'running',
+ sources: {},
+ db_build: { state: 'pending' },
+ });
+ expect(renderSourcesBanner).not.toHaveBeenCalled();
+ expect(document.getElementById('ldr-data-download-btn').textContent)
+ .toBe('Downloading...');
+ expect(document.getElementById('ldr-data-banner-text').textContent)
+ .toBe('Owned banner');
+
+ postResponse.resolve(new Response(JSON.stringify({
+ success: false,
+ message: 'OpenAlex download failed',
+ }), { status: 502 }));
+ await downloadRun;
+
+ expect(runtime.getProgressGeneration()).toBe(2);
+ expect(runtime.getProgressTimer()).toBeNull();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe('Error: OpenAlex download failed');
+ const button = document.getElementById('ldr-data-download-btn');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toBe('Retry Download');
+
+ // The window-load checkDataStatus request was also started before the
+ // click, but finishes after the POST reached its terminal state.
+ windowLoadStatus.resolve(new Response(JSON.stringify(staleStatus), {
+ status: 200,
+ }));
+ await windowLoadRun;
+
+ expect(renderSourcesBanner).not.toHaveBeenCalled();
+ expect(runtime.getProgressTimer()).toBeNull();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe('Error: OpenAlex download failed');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toBe('Retry Download');
+ expect(document.getElementById('ldr-data-banner-text').textContent)
+ .toBe('Owned banner');
+});
+
+it.each([
+ {
+ state: 'success',
+ expectedText: '[100%] Complete — Journal data is ready.',
+ expectedButton: 'Downloaded',
+ expectedDisabled: true,
+ },
+ {
+ state: 'error',
+ error_msg: 'Required OpenAlex source failed',
+ expectedText: 'Error: Required OpenAlex source failed',
+ expectedButton: 'Retry Download',
+ expectedDisabled: false,
+ },
+])('settles resumed polling when the backend reports $state', async ({
+ state,
+ error_msg: errorMessage,
+ expectedText,
+ expectedButton,
+ expectedDisabled,
+}) => {
+ const reload = vi.spyOn(window.location, 'reload').mockImplementation(() => {});
+ const running = {
+ state: 'running',
+ sources: { openalex: { state: 'running', percent: 25 } },
+ db_build: { state: 'pending' },
+ };
+ const terminal = {
+ state,
+ error_msg: errorMessage,
+ sources: { openalex: { state } },
+ db_build: { state },
+ };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ download_progress: running,
+ }), { status: 200 }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ download_progress: terminal,
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const renderProgress = vi.fn();
+ const runtime = loadPageOwnershipRuntime({
+ renderProgress,
+ renderSourcesBanner: vi.fn(),
+ });
+
+ await runtime.runDomReady();
+ expect(runtime.getProgressTimer()).not.toBeNull();
+ expect(vi.getTimerCount()).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(renderProgress).toHaveBeenNthCalledWith(1, running);
+ expect(renderProgress).toHaveBeenNthCalledWith(2, terminal);
+ expect(runtime.getProgressTimer()).toBeNull();
+ expect(runtime.getProgressGeneration()).toBe(1);
+ expect(vi.getTimerCount()).toBe(state === 'success' ? 1 : 0);
+ expect(document.getElementById('ldr-data-progress-intro').textContent)
+ .toBe(expectedText);
+ const button = document.getElementById('ldr-data-download-btn');
+ expect(button.textContent).toBe(expectedButton);
+ expect(button.disabled).toBe(expectedDisabled);
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(reload).toHaveBeenCalledTimes(state === 'success' ? 1 : 0);
+});
+
+it('refreshes the journal table once when polling completes before the POST', async () => {
+ const postResponse = deferred();
+ const reload = vi.spyOn(window.location, 'reload').mockImplementation(() => {});
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => postResponse.promise)
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ download_progress: { state: 'success', sources: {}, db_build: { state: 'success' } },
+ }), { status: 200 })));
+ const runtime = loadDownloadRuntime(vi.fn());
+
+ const download = runtime.downloadJournalData();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(document.getElementById('ldr-data-download-btn').textContent).toBe('Downloaded');
+
+ postResponse.resolve(new Response(JSON.stringify({
+ success: true, message: 'Reference database installed',
+ }), { status: 200 }));
+ await download;
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(reload).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(0);
+});
diff --git a/tests/js/pages/journal-quality-runtime.test.js b/tests/js/pages/journal-quality-runtime.test.js
new file mode 100644
index 0000000000..864d052ab9
--- /dev/null
+++ b/tests/js/pages/journal-quality-runtime.test.js
@@ -0,0 +1,699 @@
+/** Runtime FastAPI contracts for journal_quality.html. */
+
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/journal_quality.html',
+);
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolveDeferred, rejectDeferred) => {
+ resolvePromise = resolveDeferred;
+ rejectPromise = rejectDeferred;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+function renderThresholdFixture() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-journal">';
+ document.body.innerHTML = `
+ <span id="ldr-threshold-save-status"></span>
+ <span id="ldr-threshold-save-status-top"></span>
+ `;
+}
+
+function renderJournalFixture() {
+ document.body.innerHTML = `
+ <input id="ldr-journal-search" value="climate & health">
+ <select id="ldr-filter-tier"><option value="elite" selected>Elite</option></select>
+ <select id="ldr-filter-source"><option value="doaj" selected>DOAJ</option></select>
+ <div id="ldr-error" style="display: none"></div>
+ <div id="ldr-loading" style="display: block"></div>
+ <span id="stat-total"></span>
+ <span id="stat-avg-quality"></span>
+ <span id="stat-predatory"></span>
+ <span id="stat-doaj"></span>
+ <span id="stat-h-index"></span>
+ `;
+}
+
+function compileJournalPageRuntime(dependencies) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['buildApiUrl', 'loadJournalPage'],
+ dependencies,
+ preamble: `
+ const PAGE_SIZE = 50;
+ let sortField = 'quality';
+ let sortDir = 'desc';
+ let currentPage = 1;
+ let totalPages = 1;
+ let totalCount = 0;
+ let summaryLoaded = false;
+ let journalPageRequestId = 0;
+ `,
+ returnExpression: `({
+ loadJournalPage,
+ getPage: () => currentPage,
+ getTotalCount: () => totalCount,
+ })`,
+ });
+}
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.ui;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+ window.history.replaceState({}, '', '/');
+});
+
+it('PUTs the threshold with its CSRF token and renders the success envelope', async () => {
+ vi.useFakeTimers();
+ renderThresholdFixture();
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true });
+ vi.stubGlobal('fetch', fetchMock);
+ window.ui = { showMessage: vi.fn() };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['saveThreshold'],
+ preamble: `
+ let thresholdIntentGeneration = 0;
+ let thresholdSaveTail = Promise.resolve();
+ `,
+ returnExpression: '({ saveThreshold })',
+ });
+
+ await harness.saveThreshold(7);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/api/search.journal_reputation.threshold',
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-journal',
+ },
+ body: JSON.stringify({ value: 7 }),
+ },
+ );
+ expect(document.getElementById('ldr-threshold-save-status').textContent)
+ .toBe('✓ Saved');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Journal quality threshold updated to 7',
+ 'success',
+ );
+});
+
+it('surfaces a failed threshold update without claiming it was saved', async () => {
+ renderThresholdFixture();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 422,
+ }));
+ window.ui = { showMessage: vi.fn() };
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['saveThreshold'],
+ preamble: `
+ let thresholdIntentGeneration = 0;
+ let thresholdSaveTail = Promise.resolve();
+ `,
+ returnExpression: '({ saveThreshold })',
+ });
+
+ await harness.saveThreshold(11);
+
+ expect(error).toHaveBeenCalled();
+ expect(document.getElementById('ldr-threshold-save-status').textContent)
+ .toBe('✗ Save failed');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Failed to save threshold setting',
+ 'error',
+ );
+});
+
+it('loads the nested threshold setting and falls back after an HTTP error', async () => {
+ const updateThresholdExplanation = vi.fn();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ setting: { value: 6 },
+ }),
+ })
+ .mockResolvedValueOnce({ ok: false, status: 500 });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadThreshold'],
+ dependencies: { updateThresholdExplanation },
+ preamble: 'let thresholdIntentGeneration = 0;',
+ returnExpression: '({ loadThreshold })',
+ });
+
+ await harness.loadThreshold();
+ await harness.loadThreshold();
+
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 1,
+ '/settings/api/search.journal_reputation.threshold',
+ );
+ expect(updateThresholdExplanation).toHaveBeenNthCalledWith(1, 6);
+ expect(updateThresholdExplanation).toHaveBeenNthCalledWith(2, 2);
+});
+
+it('does not let threshold hydration overwrite newer slider input', async () => {
+ const staleLoad = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => staleLoad.promise));
+ const updateThresholdExplanation = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['onThresholdInput', 'loadThreshold'],
+ dependencies: { updateThresholdExplanation },
+ preamble: 'let thresholdIntentGeneration = 0;',
+ returnExpression: '({ onThresholdInput, loadThreshold })',
+ });
+
+ const load = harness.loadThreshold();
+ harness.onThresholdInput('9', 'top');
+ staleLoad.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ setting: { value: 2 } }),
+ });
+ await load;
+
+ expect(updateThresholdExplanation).toHaveBeenCalledOnce();
+ expect(updateThresholdExplanation).toHaveBeenCalledWith('9');
+});
+
+it('serializes threshold writes and releases the latest save after rejection', async () => {
+ vi.useFakeTimers();
+ renderThresholdFixture();
+ const olderSave = deferred();
+ const newerSave = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderSave.promise)
+ .mockImplementationOnce(() => newerSave.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ window.ui = { showMessage: vi.fn() };
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['saveThreshold'],
+ preamble: `
+ let thresholdIntentGeneration = 0;
+ let thresholdSaveTail = Promise.resolve();
+ `,
+ returnExpression: '({ saveThreshold })',
+ });
+
+ const olderRequest = harness.saveThreshold(3);
+ const newerRequest = harness.saveThreshold(8);
+ await Promise.resolve();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ value: 3 });
+
+ olderSave.reject(new Error('older write failed'));
+ await olderRequest;
+ await Promise.resolve();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body)).toEqual({ value: 8 });
+
+ newerSave.resolve({ ok: true });
+ await newerRequest;
+
+ expect(document.getElementById('ldr-threshold-save-status').textContent)
+ .toBe('✓ Saved');
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Journal quality threshold updated to 8',
+ 'success',
+ );
+});
+
+it('renders journal-data update status from the migrated status endpoint', async () => {
+ document.body.innerHTML = `
+ <div id="ldr-data-banner" style="display: none"></div>
+ <span id="ldr-data-banner-text"></span>
+ <button id="ldr-data-download-btn"></button>
+ `;
+ const sources = [{ name: 'OpenAlex', present: true }];
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ available: true,
+ needs_update: true,
+ latest_version: '2026.08',
+ sources,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderSourcesBanner = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['checkDataStatus'],
+ dependencies: { renderSourcesBanner },
+ preamble: `
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressTimer = null;
+ `,
+ returnExpression: '({ checkDataStatus })',
+ });
+
+ await expect(harness.checkDataStatus()).resolves.toBe(true);
+
+ expect(fetchMock).toHaveBeenCalledWith('/metrics/api/journal-data/status');
+ expect(renderSourcesBanner).toHaveBeenCalledWith(sources);
+ expect(document.getElementById('ldr-data-banner').style.display)
+ .toBe('block');
+ expect(document.getElementById('ldr-data-banner-text').textContent)
+ .toContain('2026.08');
+ expect(document.getElementById('ldr-data-download-btn').textContent)
+ .toBe('Update Data');
+});
+
+it('polls running journal downloads with an explicit JSON response contract', async () => {
+ const snapshot = {
+ state: 'running',
+ sources: { openalex: { state: 'running' } },
+ };
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ download_progress: snapshot }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderProgress = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['_pollDownloadProgress'],
+ dependencies: { _renderProgress: renderProgress },
+ preamble: `
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressTimer = null;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ `,
+ returnExpression: '({ pollDownloadProgress: _pollDownloadProgress })',
+ });
+
+ await harness.pollDownloadProgress();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/journal-data/status',
+ { headers: { Accept: 'application/json' } },
+ );
+ expect(renderProgress).toHaveBeenCalledWith(snapshot);
+});
+
+it('does not regress journal download progress from an older poll', async () => {
+ const olderPoll = deferred();
+ const newerPoll = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockImplementationOnce(() => newerPoll.promise));
+ const renderProgress = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['_pollDownloadProgress'],
+ dependencies: { _renderProgress: renderProgress },
+ preamble: `
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressTimer = 77;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ `,
+ returnExpression: '({ poll: _pollDownloadProgress })',
+ });
+
+ const olderRequest = harness.poll();
+ const newerRequest = harness.poll();
+ const current = { state: 'running', sources: { openalex: { percent: 80 } } };
+ newerPoll.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ download_progress: current }),
+ });
+ await newerRequest;
+ olderPoll.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ download_progress: {
+ state: 'running',
+ sources: { openalex: { percent: 20 } },
+ },
+ }),
+ });
+ await olderRequest;
+
+ expect(renderProgress).toHaveBeenCalledOnce();
+ expect(renderProgress).toHaveBeenCalledWith(current);
+});
+
+it('accepts an older terminal journal snapshot after newer running progress', async () => {
+ const terminalPoll = deferred();
+ const newerPoll = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => terminalPoll.promise)
+ .mockImplementationOnce(() => newerPoll.promise));
+ const renderProgress = vi.fn();
+ const clearIntervalSpy = vi.spyOn(globalThis, 'clearInterval');
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['_pollDownloadProgress'],
+ dependencies: { _renderProgress: renderProgress },
+ preamble: `
+ let _ldrProgressGeneration = 0;
+ let _ldrProgressTimer = 78;
+ let _ldrProgressRequestId = 0;
+ let _ldrLatestAppliedProgressRequestId = 0;
+ `,
+ returnExpression: `({
+ poll: _pollDownloadProgress,
+ getTimer: () => _ldrProgressTimer,
+ })`,
+ });
+
+ const terminalRequest = harness.poll();
+ const newerRequest = harness.poll();
+ newerPoll.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ download_progress: { state: 'running', sources: {} },
+ }),
+ });
+ await newerRequest;
+ terminalPoll.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ download_progress: {
+ state: 'success',
+ sources: {},
+ db_build: { state: 'success' },
+ },
+ }),
+ });
+ await terminalRequest;
+
+ expect(renderProgress).toHaveBeenCalledTimes(2);
+ expect(renderProgress).toHaveBeenLastCalledWith(expect.objectContaining({
+ state: 'success',
+ }));
+ expect(clearIntervalSpy).toHaveBeenCalledWith(78);
+ expect(harness.getTimer()).toBeNull();
+});
+
+it('builds the journal list URL from the active filters and summary flag', () => {
+ renderJournalFixture();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['buildApiUrl'],
+ preamble: `
+ const PAGE_SIZE = 50;
+ let sortField = 'quality';
+ let sortDir = 'desc';
+ `,
+ returnExpression: '({ buildApiUrl })',
+ });
+
+ const url = new URL(harness.buildApiUrl(3, true), 'https://ldr.test');
+
+ expect(url.pathname).toBe('/metrics/api/journals');
+ expect(Object.fromEntries(url.searchParams)).toEqual({
+ page: '3',
+ per_page: '50',
+ sort: 'quality',
+ order: 'desc',
+ search: 'climate & health',
+ tier: 'elite',
+ score_source: 'doaj',
+ include_summary: 'true',
+ });
+});
+
+it('treats a 503 journal list as the expected first-install state', async () => {
+ renderJournalFixture();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ status: 503 }));
+ const renderTable = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['buildApiUrl', 'loadJournalPage'],
+ dependencies: {
+ renderTable,
+ renderPagination: vi.fn(),
+ updateQualityDistChart: vi.fn(),
+ updateScoreSourceChart: vi.fn(),
+ },
+ preamble: `
+ const PAGE_SIZE = 50;
+ let sortField = 'quality';
+ let sortDir = 'desc';
+ let currentPage = 1;
+ let totalPages = 1;
+ let totalCount = 0;
+ let summaryLoaded = false;
+ let journalPageRequestId = 0;
+ `,
+ returnExpression: '({ loadJournalPage })',
+ });
+
+ await harness.loadJournalPage(1, true);
+
+ expect(document.getElementById('ldr-error').style.display).toBe('none');
+ expect(document.getElementById('ldr-loading').style.display).toBe('none');
+ expect(renderTable).not.toHaveBeenCalled();
+});
+
+it('renders journal rows, pagination, and summary from the success envelope', async () => {
+ renderJournalFixture();
+ const journals = [{ id: 'issn-1', name: 'Journal A' }];
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ journals,
+ pagination: { page: 2, total_pages: 4, total_count: 151 },
+ summary: {
+ total: 151,
+ avg_quality: 7.4,
+ predatory_count: 3,
+ doaj_count: 99,
+ avg_h_index: null,
+ quality_distribution: { 7: 10 },
+ source_distribution: { doaj: 99 },
+ },
+ }),
+ }));
+ const renderTable = vi.fn();
+ const renderPagination = vi.fn();
+ const updateQualityDistChart = vi.fn();
+ const updateScoreSourceChart = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['buildApiUrl', 'loadJournalPage'],
+ dependencies: {
+ renderTable,
+ renderPagination,
+ updateQualityDistChart,
+ updateScoreSourceChart,
+ },
+ preamble: `
+ const PAGE_SIZE = 50;
+ let sortField = 'quality';
+ let sortDir = 'desc';
+ let currentPage = 1;
+ let totalPages = 1;
+ let totalCount = 0;
+ let summaryLoaded = false;
+ let journalPageRequestId = 0;
+ `,
+ returnExpression: '({ loadJournalPage })',
+ });
+
+ await harness.loadJournalPage(2, true);
+
+ expect(renderTable).toHaveBeenCalledWith(journals, 151);
+ expect(renderPagination).toHaveBeenCalledOnce();
+ expect(updateQualityDistChart).toHaveBeenCalledWith({ 7: 10 });
+ expect(updateScoreSourceChart).toHaveBeenCalledWith({ doaj: 99 });
+ expect(document.getElementById('stat-total').textContent).toBe('151');
+ expect(document.getElementById('stat-h-index').textContent).toBe('—');
+});
+
+it('keeps a newer journal filter result over an older success', async () => {
+ renderJournalFixture();
+ const olderLoad = deferred();
+ const newerLoad = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderLoad.promise)
+ .mockImplementationOnce(() => newerLoad.promise));
+ const renderTable = vi.fn();
+ const harness = compileJournalPageRuntime({
+ renderTable,
+ renderPagination: vi.fn(),
+ updateQualityDistChart: vi.fn(),
+ updateScoreSourceChart: vi.fn(),
+ });
+
+ const olderRequest = harness.loadJournalPage(1, false);
+ document.getElementById('ldr-journal-search').value = 'new intent';
+ const newerRequest = harness.loadJournalPage(2, false);
+ const currentRows = [{ id: 'current-journal' }];
+ newerLoad.resolve({
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ journals: currentRows,
+ pagination: { page: 2, total_pages: 3, total_count: 51 },
+ }),
+ });
+ await newerRequest;
+ olderLoad.resolve({
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ journals: [{ id: 'stale-journal' }],
+ pagination: { page: 1, total_pages: 1, total_count: 1 },
+ }),
+ });
+ await olderRequest;
+
+ expect(renderTable).toHaveBeenCalledOnce();
+ expect(renderTable).toHaveBeenCalledWith(currentRows, 51);
+ expect(harness.getPage()).toBe(2);
+ expect(harness.getTotalCount()).toBe(51);
+});
+
+it('does not let an older journal failure replace a newer result', async () => {
+ renderJournalFixture();
+ const olderLoad = deferred();
+ const newerLoad = deferred();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockImplementationOnce(() => olderLoad.promise)
+ .mockImplementationOnce(() => newerLoad.promise));
+ const renderTable = vi.fn();
+ const harness = compileJournalPageRuntime({
+ renderTable,
+ renderPagination: vi.fn(),
+ updateQualityDistChart: vi.fn(),
+ updateScoreSourceChart: vi.fn(),
+ });
+
+ const olderRequest = harness.loadJournalPage(1, false);
+ document.getElementById('ldr-filter-tier').value = '';
+ const newerRequest = harness.loadJournalPage(1, false);
+ newerLoad.resolve({
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ journals: [{ id: 'current-journal' }],
+ pagination: { page: 1, total_pages: 1, total_count: 1 },
+ }),
+ });
+ await newerRequest;
+ olderLoad.reject(new Error('stale network failure'));
+ await olderRequest;
+
+ expect(renderTable).toHaveBeenCalledOnce();
+ expect(document.getElementById('ldr-error').style.display).toBe('none');
+ expect(document.getElementById('ldr-error').textContent).toBe('');
+});
+
+it('uses the research-scoped journal endpoint and renders its success shape', async () => {
+ window.history.replaceState({}, '', '/metrics/journals?research_id=run%2Fa');
+ document.body.innerHTML = `
+ <div id="ldr-yr-loading" style="display: block"></div>
+ <div id="ldr-yr-empty" style="display: none"></div>
+ <div id="ldr-yr-content" style="display: none"></div>
+ <span id="yr-stat-journals"></span>
+ <span id="yr-stat-avg-quality"></span>
+ <span id="yr-stat-papers"></span>
+ <span id="yr-stat-predatory"></span>
+ <span id="yr-table-count"></span>
+ `;
+ const journals = [{ name: 'Journal A' }];
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ summary: {
+ total_journals: 1,
+ avg_quality: 8.5,
+ total_papers: 4,
+ predatory_blocked: 2,
+ },
+ quality_distribution: { 8: 1 },
+ journals,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderYrTable = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadUserResearchJournals'],
+ dependencies: {
+ renderYrQualityChart: vi.fn(),
+ renderYrSourceChart: vi.fn(),
+ renderYrTable,
+ },
+ returnExpression: '({ loadUserResearchJournals })',
+ });
+
+ await harness.loadUserResearchJournals();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/journals/research/run%2Fa',
+ );
+ expect(document.getElementById('ldr-yr-content').style.display)
+ .toBe('block');
+ expect(document.getElementById('yr-stat-predatory').textContent).toBe('2');
+ expect(renderYrTable).toHaveBeenCalledWith(journals);
+});
+
+it('uses the aggregate journal endpoint and renders its empty success shape', async () => {
+ window.history.replaceState({}, '', '/metrics/journals');
+ document.body.innerHTML = `
+ <div id="ldr-yr-loading" style="display: block"></div>
+ <div id="ldr-yr-empty" style="display: none"></div>
+ <div id="ldr-yr-content" style="display: none"></div>
+ `;
+ const fetchMock = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ summary: { total_journals: 0 },
+ quality_distribution: {},
+ journals: [],
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const renderYrTable = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadUserResearchJournals'],
+ dependencies: {
+ renderYrQualityChart: vi.fn(),
+ renderYrSourceChart: vi.fn(),
+ renderYrTable,
+ },
+ returnExpression: '({ loadUserResearchJournals })',
+ });
+
+ await harness.loadUserResearchJournals();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/metrics/api/journals/user-research',
+ );
+ expect(document.getElementById('ldr-yr-loading').style.display)
+ .toBe('none');
+ expect(document.getElementById('ldr-yr-empty').style.display)
+ .toBe('block');
+ expect(renderYrTable).not.toHaveBeenCalled();
+});
diff --git a/tests/js/pages/library-inline-runtime.test.js b/tests/js/pages/library-inline-runtime.test.js
new file mode 100644
index 0000000000..84132035f8
--- /dev/null
+++ b/tests/js/pages/library-inline-runtime.test.js
@@ -0,0 +1,850 @@
+/**
+ * Runtime contracts for the library page's inline content viewer and sync.
+ *
+ * These execute the checked-in template functions, covering browser-visible
+ * FastAPI request paths and modal/error state rather than duplicating them in
+ * a hand-written fixture implementation.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/library.html',
+);
+const SSE_UTIL_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/utils/sse-completion.js',
+);
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileContentViewer() {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'openDocument',
+ 'openPDF',
+ 'closePDFModal',
+ 'handleEscapeKey',
+ 'openText',
+ 'closeTextModal',
+ 'handleTextEscapeKey',
+ ].map(name => extractFunction(template, name)).join('\n');
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ `
+ let currentPDFData = null;
+ let currentTextData = null;
+ let documentViewerRequestId = 0;
+ ${functions}
+ return {
+ openDocument,
+ openPDF,
+ closePDFModal,
+ openText,
+ closeTextModal,
+ };
+ `,
+ );
+ return factory();
+}
+
+function compilePerformSync() {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const source = extractFunction(template, 'performSync');
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ return new Function(`return (${source});`)(); // eslint-disable-line no-new-func
+}
+
+function loadSSEUtilities() {
+ const utilitySource = readFileSync(SSE_UTIL_PATH, 'utf8');
+ return new Function( // eslint-disable-line no-new-func
+ `${utilitySource}\nreturn {
+ createSSEJsonParser,
+ handleSSECompletion,
+ };`,
+ )();
+}
+
+function compileTextDownload(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const source = [
+ 'resetDownloadProgress',
+ 'downloadAllAsText',
+ ].map(name => extractFunction(template, name)).join('\n');
+ const runtimeDependencies = {
+ ...dependencies,
+ createSSEJsonParser: loadSSEUtilities().createSSEJsonParser,
+ };
+ const dependencyNames = Object.keys(runtimeDependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `
+ let currentDownloadController = null;
+ let currentDownloadRunId = 0;
+ ${source}
+ return downloadAllAsText;
+ `,
+ );
+ return factory(...Object.values(runtimeDependencies));
+}
+
+function compileLibraryDownloads(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'resetDownloadProgress',
+ 'downloadAllAsText',
+ 'downloadAllNew',
+ 'closeProgressModal',
+ 'cancelDownloads',
+ ].map(name => extractFunction(template, name)).join('\n');
+ const runtimeDependencies = {
+ ...dependencies,
+ createSSEJsonParser: loadSSEUtilities().createSSEJsonParser,
+ };
+ const dependencyNames = Object.keys(runtimeDependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `
+ let currentDownloadController = null;
+ let currentDownloadRunId = 0;
+ ${functions}
+ return {
+ downloadAllAsText,
+ downloadAllNew,
+ cancelDownloads,
+ getCurrentDownloadController: () => currentDownloadController,
+ };
+ `,
+ );
+ return factory(...Object.values(runtimeDependencies));
+}
+
+function streamingChunks(...chunks) {
+ const read = vi.fn();
+ for (const chunk of chunks) {
+ read.mockResolvedValueOnce({
+ done: false,
+ value: new globalThis.TextEncoder().encode(chunk),
+ });
+ }
+ read.mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ };
+}
+
+function pausableStreamResponse(event) {
+ let markStarted;
+ let finishStream;
+ const started = new Promise(resolvePromise => {
+ markStarted = resolvePromise;
+ });
+ const pendingRead = new Promise(resolvePromise => {
+ finishStream = resolvePromise;
+ });
+ const read = vi.fn()
+ .mockImplementationOnce(() => {
+ markStarted();
+ return pendingRead;
+ })
+ .mockResolvedValueOnce({ done: true, value: undefined });
+ return {
+ response: {
+ ok: true,
+ status: 200,
+ body: { getReader: vi.fn(() => ({ read })) },
+ },
+ started,
+ finish: () => finishStream({
+ done: false,
+ value: new globalThis.TextEncoder().encode(
+ `data: ${JSON.stringify(event)}\n`,
+ ),
+ }),
+ finishEOF: () => finishStream({
+ done: true,
+ value: undefined,
+ }),
+ };
+}
+
+function renderViewer() {
+ document.body.innerHTML = `
+ <div id="ldr-pdf-modal" style="display: none"></div>
+ <iframe id="pdf-viewer"></iframe>
+ <h2 id="ldr-pdf-title"></h2>
+ <div id="text-modal" style="display: none"></div>
+ <pre id="text-viewer"></pre>
+ <h2 id="text-title"></h2>
+ `;
+}
+
+function renderSync() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-sync">';
+ document.body.innerHTML = `
+ <button id="sync-start-btn"><i></i>Start Sync</button>
+ <div class="ldr-sync-explanation"></div>
+ <div id="sync-progress" style="display: none"></div>
+ <div id="sync-results" style="display: none"></div>
+ <div id="sync-status"></div>
+ <span id="files-found"></span>
+ <span id="files-missing"></span>
+ <div id="missing-files-action" style="display: none"></div>
+ `;
+}
+
+afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.closeProgressModal;
+ delete window.createSSEJsonParser;
+ delete window.handleSSECompletion;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('prefers the PDF endpoint and closes the populated modal on Escape', async () => {
+ renderViewer();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ url: '/library/api/document/doc-7/pdf',
+ title: 'Migration report',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ compileContentViewer().openDocument('doc-7', true, true);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('ldr-pdf-modal').style.display)
+ .toBe('block');
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/document/doc-7/pdf-url',
+ );
+ expect(document.getElementById('pdf-viewer').getAttribute('src'))
+ .toBe('/library/api/document/doc-7/pdf');
+ expect(document.getElementById('ldr-pdf-title').textContent)
+ .toBe('Migration report');
+
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ expect(document.getElementById('ldr-pdf-modal').style.display).toBe('none');
+ expect(document.getElementById('pdf-viewer').getAttribute('src')).toBe('');
+});
+
+it('falls back to encrypted text and renders content as text, not markup', async () => {
+ renderViewer();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ text_content: '<img src=x onerror=alert(1)>plain text',
+ title: 'Text-only document',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ compileContentViewer().openDocument('doc-8', false, true);
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('text-modal').style.display)
+ .toBe('block');
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/library/api/document/doc-8/text');
+ const viewer = document.getElementById('text-viewer');
+ expect(viewer.textContent).toBe('<img src=x onerror=alert(1)>plain text');
+ expect(viewer.querySelector('img')).toBeNull();
+
+ document.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ expect(document.getElementById('text-modal').style.display).toBe('none');
+ expect(viewer.textContent).toBe('');
+});
+
+it('does not fetch when no stored content exists and gives the user feedback', () => {
+ renderViewer();
+ const fetchMock = vi.fn();
+ const alertMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('alert', alertMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ compileContentViewer().openDocument('doc-9', false, false);
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(alertMock).toHaveBeenCalledWith(
+ 'No content available for this document',
+ );
+});
+
+it.each([
+ {
+ kind: 'PDF',
+ open: viewer => viewer.openPDF('missing-pdf'),
+ expectedUrl: '/library/api/document/missing-pdf/pdf-url',
+ expectedAlert: 'Failed to load PDF content',
+ },
+ {
+ kind: 'text',
+ open: viewer => viewer.openText('missing-text'),
+ expectedUrl: '/library/api/document/missing-text/text',
+ expectedAlert: 'Failed to load text content',
+ },
+])('surfaces a non-ok $kind viewer response without opening a blank modal', async ({
+ open,
+ expectedUrl,
+ expectedAlert,
+}) => {
+ renderViewer();
+ const json = vi.fn();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: false,
+ status: 404,
+ json,
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await open(compileContentViewer());
+
+ expect(fetchMock).toHaveBeenCalledWith(expectedUrl);
+ expect(json).not.toHaveBeenCalled();
+ expect(alertMock).toHaveBeenCalledWith(expectedAlert);
+ expect(document.getElementById('ldr-pdf-modal').style.display).toBe('none');
+ expect(document.getElementById('text-modal').style.display).toBe('none');
+});
+
+it('keeps a newer text viewer authoritative over an older PDF request', async () => {
+ renderViewer();
+ const olderPdf = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderPdf.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ text_content: 'Current encrypted text',
+ title: 'Current document',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const viewer = compileContentViewer();
+
+ const oldLoad = viewer.openPDF('old-pdf');
+ await viewer.openText('current-text');
+ olderPdf.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ url: '/library/api/document/old-pdf/pdf',
+ title: 'Stale document',
+ }),
+ });
+ await oldLoad;
+
+ expect(document.getElementById('text-modal').style.display).toBe('block');
+ expect(document.getElementById('text-viewer').textContent)
+ .toBe('Current encrypted text');
+ expect(document.getElementById('text-title').textContent)
+ .toBe('Current document');
+ expect(document.getElementById('ldr-pdf-modal').style.display).toBe('none');
+ expect(document.getElementById('pdf-viewer').getAttribute('src')).toBeNull();
+});
+
+it.each([
+ {
+ label: 'PDF success',
+ modalId: 'ldr-pdf-modal',
+ open: viewer => viewer.openPDF('late-pdf'),
+ close: viewer => viewer.closePDFModal(),
+ response: {
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ url: '/library/api/document/late-pdf/pdf',
+ title: 'Must stay closed',
+ }),
+ },
+ },
+ {
+ label: 'text failure',
+ modalId: 'text-modal',
+ open: viewer => viewer.openText('late-text'),
+ close: viewer => viewer.closeTextModal(),
+ response: { ok: false, status: 503 },
+ },
+])('keeps an explicit close authoritative over a late $label', async ({
+ modalId,
+ open,
+ close,
+ response,
+}) => {
+ renderViewer();
+ const pendingResponse = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => pendingResponse.promise));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const viewer = compileContentViewer();
+ document.getElementById(modalId).style.display = 'block';
+
+ const request = open(viewer);
+ close(viewer);
+ pendingResponse.resolve(response);
+ await request;
+
+ expect(document.getElementById(modalId).style.display).toBe('none');
+ expect(document.getElementById('pdf-viewer').getAttribute('src') || '')
+ .toBe('');
+ expect(document.getElementById('ldr-pdf-title').textContent).toBe('');
+ expect(document.getElementById('text-viewer').textContent).toBe('');
+ expect(document.getElementById('text-title').textContent).toBe('');
+ expect(alertMock).not.toHaveBeenCalled();
+});
+
+it('syncs through the FastAPI route and exposes missing-file recovery', async () => {
+ renderSync();
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ files_found: 12, files_missing: 2 }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compilePerformSync()();
+
+ expect(fetchMock).toHaveBeenCalledWith('/library/api/sync-library', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-sync',
+ },
+ });
+ expect(document.getElementById('sync-progress').style.display).toBe('none');
+ expect(document.getElementById('sync-results').style.display).toBe('block');
+ expect(document.getElementById('files-found').textContent).toBe('12');
+ expect(document.getElementById('files-missing').textContent).toBe('2');
+ expect(document.getElementById('missing-files-action').style.display)
+ .toBe('block');
+ expect(document.getElementById('sync-start-btn').style.display).toBe('none');
+});
+
+it('restores the sync controls after an HTTP failure', async () => {
+ renderSync();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 503 }));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await compilePerformSync()();
+
+ const button = document.getElementById('sync-start-btn');
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Start Sync');
+ expect(document.querySelector('.ldr-sync-explanation').style.display)
+ .toBe('block');
+ expect(document.getElementById('sync-progress').style.display).toBe('none');
+ expect(document.getElementById('sync-status').textContent)
+ .toBe('Sync failed. Please try again.');
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to sync library. Please check your connection and try again.',
+ );
+});
+
+it('processes split text progress once and reports premature EOF', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-text">';
+ document.body.innerHTML = `
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('extract-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ const fetchMock = vi.fn().mockResolvedValue(streamingChunks(
+ 'data: {"progress":50,"current":1,"total":2,"status":"suc',
+ 'cess","file":"split.txt","url":"https://example.test/doc"}\n',
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const updateTextExtractionProgress = vi.fn();
+ const handleSSECompletion = vi.fn(() => false);
+ const downloadAllAsText = compileTextDownload({
+ showDownloadProgressModal: vi.fn(),
+ updateTextExtractionProgress,
+ handleSSECompletion,
+ });
+
+ await downloadAllAsText();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock.mock.calls[0][0]).toBe('/library/api/download-all-text');
+ expect(updateTextExtractionProgress).toHaveBeenCalledOnce();
+ expect(updateTextExtractionProgress).toHaveBeenCalledWith({
+ progress: 50,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'split.txt',
+ url: 'https://example.test/doc',
+ });
+ expect(handleSSECompletion).toHaveBeenCalledOnce();
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start text extraction:',
+ expect.objectContaining({
+ message: 'Text extraction stream ended before completion',
+ }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start text extraction. Please try again.',
+ );
+ expect(button.disabled).toBe(false);
+});
+
+it('ignores superseded library stream frames and frames delivered after cancellation', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-stream">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all</span></button>
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress" style="width: 0%"></div>
+ <span id="current-count">0</span>
+ <span id="total-count">0</span>
+ <div id="ldr-download-log"></div>
+ `;
+ const olderBulk = pausableStreamResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ file: 'stale-library.pdf',
+ });
+ const newerText = pausableStreamResponse({
+ complete: true,
+ progress: 100,
+ current: 1,
+ total: 1,
+ status: 'success',
+ file: 'cancelled-library.txt',
+ });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ queued: 1,
+ research_ids: ['stale-library'],
+ }),
+ })
+ .mockResolvedValueOnce(olderBulk.response)
+ .mockResolvedValueOnce(newerText.response);
+ vi.stubGlobal('fetch', fetchMock);
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const handleSSECompletion = vi.fn(data => data.complete);
+ const updateDownloadProgress = vi.fn();
+ const updateTextExtractionProgress = vi.fn();
+ const runtime = compileLibraryDownloads({
+ showDownloadProgressModal: vi.fn(),
+ updateDownloadProgress,
+ updateTextExtractionProgress,
+ handleSSECompletion,
+ });
+
+ vi.stubGlobal('event', {
+ target: document.querySelector('#download-all span'),
+ });
+ const olderRun = runtime.downloadAllNew();
+ await olderBulk.started;
+ const olderSignal = fetchMock.mock.calls[1][1].signal;
+
+ event.target = document.querySelector('#extract-text span');
+ const newerRun = runtime.downloadAllAsText();
+ await newerText.started;
+ const newerSignal = fetchMock.mock.calls[2][1].signal;
+
+ olderBulk.finish();
+ await olderRun;
+
+ expect(updateDownloadProgress).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(document.querySelector('#download-progress-modal h2').textContent)
+ .toBe('Text Extraction to Database');
+ expect(olderSignal.aborted).toBe(true);
+ expect(newerSignal.aborted).toBe(false);
+ expect(runtime.getCurrentDownloadController()?.signal).toBe(newerSignal);
+
+ const timeoutMock = vi.fn();
+ vi.stubGlobal('setTimeout', timeoutMock);
+ document.getElementById('download-progress-modal').style.display = 'block';
+ runtime.cancelDownloads();
+ expect(newerSignal.aborted).toBe(true);
+ expect(timeoutMock).toHaveBeenCalledOnce();
+
+ const cancelledProgress = document.getElementById('ldr-overall-progress');
+ expect(cancelledProgress.style.backgroundColor).toBe('var(--error-color)');
+ cancelledProgress.style.width = '75%';
+ document.getElementById('current-count').textContent = '3';
+ document.getElementById('total-count').textContent = '4';
+ document.getElementById('ldr-download-log').textContent = 'cancelled run';
+
+ const replacementText = pausableStreamResponse({
+ complete: true,
+ progress: 25,
+ current: 1,
+ total: 4,
+ status: 'success',
+ file: 'replacement.txt',
+ });
+ fetchMock.mockResolvedValueOnce(replacementText.response);
+ event.target = document.getElementById('extract-text');
+ const replacementRun = runtime.downloadAllAsText();
+ await replacementText.started;
+
+ expect(cancelledProgress.style.backgroundColor).toBe('');
+ expect(cancelledProgress.style.width).toBe('0%');
+ expect(document.getElementById('current-count').textContent).toBe('0');
+ expect(document.getElementById('total-count').textContent).toBe('0');
+ expect(document.getElementById('ldr-download-log').textContent).toBe('');
+ timeoutMock.mock.calls[0][0]();
+ expect(document.getElementById('download-progress-modal').style.display)
+ .toBe('block');
+
+ newerText.finishEOF();
+ await newerRun;
+
+ expect(updateTextExtractionProgress).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(alertMock).not.toHaveBeenCalled();
+
+ replacementText.finish();
+ await replacementRun;
+});
+
+it('aborts an active library text stream before download-all takes ownership', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-stream">';
+ document.body.innerHTML = `
+ <button id="download-all"><span>Download all</span></button>
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const olderText = pausableStreamResponse({
+ progress: 50,
+ current: 1,
+ total: 2,
+ status: 'success',
+ file: 'superseded.txt',
+ });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(olderText.response)
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ queued: 0,
+ research_ids: [],
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('alert', vi.fn());
+ const updateTextExtractionProgress = vi.fn();
+ const runtime = compileLibraryDownloads({
+ showDownloadProgressModal: vi.fn(),
+ updateDownloadProgress: vi.fn(),
+ updateTextExtractionProgress,
+ handleSSECompletion: vi.fn(),
+ });
+
+ vi.stubGlobal('event', {
+ target: document.querySelector('#extract-text span'),
+ });
+ const olderRun = runtime.downloadAllAsText();
+ await olderText.started;
+ const olderSignal = fetchMock.mock.calls[0][1].signal;
+
+ event.target = document.querySelector('#download-all span');
+ await runtime.downloadAllNew();
+
+ expect(olderSignal.aborted).toBe(true);
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/library/api/download-all-text',
+ '/library/api/queue-all-undownloaded',
+ ]);
+ expect(runtime.getCurrentDownloadController()).toBeNull();
+
+ olderText.finish();
+ await olderRun;
+ expect(updateTextExtractionProgress).not.toHaveBeenCalled();
+});
+
+it('surfaces a non-ok text response and restores the library action', async () => {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-text">';
+ document.body.innerHTML = `
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('extract-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(
+ JSON.stringify({ detail: 'Text extraction unavailable' }),
+ {
+ status: 503,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ )));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const updateTextExtractionProgress = vi.fn();
+ const handleSSECompletion = vi.fn();
+ const downloadAllAsText = compileTextDownload({
+ showDownloadProgressModal: vi.fn(),
+ updateTextExtractionProgress,
+ handleSSECompletion,
+ });
+
+ await downloadAllAsText();
+
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Failed to start text extraction:',
+ expect.objectContaining({ message: 'HTTP error! status: 503' }),
+ );
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Failed to start text extraction. Please try again.',
+ );
+ expect(updateTextExtractionProgress).not.toHaveBeenCalled();
+ expect(handleSSECompletion).not.toHaveBeenCalled();
+ expect(button.disabled).toBe(false);
+ expect(button.textContent).toContain('Extract');
+});
+
+it('completes text extraction with the DB-only backend contract', async () => {
+ vi.useFakeTimers();
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-text">';
+ document.body.innerHTML = `
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('extract-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(streamingChunks(
+ 'data: {"complete":true,"total":7}\n',
+ )));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ window.closeProgressModal = vi.fn();
+ const utilities = loadSSEUtilities();
+ const updateTextExtractionProgress = vi.fn();
+ const downloadAllAsText = compileTextDownload({
+ showDownloadProgressModal: vi.fn(),
+ updateTextExtractionProgress,
+ handleSSECompletion: utilities.handleSSECompletion,
+ });
+
+ await downloadAllAsText();
+
+ expect(updateTextExtractionProgress).toHaveBeenCalledOnce();
+ expect(alertMock).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(window.closeProgressModal).toHaveBeenCalledOnce();
+ expect(alertMock).toHaveBeenCalledOnce();
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Text extraction complete! Extracted 7 documents to encrypted database.',
+ );
+ expect(button.disabled).toBe(false);
+});
+
+it('suppresses a delayed completion after a newer extraction becomes current', async () => {
+ vi.useFakeTimers();
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-text">';
+ document.body.innerHTML = `
+ <button id="extract-text"><span>Extract</span></button>
+ <div id="download-progress-modal"><h2></h2></div>
+ <div id="ldr-overall-progress"></div>
+ <span id="current-count"></span>
+ <span id="total-count"></span>
+ <div id="ldr-download-log"></div>
+ `;
+ const button = document.getElementById('extract-text');
+ vi.stubGlobal('event', { target: button.querySelector('span') });
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce(streamingChunks(
+ 'data: {"complete":true,"total":7}\n',
+ ))
+ .mockResolvedValueOnce(streamingChunks(
+ 'data: {"complete":true,"total":10}\n',
+ )));
+ const alertMock = vi.fn();
+ vi.stubGlobal('alert', alertMock);
+ window.closeProgressModal = vi.fn();
+ const utilities = loadSSEUtilities();
+ const downloadAllAsText = compileTextDownload({
+ showDownloadProgressModal: vi.fn(),
+ updateTextExtractionProgress: vi.fn(),
+ handleSSECompletion: utilities.handleSSECompletion,
+ });
+
+ await downloadAllAsText();
+ event.target = button.querySelector('span');
+ await downloadAllAsText();
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(window.closeProgressModal).toHaveBeenCalledOnce();
+ expect(alertMock).toHaveBeenCalledOnce();
+ expect(alertMock).toHaveBeenCalledWith(
+ 'Text extraction complete! Extracted 10 documents to encrypted database.',
+ );
+ expect(alertMock).not.toHaveBeenCalledWith(
+ 'Text extraction complete! Extracted 7 documents to encrypted database.',
+ );
+});
diff --git a/tests/js/pages/link-analytics-bootstrap-runtime.test.js b/tests/js/pages/link-analytics-bootstrap-runtime.test.js
new file mode 100644
index 0000000000..b3ddfdbe86
--- /dev/null
+++ b/tests/js/pages/link-analytics-bootstrap-runtime.test.js
@@ -0,0 +1,109 @@
+/** Browser-order contract for the checked-in Link Analytics template. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/link_analytics.html',
+);
+const RENDER_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/link_analytics_render.js',
+);
+const TEMPLATE_SOURCE = readFileSync(TEMPLATE_PATH, 'utf8');
+const RENDER_SOURCE = readFileSync(RENDER_PATH, 'utf8');
+
+function extractInlineBootstrap() {
+ const match = TEMPLATE_SOURCE.match(
+ /<script>\s*(let topDomainsChart[\s\S]*?)<\/script>/,
+ );
+ if (!match) throw new Error('Link Analytics inline bootstrap not found');
+ return match[1];
+}
+
+function jsonResponse(payload) {
+ return {
+ ok: true,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.URLValidator;
+ delete window.updateEnhancedDomainList;
+ delete window.escapeHtml;
+});
+
+it('safely completes the eager initial render before the deferred global escaper loads', async () => {
+ delete window.escapeHtml;
+ window.URLValidator = { isSafeUrl: vi.fn(() => true) };
+ // Scripts inserted through innerHTML remain inert; execute them below in
+ // their production order while retaining the template's real DOM.
+ // eslint-disable-next-line no-unsanitized/property -- repository-owned template fixture.
+ document.body.innerHTML = TEMPLATE_SOURCE;
+ vi.spyOn(window.HTMLCanvasElement.prototype, 'getContext')
+ .mockReturnValue({});
+
+ const payload = '<img src=x onerror="window.__linkAnalyticsXss=true">';
+ const fetchMock = vi.fn((url) => {
+ if (url === '/metrics/api/link-analytics?period=30d') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ data: {
+ total_links: 1,
+ total_unique_domains: 1,
+ avg_links_per_research: 1,
+ total_researches: 1,
+ domain_categories: { [payload]: 1 },
+ top_domains: [{
+ domain: 'safe.example.com',
+ count: 1,
+ percentage: 100,
+ recent_researches: [{ id: 'run-3299', query: payload }],
+ }],
+ domain_distribution: { top_10: 1, others: 0 },
+ temporal_trend: [],
+ domain_metrics: {},
+ },
+ }));
+ }
+ if (url === '/metrics/api/domain-classifications') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ classifications: [],
+ }));
+ }
+ throw new Error(`Unexpected Link Analytics request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const ChartStub = vi.fn(function() {
+ this.destroy = vi.fn();
+ });
+
+ // Repository-owned production scripts only; no user-controlled source.
+ new Function(RENDER_SOURCE)(); // eslint-disable-line no-new-func
+ new Function('Chart', extractInlineBootstrap())(ChartStub); // eslint-disable-line no-new-func
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('content').style.display).toBe('block');
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/link-analytics?period=30d',
+ '/metrics/api/domain-classifications',
+ ]);
+ expect(window.escapeHtml).toBeUndefined();
+ expect(document.getElementById('error').style.display).not.toBe('block');
+ expect(document.querySelector('#domain-category-grid img')).toBeNull();
+ expect(document.querySelector('#domain-list img')).toBeNull();
+ expect(document.querySelector('#domain-category-grid .ldr-category-name')
+ .textContent).toBe(payload);
+ expect(document.querySelector('#domain-list .ldr-research-link').textContent.trim())
+ .toBe(payload.substring(0, 30) + '...');
+ expect(window.__linkAnalyticsXss).toBeUndefined();
+});
diff --git a/tests/js/pages/link-analytics-classification-runtime.test.js b/tests/js/pages/link-analytics-classification-runtime.test.js
new file mode 100644
index 0000000000..b53917ccea
--- /dev/null
+++ b/tests/js/pages/link-analytics-classification-runtime.test.js
@@ -0,0 +1,510 @@
+/**
+ * Browser contracts for the domain-classification workflow embedded in
+ * link_analytics.html. The harness compiles the checked-in template functions
+ * so endpoint, response-shape, CSRF, sequencing, and lifecycle assertions stay
+ * tied to the code shipped to the browser.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/link_analytics.html',
+);
+const PROGRESS_URL = '/metrics/api/domain-classifications/progress';
+const CLASSIFICATIONS_URL = '/metrics/api/domain-classifications';
+const CLASSIFY_URL = '/metrics/api/domain-classifications/classify';
+
+function jsonResponse(payload, { ok = true, status = 200, text = '' } = {}) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ text: vi.fn().mockResolvedValue(text),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+function mountClassificationUi() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-link">';
+ document.body.innerHTML = `
+ <button id="start-classification">Start</button>
+ <button id="stop-classification">Stop</button>
+ <input id="force-reclassify" type="checkbox">
+ <section id="classification-info" style="display: block"></section>
+ <section id="classification-progress" style="display: none">
+ <div id="progress-fill" style="width: 0%">0%</div>
+ <span id="current-domain"></span>
+ <div id="classification-log"></div>
+ </section>
+ <section id="classification-complete" style="display: none">
+ <span id="final-classified">0</span>
+ </section>
+ <span id="total-domains-count">0</span>
+ <span id="classified-count">0</span>
+ <span id="classification-status"></span>
+ `;
+}
+
+function extractStartRegistration() {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const registration = template.match(
+ /^\s*startBtn\.addEventListener\(\s*['"]click['"]\s*,\s*startDomainClassification\s*\);\s*$/m,
+ );
+ if (!registration) {
+ throw new Error('start-classification click registration not found');
+ }
+ return registration[0];
+}
+
+function extractStopRegistration() {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const registration = template.match(
+ /(stopBtn\.addEventListener\('click', \(\) => \{[\s\S]*?\n\}\);)/,
+ );
+ if (!registration) {
+ throw new Error('stop-classification click registration not found');
+ }
+ return registration[1];
+}
+
+function compileClassificationRuntime(delay = (callback) => callback()) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'loadClassificationProgress',
+ 'startDomainClassification',
+ 'classifyAllDomains',
+ 'addLogEntry',
+ 'showClassificationComplete',
+ ],
+ dependencies: { setTimeout: delay },
+ preamble: `
+ let classificationInProgress = false;
+ let domainsToClassify = [];
+ let classificationRunId = 0;
+ let classificationAbortController = null;
+ const startBtn = document.getElementById('start-classification');
+ const stopBtn = document.getElementById('stop-classification');
+ ${extractStartRegistration()}
+ ${extractStopRegistration()}
+ `,
+ returnExpression: `({
+ loadClassificationProgress,
+ startDomainClassification,
+ getClassificationInProgress: () => classificationInProgress,
+ getDomainsToClassify: () => domainsToClassify,
+ })`,
+ });
+}
+
+beforeEach(() => {
+ mountClassificationUi();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('loads the progress envelope and renders its counts', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 12, classified: 7 },
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime();
+
+ await runtime.loadClassificationProgress();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(PROGRESS_URL);
+ expect(document.getElementById('total-domains-count').textContent).toBe('12');
+ expect(document.getElementById('classified-count').textContent).toBe('7');
+ expect(document.getElementById('classification-status').textContent)
+ .toBe('7/12 domains classified');
+});
+
+it('classifies unhandled domains sequentially with CSRF and completes the UI', async () => {
+ const delay = vi.fn((callback) => callback());
+ const postSnapshots = [];
+ let progressCalls = 0;
+ const fetchMock = vi.fn((url, options) => {
+ if (url === PROGRESS_URL) {
+ progressCalls += 1;
+ if (progressCalls === 1) {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 3, classified: 1 },
+ }));
+ }
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ progress: {
+ all_domains: ['known.test', 'alpha.test', 'beta.test'],
+ },
+ }));
+ }
+ if (url === CLASSIFICATIONS_URL) {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ classifications: [{ domain: 'known.test' }],
+ }));
+ }
+ if (url === CLASSIFY_URL) {
+ const body = JSON.parse(options.body);
+ postSnapshots.push({
+ domain: body.domain,
+ progress: document.getElementById('progress-fill').textContent,
+ current: document.getElementById('current-domain').textContent,
+ });
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ classification: {
+ category: 'Research',
+ subcategory: body.domain === 'alpha.test' ? 'Journal' : 'Index',
+ },
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime(delay);
+
+ await runtime.startDomainClassification();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ PROGRESS_URL,
+ PROGRESS_URL,
+ CLASSIFICATIONS_URL,
+ CLASSIFY_URL,
+ CLASSIFY_URL,
+ ]);
+ const postOptions = fetchMock.mock.calls
+ .filter(([url]) => url === CLASSIFY_URL)
+ .map(([, options]) => options);
+ expect(postOptions).toHaveLength(2);
+ postOptions.forEach((options, index) => {
+ expect(options).toEqual({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-link',
+ },
+ credentials: 'same-origin',
+ signal: expect.anything(),
+ body: JSON.stringify({
+ domain: index === 0 ? 'alpha.test' : 'beta.test',
+ force_update: false,
+ }),
+ });
+ });
+ expect(postSnapshots).toEqual([
+ {
+ domain: 'alpha.test',
+ progress: '50%',
+ current: 'Classifying: alpha.test',
+ },
+ {
+ domain: 'beta.test',
+ progress: '100%',
+ current: 'Classifying: beta.test',
+ },
+ ]);
+ expect(delay).toHaveBeenCalledTimes(2);
+ expect(delay.mock.calls.every(([, milliseconds]) => milliseconds === 1000))
+ .toBe(true);
+ expect(runtime.getDomainsToClassify()).toEqual(['alpha.test', 'beta.test']);
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(document.getElementById('start-classification').disabled).toBe(false);
+ expect(document.getElementById('classification-progress').style.display)
+ .toBe('none');
+ expect(document.getElementById('classification-complete').style.display)
+ .toBe('block');
+ expect(document.getElementById('final-classified').textContent).toBe('2');
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('✓ alpha.test: Research / Journal');
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('✓ beta.test: Research / Index');
+});
+
+it('continues after an HTTP failure and reports only successful classifications', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const delay = vi.fn((callback) => callback());
+ let progressCalls = 0;
+ const postedDomains = [];
+ const fetchMock = vi.fn((url, options) => {
+ if (url === PROGRESS_URL) {
+ progressCalls += 1;
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ progress: progressCalls === 1
+ ? { total_domains: 2, classified: 0 }
+ : { all_domains: ['unavailable.test', 'healthy.test'] },
+ }));
+ }
+ if (url === CLASSIFICATIONS_URL) {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ classifications: [],
+ }));
+ }
+ if (url === CLASSIFY_URL) {
+ const { domain } = JSON.parse(options.body);
+ postedDomains.push(domain);
+ if (domain === 'unavailable.test') {
+ return Promise.resolve(jsonResponse({}, {
+ ok: false,
+ status: 503,
+ text: 'classifier unavailable',
+ }));
+ }
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ classification: { category: 'News', subcategory: 'Publisher' },
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime(delay);
+
+ await runtime.startDomainClassification();
+
+ expect(postedDomains).toEqual(['unavailable.test', 'healthy.test']);
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'HTTP error! status: 503, body: classifier unavailable',
+ );
+ expect(delay).toHaveBeenCalledOnce();
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('✗ unavailable.test: HTTP 503 error');
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('✓ healthy.test: News / Publisher');
+ expect(document.getElementById('final-classified').textContent).toBe('1');
+ expect(runtime.getClassificationInProgress()).toBe(false);
+});
+
+it('uses the checked-in click registration and restores retry after rejection', async () => {
+ const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ const firstProgress = deferred();
+ const fetchMock = vi.fn().mockImplementation(() => firstProgress.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime();
+ const startButton = document.getElementById('start-classification');
+
+ startButton.click();
+ startButton.dispatchEvent(new MouseEvent('click'));
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(runtime.getClassificationInProgress()).toBe(true);
+ expect(startButton.disabled).toBe(true);
+
+ firstProgress.reject(new Error('temporarily offline'));
+ await vi.waitFor(() => {
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ });
+
+ expect(errorSpy).toHaveBeenCalledWith(
+ 'Error starting classification:',
+ expect.objectContaining({ message: 'temporarily offline' }),
+ );
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(startButton.disabled).toBe(false);
+ expect(document.getElementById('classification-info').style.display)
+ .toBe('block');
+ expect(document.getElementById('classification-progress').style.display)
+ .toBe('none');
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('Error: temporarily offline');
+
+ fetchMock.mockReset();
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 1, classified: 1 },
+ }))
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { all_domains: ['known.test'] },
+ }))
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ classifications: [{ domain: 'known.test' }],
+ }));
+
+ startButton.click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('classification-complete').style.display)
+ .toBe('block');
+ });
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ PROGRESS_URL,
+ PROGRESS_URL,
+ CLASSIFICATIONS_URL,
+ ]);
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('All domains are already classified!');
+ expect(document.getElementById('classification-complete').style.display)
+ .toBe('block');
+ expect(Number(document.getElementById('final-classified').textContent)).toBe(0);
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(startButton.disabled).toBe(false);
+});
+
+it('uses the real stop control to retire a deferred classification run', async () => {
+ const domainsResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 2, classified: 0 },
+ }))
+ .mockImplementationOnce(() => domainsResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime();
+ const startButton = document.getElementById('start-classification');
+ const stopButton = document.getElementById('stop-classification');
+
+ const run = runtime.startDomainClassification();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ const deferredSignal = fetchMock.mock.calls[1][1].signal;
+ stopButton.click();
+
+ expect(deferredSignal.aborted).toBe(true);
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(startButton.disabled).toBe(false);
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('Classification stopped by user');
+
+ domainsResponse.resolve(jsonResponse({
+ status: 'success',
+ progress: { all_domains: ['stale.test'] },
+ }));
+ await run;
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(document.getElementById('classification-log').textContent)
+ .toContain('Classification stopped by user');
+ expect(document.getElementById('classification-log').textContent)
+ .not.toContain('Starting classification');
+ expect(document.getElementById('classification-complete').style.display)
+ .toBe('none');
+});
+
+it.each([
+ {
+ label: 'HTTP failure',
+ classificationsResponse: jsonResponse({}, {
+ ok: false,
+ status: 503,
+ text: 'unavailable',
+ }),
+ expectedMessage: 'Unable to load existing classifications (HTTP 503)',
+ },
+ {
+ label: 'error envelope',
+ classificationsResponse: jsonResponse({
+ status: 'error',
+ message: 'classification index unavailable',
+ }),
+ expectedMessage: 'classification index unavailable',
+ },
+])('does not classify every domain after a lookup $label', async ({
+ classificationsResponse,
+ expectedMessage,
+}) => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 1, classified: 0 },
+ }))
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { all_domains: ['must-not-post.test'] },
+ }))
+ .mockResolvedValueOnce(classificationsResponse);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime();
+
+ await runtime.startDomainClassification();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ PROGRESS_URL,
+ PROGRESS_URL,
+ CLASSIFICATIONS_URL,
+ ]);
+ expect(fetchMock).not.toHaveBeenCalledWith(
+ CLASSIFY_URL,
+ expect.anything(),
+ );
+ expect(document.getElementById('classification-log').textContent)
+ .toContain(`Fatal error: ${expectedMessage}`);
+ expect(document.getElementById('classification-log').textContent)
+ .toContain(`Error: ${expectedMessage}`);
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(document.getElementById('start-classification').disabled).toBe(false);
+ expect(document.getElementById('classification-info').style.display)
+ .toBe('block');
+});
+
+it.each([
+ {
+ failure: 'rejects',
+ secondProgress: () => Promise.reject(new Error('refresh offline')),
+ message: 'refresh offline',
+ },
+ {
+ failure: 'returns an error envelope',
+ secondProgress: () => Promise.resolve(jsonResponse({
+ status: 'error',
+ message: 'progress unavailable',
+ })),
+ message: 'progress unavailable',
+ },
+])('restores retry controls when the classification progress refresh $failure', async ({
+ secondProgress,
+ message,
+}) => {
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ status: 'success',
+ progress: { total_domains: 2, classified: 0 },
+ }))
+ .mockImplementationOnce(secondProgress);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileClassificationRuntime();
+ const startButton = document.getElementById('start-classification');
+
+ await runtime.startDomainClassification();
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ PROGRESS_URL,
+ PROGRESS_URL,
+ ]);
+ expect(runtime.getClassificationInProgress()).toBe(false);
+ expect(startButton.disabled).toBe(false);
+ expect(document.getElementById('classification-info').style.display)
+ .toBe('block');
+ expect(document.getElementById('classification-progress').style.display)
+ .toBe('none');
+ expect(document.getElementById('classification-log').textContent)
+ .toContain(`Fatal error: ${message}`);
+ expect(document.getElementById('classification-log').textContent)
+ .toContain(`Error: ${message}`);
+});
diff --git a/tests/js/pages/link-analytics-xss.test.js b/tests/js/pages/link-analytics-xss.test.js
index bd929a7e01..2cf6be7c14 100644
--- a/tests/js/pages/link-analytics-xss.test.js
+++ b/tests/js/pages/link-analytics-xss.test.js
@@ -145,6 +145,38 @@ describe('pages/link_analytics_render.js — XSS regression for PR #3095', () =>
expect(href.toLowerCase()).not.toContain('javascript:');
});
+ it('falls back to a non-navigating href when URLValidator rejects the domain', () => {
+ const originalValidator = window.URLValidator;
+ const validator = { isSafeUrl: vi.fn(() => false) };
+ const warnSpy = vi.spyOn(window.SafeLogger, 'warn');
+ window.URLValidator = validator;
+
+ try {
+ window.updateEnhancedDomainList([{
+ domain: 'rejected.example.com',
+ count: 1,
+ recent_researches: [],
+ }], {});
+
+ const link = document.querySelector('#domain-list .ldr-domain-name a');
+ expect(validator.isSafeUrl).toHaveBeenCalledWith(
+ 'https://rejected.example.com'
+ );
+ expect(link.getAttribute('href')).toBe('#');
+ expect(warnSpy).toHaveBeenCalledWith(
+ 'link_analytics: rejected unsafe external href for domain',
+ 'rejected.example.com'
+ );
+ } finally {
+ if (originalValidator === undefined) {
+ delete window.URLValidator;
+ } else {
+ window.URLValidator = originalValidator;
+ }
+ warnSpy.mockRestore();
+ }
+ });
+
it('escapeHtml-encodes classification category/subcategory and Number()-coerces confidence', () => {
// Quote in subcategory tests attribute containment on the badge title.
const ATTR_BREAKOUT = `" tiles="evil`;
@@ -222,6 +254,25 @@ describe('pages/link_analytics_render.js — XSS regression for PR #3095', () =>
expect(html).toContain('(90% confidence)');
});
+ it('links recent research to the encoded FastAPI results route', () => {
+ const domains = [{
+ domain: 'example.com',
+ count: 1,
+ recent_researches: [{
+ id: 'run/with spaces?#fragment',
+ query: 'A recent research run',
+ }],
+ }];
+
+ window.updateEnhancedDomainList(domains, {});
+
+ const link = document.querySelector('#domain-list .ldr-research-link');
+ expect(link).not.toBeNull();
+ expect(link.getAttribute('href')).toBe(
+ '/results/run%2Fwith%20spaces%3F%23fragment'
+ );
+ });
+
it('renders the empty-list fallback when domains is []', () => {
window.updateEnhancedDomainList([], {});
diff --git a/tests/js/pages/metrics-dashboard-runtime.test.js b/tests/js/pages/metrics-dashboard-runtime.test.js
new file mode 100644
index 0000000000..b8875a3135
--- /dev/null
+++ b/tests/js/pages/metrics-dashboard-runtime.test.js
@@ -0,0 +1,502 @@
+/**
+ * Runtime contracts for the metrics dashboard's inline FastAPI consumers.
+ */
+
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/metrics.html',
+);
+
+function renderLoadingStates() {
+ document.body.innerHTML = `
+ <div id="loading" style="display: none"></div>
+ <div id="metrics-content" style="display: block"></div>
+ <div id="error" style="display: none"></div>
+ `;
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolveValue, rejectError) => {
+ resolvePromise = resolveValue;
+ rejectPromise = rejectError;
+ });
+ return { promise, reject: rejectPromise, resolve: resolvePromise };
+}
+
+function loaderDependencies() {
+ return {
+ displayMetrics: vi.fn(),
+ displayEnhancedMetrics: vi.fn(),
+ createTimeSeriesChart: vi.fn(),
+ createSearchActivityChart: vi.fn(),
+ setupTooltipPositioning: vi.fn(),
+ loadCostAnalytics: vi.fn(),
+ loadRateLimitingAnalytics: vi.fn(),
+ showEmptyState: vi.fn(),
+ showError: vi.fn(),
+ };
+}
+
+function compileMetricsLoader(dependencies, mode = 'detailed') {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'loadMetrics',
+ 'handleTimeRangeChange',
+ 'handleResearchModeChange',
+ ],
+ dependencies,
+ preamble: `
+ let currentPeriod = '30d';
+ let currentMode = ${JSON.stringify(mode)};
+ let metricsRequestId = 0;
+ let metricsData = null;
+ `,
+ returnExpression: `({
+ loadMetrics,
+ handleTimeRangeChange,
+ handleResearchModeChange,
+ getMetricsData: () => metricsData,
+ })`,
+ });
+}
+
+function compileMetricsFanOut(dependencies) {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: [
+ 'loadMetrics',
+ 'loadCostAnalytics',
+ 'loadRateLimitingAnalytics',
+ 'handleTimeRangeChange',
+ ],
+ dependencies,
+ preamble: `
+ let currentPeriod = '30d';
+ let currentMode = 'all';
+ let metricsRequestId = 0;
+ let metricsData = null;
+ `,
+ returnExpression: `({
+ loadMetrics,
+ handleTimeRangeChange,
+ getMetricsData: () => metricsData,
+ })`,
+ });
+}
+
+function basicMetrics(overrides = {}) {
+ return {
+ total_tokens: 10,
+ total_researches: 1,
+ by_model: [],
+ recent_researches: [],
+ ...overrides,
+ };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('loads basic and enhanced metrics with the selected period and mode', async () => {
+ renderLoadingStates();
+ const metrics = basicMetrics();
+ const enhanced = {
+ performance_stats: {},
+ time_series_data: [{ date: '2026-08-31', tokens: 10 }],
+ search_time_series: [{ date: '2026-08-31', searches: 2 }],
+ };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'success', metrics }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: enhanced,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = loaderDependencies();
+ const harness = compileMetricsLoader(dependencies);
+
+ await harness.loadMetrics('90d');
+
+ expect(fetchMock.mock.calls.map(call => call[0])).toEqual([
+ '/metrics/api/metrics?period=90d&mode=detailed',
+ '/metrics/api/metrics/enhanced?period=90d&mode=detailed',
+ ]);
+ expect(harness.getMetricsData()).toEqual(metrics);
+ expect(dependencies.displayMetrics).toHaveBeenCalledOnce();
+ expect(dependencies.displayEnhancedMetrics).toHaveBeenCalledWith(enhanced);
+ expect(dependencies.createTimeSeriesChart)
+ .toHaveBeenCalledWith(enhanced.time_series_data);
+ expect(dependencies.createSearchActivityChart)
+ .toHaveBeenCalledWith(enhanced.search_time_series);
+ expect(dependencies.loadCostAnalytics).toHaveBeenCalledWith('90d', 1);
+ expect(dependencies.loadRateLimitingAnalytics).toHaveBeenCalledWith(
+ '90d',
+ 1,
+ );
+ expect(document.getElementById('loading').style.display).toBe('none');
+ expect(document.getElementById('metrics-content').style.display)
+ .toBe('block');
+});
+
+it('uses the empty-state contract without requesting secondary analytics', async () => {
+ renderLoadingStates();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: basicMetrics({
+ total_tokens: 0,
+ total_researches: 0,
+ }),
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: { time_series_data: [], search_time_series: [] },
+ }),
+ }));
+ const dependencies = loaderDependencies();
+
+ await compileMetricsLoader(dependencies, 'all').loadMetrics('7d');
+
+ expect(dependencies.showEmptyState).toHaveBeenCalledOnce();
+ expect(dependencies.displayMetrics).not.toHaveBeenCalled();
+ expect(dependencies.displayEnhancedMetrics).toHaveBeenCalledOnce();
+ expect(dependencies.loadCostAnalytics).not.toHaveBeenCalled();
+ expect(dependencies.loadRateLimitingAnalytics).not.toHaveBeenCalled();
+ expect(dependencies.showError).not.toHaveBeenCalled();
+});
+
+it('shows the dashboard error state when either primary response is not OK', async () => {
+ renderLoadingStates();
+ const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 503 });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = loaderDependencies();
+
+ await compileMetricsLoader(dependencies).loadMetrics('30d');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(dependencies.showError).toHaveBeenCalledOnce();
+ expect(dependencies.displayMetrics).not.toHaveBeenCalled();
+});
+
+it('keeps period and research-mode selectors aligned with loader arguments', () => {
+ document.body.innerHTML = `
+ <button data-period="7d" class="active"></button>
+ <button data-period="90d"></button>
+ <button data-mode="all" class="active"></button>
+ <button data-mode="quick"></button>
+ `;
+ const loadMetrics = vi.fn();
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['handleTimeRangeChange', 'handleResearchModeChange'],
+ dependencies: { loadMetrics },
+ preamble: `
+ let currentPeriod = '7d';
+ let currentMode = 'all';
+ `,
+ returnExpression: `({
+ handleTimeRangeChange,
+ handleResearchModeChange,
+ })`,
+ });
+
+ harness.handleTimeRangeChange('90d');
+ harness.handleResearchModeChange('quick');
+
+ expect(document.querySelector('[data-period="7d"]').classList)
+ .not.toContain('active');
+ expect(document.querySelector('[data-period="90d"]').classList)
+ .toContain('active');
+ expect(document.querySelector('[data-mode="all"]').classList)
+ .not.toContain('active');
+ expect(document.querySelector('[data-mode="quick"]').classList)
+ .toContain('active');
+ expect(loadMetrics).toHaveBeenNthCalledWith(1, '90d');
+ expect(loadMetrics).toHaveBeenNthCalledWith(2, '90d');
+});
+
+it('keeps a mode change authoritative while the older basic body is pending', async () => {
+ renderLoadingStates();
+ document.body.insertAdjacentHTML('beforeend', `
+ <button data-mode="all" class="active"></button>
+ <button data-mode="quick"></button>
+ `);
+ const olderBasicBody = deferred();
+ const olderBasicResponse = {
+ ok: true,
+ json: vi.fn(() => olderBasicBody.promise),
+ };
+ const currentMetrics = basicMetrics({ total_tokens: 70 });
+ const currentEnhanced = {
+ performance_stats: { average_duration: 7 },
+ time_series_data: [],
+ search_time_series: [],
+ };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(olderBasicResponse)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: currentMetrics,
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: currentEnhanced,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = loaderDependencies();
+ const runtime = compileMetricsLoader(dependencies, 'all');
+
+ const olderLoad = runtime.loadMetrics('30d');
+ await vi.waitFor(() => {
+ expect(olderBasicResponse.json).toHaveBeenCalledOnce();
+ });
+
+ runtime.handleResearchModeChange('quick');
+ await vi.waitFor(() => {
+ expect(runtime.getMetricsData()).toEqual(currentMetrics);
+ });
+
+ olderBasicBody.resolve({
+ status: 'success',
+ metrics: basicMetrics({ total_tokens: 30 }),
+ });
+ await olderLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/metrics?period=30d&mode=all',
+ '/metrics/api/metrics?period=30d&mode=quick',
+ '/metrics/api/metrics/enhanced?period=30d&mode=quick',
+ ]);
+ expect(document.querySelector('[data-mode="all"]').classList)
+ .not.toContain('active');
+ expect(document.querySelector('[data-mode="quick"]').classList)
+ .toContain('active');
+ expect(dependencies.displayMetrics).toHaveBeenCalledOnce();
+ expect(dependencies.displayEnhancedMetrics)
+ .toHaveBeenCalledWith(currentEnhanced);
+ expect(dependencies.showError).not.toHaveBeenCalled();
+});
+
+it('ignores an older rejected request after a period handler starts a new load', async () => {
+ renderLoadingStates();
+ document.body.insertAdjacentHTML('beforeend', `
+ <button data-period="30d" class="active"></button>
+ <button data-period="7d"></button>
+ `);
+ const olderResponse = deferred();
+ const currentMetrics = basicMetrics({ total_tokens: 7 });
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: currentMetrics,
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: {
+ performance_stats: {},
+ time_series_data: [],
+ search_time_series: [],
+ },
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = loaderDependencies();
+ const runtime = compileMetricsLoader(dependencies, 'all');
+
+ const olderLoad = runtime.loadMetrics('30d');
+ runtime.handleTimeRangeChange('7d');
+ await vi.waitFor(() => {
+ expect(runtime.getMetricsData()).toEqual(currentMetrics);
+ });
+
+ olderResponse.reject(new Error('late network failure'));
+ await olderLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/metrics/api/metrics?period=30d&mode=all',
+ '/metrics/api/metrics?period=7d&mode=all',
+ '/metrics/api/metrics/enhanced?period=7d&mode=all',
+ ]);
+ expect(document.querySelector('[data-period="30d"]').classList)
+ .not.toContain('active');
+ expect(document.querySelector('[data-period="7d"]').classList)
+ .toContain('active');
+ expect(dependencies.showError).not.toHaveBeenCalled();
+ expect(document.getElementById('metrics-content').style.display)
+ .toBe('block');
+});
+
+it('prevents stale secondary fan-out success and failure from replacing a newer period', async () => {
+ renderLoadingStates();
+ document.body.insertAdjacentHTML('beforeend', `
+ <button data-period="30d" class="active"></button>
+ <button data-period="7d"></button>
+ `);
+ const olderCost = deferred();
+ const olderRate = deferred();
+ const currentCost = { status: 'success', overview: { total_cost: 7 } };
+ const currentRate = {
+ status: 'success',
+ data: { rate_limiting: { total_engines_tracked: 7 } },
+ };
+ const primaryResponse = totalTokens => ({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: basicMetrics({ total_tokens: totalTokens }),
+ }),
+ });
+ const enhancedResponse = {
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ metrics: {
+ performance_stats: {},
+ time_series_data: [],
+ search_time_series: [],
+ },
+ }),
+ };
+ const fetchMock = vi.fn(url => {
+ if (url === '/metrics/api/cost-analytics?period=30d') {
+ return olderCost.promise;
+ }
+ if (url === '/metrics/api/rate-limiting?period=30d') {
+ return olderRate.promise;
+ }
+ if (url === '/metrics/api/cost-analytics?period=7d') {
+ return Promise.resolve(new Response(JSON.stringify(currentCost)));
+ }
+ if (url === '/metrics/api/rate-limiting?period=7d') {
+ return Promise.resolve(new Response(JSON.stringify(currentRate)));
+ }
+ if (url.includes('/enhanced?')) return Promise.resolve(enhancedResponse);
+ return Promise.resolve(primaryResponse(url.includes('period=7d') ? 7 : 30));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = {
+ ...loaderDependencies(),
+ displayCostData: vi.fn(),
+ displayRateLimitingData: vi.fn(),
+ };
+ delete dependencies.loadCostAnalytics;
+ delete dependencies.loadRateLimitingAnalytics;
+ const runtime = compileMetricsFanOut(dependencies);
+
+ await runtime.loadMetrics('30d');
+ runtime.handleTimeRangeChange('7d');
+ await vi.waitFor(() => {
+ expect(dependencies.displayCostData).toHaveBeenCalledWith(currentCost);
+ expect(dependencies.displayRateLimitingData).toHaveBeenCalledWith(
+ currentRate.data,
+ );
+ });
+
+ olderCost.resolve(new Response(JSON.stringify({
+ status: 'success',
+ overview: { total_cost: 30 },
+ })));
+ olderRate.reject(new Error('late rate failure'));
+ await new Promise(resolvePromise => setTimeout(resolvePromise, 0));
+
+ expect(dependencies.displayCostData).toHaveBeenCalledOnce();
+ expect(dependencies.displayRateLimitingData).toHaveBeenCalledOnce();
+ expect(runtime.getMetricsData()).toEqual(basicMetrics({ total_tokens: 7 }));
+ expect(dependencies.showError).not.toHaveBeenCalled();
+});
+
+it('unwraps the cost and rate-limiting response envelopes', async () => {
+ const displayCostData = vi.fn();
+ const displayRateLimitingData = vi.fn();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ overview: { total_cost: 1.25 },
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ data: { rate_limiting: { total_engines_tracked: 2 } },
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadCostAnalytics', 'loadRateLimitingAnalytics'],
+ dependencies: { displayCostData, displayRateLimitingData },
+ preamble: "let currentPeriod = '30d'; let metricsRequestId = 0;",
+ returnExpression: '({ loadCostAnalytics, loadRateLimitingAnalytics })',
+ });
+
+ await harness.loadCostAnalytics('7d');
+ await harness.loadRateLimitingAnalytics('90d');
+
+ expect(fetchMock.mock.calls.map(call => call[0])).toEqual([
+ '/metrics/api/cost-analytics?period=7d',
+ '/metrics/api/rate-limiting?period=90d',
+ ]);
+ expect(displayCostData).toHaveBeenCalledWith({
+ status: 'success',
+ overview: { total_cost: 1.25 },
+ });
+ expect(displayRateLimitingData).toHaveBeenCalledWith({
+ rate_limiting: { total_engines_tracked: 2 },
+ });
+});
+
+it('renders unavailable secondary analytics on HTTP and network failures', async () => {
+ const displayCostData = vi.fn();
+ const displayRateLimitingData = vi.fn();
+ vi.stubGlobal('fetch', vi.fn()
+ .mockResolvedValueOnce({ ok: false })
+ .mockRejectedValueOnce(new Error('offline')));
+ const harness = compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadCostAnalytics', 'loadRateLimitingAnalytics'],
+ dependencies: { displayCostData, displayRateLimitingData },
+ preamble: "let currentPeriod = '30d'; let metricsRequestId = 0;",
+ returnExpression: '({ loadCostAnalytics, loadRateLimitingAnalytics })',
+ });
+
+ await harness.loadCostAnalytics();
+ await harness.loadRateLimitingAnalytics();
+
+ expect(displayCostData).toHaveBeenCalledWith(null);
+ expect(displayRateLimitingData).toHaveBeenCalledWith(null);
+});
diff --git a/tests/js/pages/news-actions-direct-runtime.test.js b/tests/js/pages/news-actions-direct-runtime.test.js
new file mode 100644
index 0000000000..bf7d68a0f1
--- /dev/null
+++ b/tests/js/pages/news-actions-direct-runtime.test.js
@@ -0,0 +1,1342 @@
+/** Direct browser-runtime coverage for feed state and user actions in news.js. */
+
+import DOMPurify from 'dompurify';
+
+const NOW = new Date('2026-09-01T12:00:00.000Z');
+
+function response(payload, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ headers: {},
+ json: vi.fn().mockResolvedValue(payload),
+ text: vi.fn().mockResolvedValue(JSON.stringify(payload)),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+function installDom() {
+ document.body.innerHTML = `
+ <header class="ldr-feed-header"><h2>News</h2></header>
+ <section id="news-feed-content"></section>
+ <input id="table-view-toggle" type="checkbox">
+ <input id="news-search" type="search">
+ <button id="search-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <input id="impact-filter" type="range" min="0" max="10" value="0">
+ <span class="ldr-impact-value">0+</span>
+ <span class="ldr-slider-value">0</span>
+ <section id="news-semantic-results" style="display: none"></section>
+ <input id="news-query">
+ <form id="news-search-form"></form>
+ <div id="newsSubscriptionModal">
+ <form id="news-subscription-form">
+ <textarea id="news-subscription-query"></textarea>
+ <input id="news-subscription-name">
+ <select id="news-subscription-frequency">
+ <option value="4">Every 4 hours</option>
+ </select>
+ <select id="news-subscription-folder">
+ <option value="">Uncategorized</option>
+ </select>
+ <input id="news-subscription-active" type="checkbox" checked>
+ <input id="news-subscription-run-now" type="checkbox">
+ <input id="news-subscription-model">
+ <select id="news-subscription-strategy">
+ <option value="source-based">Source based</option>
+ </select>
+ <button id="run-template-btn" type="button"></button>
+ <button type="submit">Create</button>
+ </form>
+ </div>
+ <div class="ldr-time-filter-group">
+ <button class="ldr-filter-btn active" data-time="all"></button>
+ <button class="ldr-filter-btn" data-time="today"></button>
+ <button class="ldr-filter-btn" data-time="week"></button>
+ </div>
+ <input id="auto-refresh" type="checkbox">
+ <label for="auto-refresh">Auto-refresh</label>
+ <button id="refresh-feed-btn"><i></i></button>
+ <div id="recent-searches"></div>
+ <div id="trending-topics"></div>
+ <div id="priority-status" style="display: none"><span id="priority-message"></span></div>
+ <div id="news-alert" style="display: none"></div>
+ <button id="news-search-mode-btn"></button>
+ <div id="news-search-mode-menu">
+ <a class="dropdown-item active" data-mode="hybrid"></a>
+ <a class="dropdown-item" data-mode="text"></a>
+ <a class="dropdown-item" data-mode="semantic"></a>
+ </div>
+ <section id="query-template" style="display: none">
+ <pre class="ldr-template-content"></pre>
+ </section>
+ `;
+}
+
+let fetchMock;
+let feedItems;
+let searchHistory;
+let clipboardWrite;
+let createdBlob;
+let downloadedFilename;
+let bootstrapSnapshot;
+
+function setReadState(newsId, shouldBeRead) {
+ const card = document.querySelector(`[data-news-id="${newsId}"]`);
+ const isRead = card?.classList.contains('ldr-is-read') ?? false;
+ if (isRead !== shouldBeRead) window.toggleReadStatus(newsId);
+}
+
+function setSavedState(newsId, shouldBeSaved) {
+ const savedIds = JSON.parse(
+ localStorage.getItem('saved_news_ids') || '[]',
+ );
+ if (savedIds.includes(newsId) !== shouldBeSaved) {
+ window.toggleSaveItem(newsId);
+ }
+}
+
+async function restoreAllFeed() {
+ history.replaceState({}, '', '/');
+ document.getElementById('news-search').value = '';
+
+ const tableToggle = document.getElementById('table-view-toggle');
+ if (tableToggle.checked) {
+ tableToggle.checked = false;
+ tableToggle.dispatchEvent(new Event('change'));
+ }
+
+ window.clearAllFilters();
+ await window.selectSubscription('all');
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ });
+}
+
+async function renderSecondNewsLinks(sourceUrl, linkUrl = sourceUrl) {
+ const originalFetch = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation((input, options = {}) => {
+ if (String(input).startsWith('/news/api/feed?')) {
+ return Promise.resolve(response({
+ news_items: feedItems.map(item => (
+ item.id === 'news-two'
+ ? {
+ ...item,
+ source_url: sourceUrl,
+ links: item.links.map(link => ({
+ ...link,
+ url: linkUrl,
+ })),
+ }
+ : { ...item }
+ )),
+ }));
+ }
+ return originalFetch(input, options);
+ });
+
+ try {
+ await window.selectSubscription('all');
+ const card = document.querySelector('[data-news-id="news-two"]');
+ return {
+ primaryHref: card.querySelector('.btn-primary').getAttribute('href'),
+ sourceHref: card.querySelector('.ldr-source-link').getAttribute('href'),
+ };
+ } finally {
+ fetchMock.mockImplementation(originalFetch);
+ }
+}
+
+beforeAll(async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ localStorage.clear();
+ sessionStorage.clear();
+ installDom();
+
+ // DOMPurify's DOM traversal is not supported by happy-dom. This harness
+ // mirrors the production policy relevant to the page: event attributes
+ // and unsafe URLs are removed, while declarative data attributes survive.
+ const purify = {
+ addHook: vi.fn(),
+ sanitize: vi.fn(dirty => {
+ const template = document.createElement('template');
+ // eslint-disable-next-line no-unsanitized/property -- static test sanitizer for controlled repo fixtures.
+ template.innerHTML = String(dirty);
+ template.content.querySelectorAll('script, iframe, object')
+ .forEach(node => node.remove());
+ template.content.querySelectorAll('*').forEach(node => {
+ for (const attr of [...node.attributes]) {
+ if (attr.name.startsWith('on')) node.removeAttribute(attr.name);
+ if (
+ attr.name === 'href' &&
+ /^(?:javascript|data|vbscript):/i.test(attr.value.trim())
+ ) node.setAttribute('href', '#');
+ }
+ });
+ return template.content.cloneNode(true);
+ }),
+ };
+ globalThis.DOMPurify = purify;
+ window.DOMPurify = purify;
+ window.RESEARCH_STATUS = {
+ IN_PROGRESS: 'in_progress',
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ SUSPENDED: 'suspended',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'failed', 'error', 'cancelled', 'suspended',
+ ]);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-news-direct') };
+ window.safeUpdateButton = vi.fn((button, icon, label) => {
+ button.dataset.icon = icon;
+ button.textContent = label;
+ });
+
+ clipboardWrite = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', {
+ configurable: true,
+ value: { writeText: clipboardWrite },
+ });
+ Object.defineProperty(navigator, 'share', {
+ configurable: true,
+ value: undefined,
+ });
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(blob => {
+ createdBlob = blob;
+ return 'blob:news-export';
+ }),
+ });
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click').mockImplementation(function() {
+ downloadedFilename = this.download;
+ });
+
+ const modalInstances = new WeakMap();
+ class Modal {
+ constructor(element) {
+ this.element = element;
+ modalInstances.set(element, this);
+ }
+
+ show() {
+ this.element.dataset.shown = 'true';
+ }
+
+ hide() {
+ this.element.dataset.hidden = 'true';
+ }
+
+ static getInstance(element) {
+ return modalInstances.get(element) || null;
+ }
+ }
+ globalThis.bootstrap = { Modal };
+ window.bootstrap = globalThis.bootstrap;
+
+ feedItems = [{
+ id: 'news-one',
+ research_id: 'research-one',
+ headline: 'FastAPI migration reaches production',
+ category: 'Technology',
+ impact_score: 9,
+ upvotes: 1,
+ downvotes: 0,
+ created_at: '2026-09-01T11:30:00.000Z',
+ findings: '**Deployment complete**\n\nNo regressions observed.',
+ summary: 'Migration deployed. Services are healthy.',
+ topics: ['FastAPI', 'Migration'],
+ source_url: 'https://publisher.example/article?id=3299',
+ links: [{
+ title: 'Publisher report with a deliberately long descriptive title',
+ url: 'https://publisher.example/source?id=3299',
+ }],
+ }, {
+ id: 'news-two',
+ research_id: 'research/two',
+ headline: 'Older economy briefing',
+ category: 'Economy',
+ impact_score: 3,
+ upvotes: 0,
+ downvotes: 2,
+ created_at: '2026-08-10T10:00:00.000Z',
+ summary: 'Markets were quiet. Analysis remains stable.',
+ topics: ['Economy', 'Migration'],
+ source_url: 'javascript:window.__newsActionXss=true',
+ links: [{
+ title: 'Unsafe source',
+ url: 'javascript:window.__newsActionXss=true',
+ }],
+ }];
+ searchHistory = [{
+ id: 'search-1',
+ query: 'FastAPI migration',
+ type: 'table',
+ timestamp: '2026-09-01T11:55:00.000Z',
+ resultCount: 2,
+ }];
+
+ fetchMock = vi.fn(async (input, options = {}) => {
+ const url = String(input);
+ if (url === '/news/api/search-history' && options.method === 'GET') {
+ return response({ search_history: [...searchHistory] });
+ }
+ if (url === '/news/api/search-history' && options.method === 'POST') {
+ const payload = JSON.parse(options.body);
+ searchHistory.unshift({
+ id: `search-${searchHistory.length + 1}`,
+ timestamp: NOW.toISOString(),
+ ...payload,
+ });
+ return response({ status: 'success' });
+ }
+ if (url === '/library/api/research-history/collection') {
+ return response({ success: true, collection_id: 'news-collection-3299' });
+ }
+ if (url === '/news/api/subscriptions/current') {
+ return response({
+ subscriptions: [{ id: 'subscription-3299', query: 'Migration' }],
+ });
+ }
+ if (url === '/news/api/subscription/folders') {
+ return response([{
+ id: 'folder-3299',
+ icon: '🚀',
+ name: '<img src=x onerror="window.__newsActionXss=true"> Migration',
+ }]);
+ }
+ if (url === '/api/start_research' && options.method === 'POST') {
+ return response({
+ status: 'queued',
+ research_id: 'advanced-news-3299',
+ });
+ }
+ if (url === '/news/api/subscribe' && options.method === 'POST') {
+ return response({ subscription_id: 'subscription-created' });
+ }
+ if (url.startsWith('/news/api/feed?')) {
+ return response({ news_items: feedItems.map(item => ({ ...item })) });
+ }
+ if (url === '/news/api/feedback/batch') {
+ return response({
+ votes: {
+ 'news-one': { upvotes: 7, downvotes: 1, user_vote: 'up' },
+ 'news-two': { upvotes: 0, downvotes: 4, user_vote: null },
+ },
+ });
+ }
+ if (url === '/news/api/feedback/news-one' && options.method === 'POST') {
+ return response({ upvotes: 12, downvotes: 3 });
+ }
+ if (url === '/history/api') return response({ items: [] });
+ throw new Error(`Unexpected request: ${url} ${options.method || 'GET'}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/config/constants.js');
+ await import('@js/config/urls.js');
+ await import('@js/security/url-validator.js');
+ await import('@js/security/xss-protection.js');
+ await import('@js/pages/news.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ expect(document.querySelector('[data-news-id="news-one"] .ldr-vote-btn')
+ .textContent).toContain('7');
+ expect(document.getElementById('recent-searches').textContent)
+ .toContain('FastAPI migration');
+ });
+
+ const unsafeCard = document.querySelector('[data-news-id="news-two"]');
+ bootstrapSnapshot = {
+ trendingText: document.getElementById('trending-topics').textContent,
+ bulkActionsText: document.querySelector('.ldr-bulk-actions-bar').textContent,
+ primaryHref: unsafeCard.querySelector('.btn-primary').getAttribute('href'),
+ sourceHref: unsafeCard.querySelector('.ldr-source-link').getAttribute('href'),
+ scriptCount: unsafeCard.querySelectorAll('script').length,
+ xssExecuted: window.__newsActionXss,
+ };
+});
+
+afterAll(() => {
+ window.dispatchEvent(new Event('pagehide'));
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ sessionStorage.clear();
+ document.body.replaceChildren();
+ delete window.__newsActionXss;
+ delete window.api;
+ delete window.bootstrap;
+ delete window.DOMPurify;
+ delete window.safeUpdateButton;
+});
+
+beforeEach(async () => {
+ await restoreAllFeed();
+});
+
+it('boots through migrated endpoints and renders feed, votes, history, and safe links', () => {
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscriptions/current', {
+ credentials: 'same-origin',
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/research-history/collection',
+ { headers: { 'X-CSRFToken': 'csrf-news-direct' } },
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/feed?limit=20&use_cache=true',
+ );
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/feedback/batch', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-direct',
+ },
+ body: JSON.stringify({ card_ids: ['news-one', 'news-two'] }),
+ });
+ expect(bootstrapSnapshot).toMatchObject({
+ primaryHref: '#',
+ sourceHref: '#',
+ scriptCount: 0,
+ xssExecuted: undefined,
+ });
+ expect(bootstrapSnapshot.trendingText).toContain('Migration 2');
+ expect(bootstrapSnapshot.bulkActionsText).toContain('2 unread');
+});
+
+it('uses action attributes accepted by the installed DOMPurify defaults', () => {
+ expect(DOMPurify.isValidAttribute(
+ 'button', 'data-news-action', 'toggle-read',
+ )).toBe(true);
+ expect(DOMPurify.isValidAttribute(
+ 'button', 'data-news-page-action', 'clear-search',
+ )).toBe(true);
+ expect(DOMPurify.isValidAttribute(
+ 'button', 'data-vote-type', 'up',
+ )).toBe(true);
+ expect(DOMPurify.isValidAttribute(
+ 'button', 'onclick', "vote('news-one', 'up')",
+ )).toBe(false);
+});
+
+it.each([
+ ['protocol-relative paths', '//outside.example/report'],
+ ['slash-backslash paths', '/\\outside.example/report'],
+ ['C0-prefixed paths', `${String.fromCharCode(0)}//outside.example/report`],
+ ['control-obscured schemes', `h${String.fromCharCode(9)}ttps://outside.example/report`],
+])('blocks rendered report links with %s', async (_case, unsafeUrl) => {
+ await expect(renderSecondNewsLinks(unsafeUrl)).resolves.toEqual({
+ primaryHref: '#',
+ sourceHref: '#',
+ });
+});
+
+it('preserves valid internal report and HTTPS source links', async () => {
+ await expect(renderSecondNewsLinks(
+ '/results/research-two?view=full#sources',
+ 'https://publisher.example/report?id=3299',
+ )).resolves.toEqual({
+ primaryHref: '/results/research-two?view=full#sources',
+ sourceHref: 'https://publisher.example/report?id=3299',
+ });
+});
+
+it('preserves fragment, same-origin protocol-relative, and FTP report links', async () => {
+ const sameOriginReport = `//${window.location.host}/results/research-two`;
+ await expect(renderSecondNewsLinks(
+ '#report-details',
+ sameOriginReport,
+ )).resolves.toEqual({
+ primaryHref: '#report-details',
+ sourceHref: sameOriginReport,
+ });
+
+ await expect(renderSecondNewsLinks(
+ 'ftp://publisher.example/report',
+ 'ftps://publisher.example/source',
+ )).resolves.toEqual({
+ primaryHref: 'ftp://publisher.example/report',
+ sourceHref: 'ftps://publisher.example/source',
+ });
+});
+
+it('uses the legacy isSafeUrl validator when safeAssign is unavailable', async () => {
+ const validatorDescriptor = Object.getOwnPropertyDescriptor(
+ window,
+ 'URLValidator',
+ );
+ const isSafeUrl = vi.fn(url => url.includes('allowed.example'));
+ Object.defineProperty(window, 'URLValidator', {
+ configurable: true,
+ value: { isSafeUrl },
+ });
+
+ try {
+ await expect(renderSecondNewsLinks(
+ 'https://allowed.example/report',
+ 'https://blocked.example/source',
+ )).resolves.toEqual({
+ primaryHref: 'https://allowed.example/report',
+ sourceHref: '#',
+ });
+ expect(isSafeUrl).toHaveBeenCalledWith(
+ 'https://allowed.example/report',
+ );
+ expect(isSafeUrl).toHaveBeenCalledWith(
+ 'https://blocked.example/source',
+ );
+ } finally {
+ Object.defineProperty(window, 'URLValidator', validatorDescriptor);
+ }
+});
+
+it('canonically validates rendered report links without URLValidator', async () => {
+ const validatorDescriptor = Object.getOwnPropertyDescriptor(
+ window,
+ 'URLValidator',
+ );
+ Object.defineProperty(window, 'URLValidator', {
+ configurable: true,
+ value: undefined,
+ });
+
+ try {
+ await expect(renderSecondNewsLinks(
+ '/\\outside.example/report',
+ `${String.fromCharCode(0)}//outside.example/source`,
+ )).resolves.toEqual({
+ primaryHref: '#',
+ sourceHref: '#',
+ });
+
+ await expect(renderSecondNewsLinks(
+ '/results/research-two',
+ 'https://publisher.example/source',
+ )).resolves.toEqual({
+ primaryHref: '/results/research-two',
+ sourceHref: 'https://publisher.example/source',
+ });
+ } finally {
+ Object.defineProperty(window, 'URLValidator', validatorDescriptor);
+ }
+});
+
+it.each([
+ ['active data URL', 'data:text/html,<script>window.__newsActionXss=true</script>'],
+ ['blob URL', 'blob:http://localhost/untrusted-news-source'],
+])('blocks news-card navigation to an untrusted %s', async (
+ _case,
+ unsafeUrl,
+) => {
+ const originalFetch = fetchMock.getMockImplementation();
+ fetchMock.mockImplementation((input, options = {}) => {
+ if (String(input).startsWith('/news/api/feed?')) {
+ return Promise.resolve(response({
+ news_items: feedItems.map(item => (
+ item.id === 'news-two'
+ ? { ...item, source_url: unsafeUrl }
+ : { ...item }
+ )),
+ }));
+ }
+ return originalFetch(input, options);
+ });
+ const safeAssign = vi.spyOn(window.URLValidator, 'safeAssign');
+
+ try {
+ await window.selectSubscription('all');
+ const hrefBefore = window.location.href;
+ document.querySelector('[data-news-id="news-two"] .ldr-news-summary')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+ expect(safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ unsafeUrl,
+ );
+ expect(safeAssign.mock.results.at(-1).value).toBe(false);
+ expect(window.location.href).toBe(hrefBefore);
+ expect(window.__newsActionXss).toBeUndefined();
+ } finally {
+ safeAssign.mockRestore();
+ fetchMock.mockImplementation(originalFetch);
+ }
+});
+
+it('creates a table view that retains only valid HTTP sources', () => {
+ const toggle = document.getElementById('table-view-toggle');
+ toggle.checked = true;
+ toggle.dispatchEvent(new Event('change'));
+
+ const table = document.getElementById('news-table-view');
+ expect(table.style.display).toBe('block');
+ expect(document.getElementById('news-feed-content').style.display).toBe('none');
+ expect(table.querySelectorAll('tbody tr')).toHaveLength(2);
+ expect(table.querySelectorAll('tbody a')).toHaveLength(1);
+ expect(table.querySelector('tbody a').getAttribute('href'))
+ .toBe('https://publisher.example/article?id=3299');
+
+ toggle.checked = false;
+ toggle.dispatchEvent(new Event('change'));
+ expect(document.getElementById('news-feed-content').style.display).toBe('block');
+ expect(table.style.display).toBe('none');
+});
+
+it('votes through the exported page action with CSRF and authoritative counts', async () => {
+ await window.vote('news-one', 'down');
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/feedback/news-one', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-direct',
+ },
+ body: JSON.stringify({ vote: 'down' }),
+ });
+ const card = document.querySelector('[data-news-id="news-one"]');
+ const [up, down] = card.querySelectorAll('.ldr-vote-btn');
+ expect(up.textContent).toContain('12');
+ expect(up.classList.contains('ldr-voted')).toBe(false);
+ expect(down.textContent).toContain('3');
+ expect(down.classList.contains('ldr-voted')).toBe(true);
+});
+
+it('keeps every rendered card action clickable through the page sanitizer contract', async () => {
+ setReadState('news-one', false);
+ setSavedState('news-one', false);
+ clipboardWrite.mockClear();
+ createdBlob = null;
+ downloadedFilename = null;
+
+ const card = document.querySelector('[data-news-id="news-one"]');
+ const actionControls = [...card.querySelectorAll('[data-news-action]')];
+ expect(actionControls.map(control => control.dataset.newsAction)).toEqual([
+ 'toggle-read',
+ 'share',
+ 'copy-link',
+ 'export-markdown',
+ 'hide',
+ 'vote',
+ 'vote',
+ 'mark-read',
+ 'toggle-save',
+ ]);
+ expect(card.querySelector('[onclick]')).toBeNull();
+
+ // Click the nested icons to prove the delegated listener owns descendants,
+ // not just clicks that happen directly on the action element.
+ card.querySelector('[data-news-action="toggle-read"] i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('news-one');
+
+ card.querySelector('[data-news-action="toggle-save"] i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(JSON.parse(localStorage.getItem('saved_news_ids'))).toContain('news-one');
+ expect(card.querySelector('.ldr-save-btn i').className)
+ .toBe('bi bi-bookmark-fill');
+
+ const downvoteCallsBefore = fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/news/api/feedback/news-one' && options.method === 'POST'
+ )).length;
+ card.querySelector('[data-news-action="vote"][data-vote-type="down"] i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await vi.waitFor(() => {
+ expect(fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/news/api/feedback/news-one' && options.method === 'POST'
+ ))).toHaveLength(downvoteCallsBefore + 1);
+ expect(card.querySelectorAll('.ldr-vote-btn')[1].textContent)
+ .toContain('3');
+ });
+
+ const cardNavigation = vi.spyOn(window.URLValidator, 'safeAssign');
+ const shareEvent = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ });
+ card.querySelector('[data-news-action="share"] i').dispatchEvent(shareEvent);
+ const copyEvent = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ });
+ card.querySelector('[data-news-action="copy-link"] i').dispatchEvent(copyEvent);
+ await vi.waitFor(() => expect(clipboardWrite).toHaveBeenCalledTimes(2));
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ 'FastAPI migration reaches production\n\nhttps://publisher.example/article?id=3299',
+ );
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ 'https://publisher.example/article?id=3299',
+ );
+ expect(shareEvent.defaultPrevented).toBe(true);
+ expect(copyEvent.defaultPrevented).toBe(true);
+ expect(cardNavigation).not.toHaveBeenCalled();
+ cardNavigation.mockRestore();
+ history.replaceState({}, '', '/');
+
+ const exportEvent = new MouseEvent('click', {
+ bubbles: true,
+ cancelable: true,
+ });
+ card.querySelector('[data-news-action="export-markdown"] i')
+ .dispatchEvent(exportEvent);
+ expect(exportEvent.defaultPrevented).toBe(true);
+ expect(createdBlob.type).toBe('text/markdown');
+ expect(downloadedFilename).toBe('fastapi_migration_reaches_production.md');
+ URL.createObjectURL.mockClear();
+
+ setReadState('news-one', false);
+ card.querySelector('[data-news-action="mark-read"] i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('news-one');
+
+ card.querySelector('[data-news-action="hide"] i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(300);
+ expect(document.querySelector('[data-news-id="news-one"]')).toBeNull();
+});
+
+it('opens the subscription form from its sanitized rendered card control', async () => {
+ feedItems[0].query = 'FastAPI migration releases';
+
+ try {
+ await window.selectSubscription('all');
+ const subscribeControl = document.querySelector(
+ '[data-news-id="news-one"] [data-news-action="subscribe"]',
+ );
+ expect(subscribeControl).not.toBeNull();
+ expect(subscribeControl.getAttribute('onclick')).toBeNull();
+
+ subscribeControl.querySelector('i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+
+ const target = new URL(window.location.href);
+ expect(target.pathname).toBe('/news/subscriptions/new');
+ expect(target.searchParams.get('query')).toBe('FastAPI migration releases');
+ expect(target.searchParams.get('research_id')).toBe('research-one');
+ } finally {
+ delete feedItems[0].query;
+ history.replaceState({}, '', '/');
+ }
+});
+
+it('combines impact, time, and topic filters and clears their DOM state', () => {
+ const visibleIds = () => [...document.querySelectorAll('.ldr-news-item')]
+ .map(item => item.dataset.newsId);
+ const impact = document.getElementById('impact-filter');
+ impact.value = '8';
+ impact.dispatchEvent(new Event('input'));
+ expect(visibleIds()).toEqual(['news-one']);
+ expect(document.querySelector('.ldr-impact-value').textContent).toBe('8+');
+
+ impact.value = '0';
+ impact.dispatchEvent(new Event('input'));
+ document.querySelector('[data-time="week"]')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(visibleIds()).toEqual(['news-one']);
+
+ window.filterByTopic('Economy');
+ expect(visibleIds()).toEqual([]);
+ expect(document.querySelector('.ldr-filter-status-bar').textContent)
+ .toContain('Topic: Economy');
+
+ window.clearAllFilters();
+ expect(visibleIds()).toEqual(['news-one', 'news-two']);
+ expect(document.querySelector('[data-time="all"]').classList.contains('active'))
+ .toBe(true);
+ expect(impact.value).toBe('0');
+ expect(document.querySelector('.ldr-slider-value').textContent).toBe('0');
+ expect(document.querySelector('.ldr-filter-status-bar')).toBeNull();
+});
+
+it('persists read and saved ownership and restores the server feed after saved view', async () => {
+ setReadState('news-one', false);
+ setReadState('news-two', false);
+ setSavedState('news-one', false);
+
+ window.toggleReadStatus('news-one');
+ expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('news-one');
+ expect(document.querySelector('[data-news-id="news-one"]')
+ .classList.contains('ldr-is-read')).toBe(true);
+
+ window.markAllAsRead();
+ expect(new Set(JSON.parse(localStorage.getItem('news_read_ids'))))
+ .toEqual(new Set(['news-one', 'news-two']));
+
+ window.toggleSaveItem('news-one');
+ expect(JSON.parse(localStorage.getItem('saved_news_ids'))).toEqual(['news-one']);
+ expect(JSON.parse(localStorage.getItem('saved_news_items'))['news-one'])
+ .toMatchObject({ headline: 'FastAPI migration reaches production' });
+ expect(document.querySelector('[data-news-id="news-one"] .ldr-save-btn i').className)
+ .toBe('bi bi-bookmark-fill');
+
+ const feedCallsBeforeSaved = fetchMock.mock.calls.filter(([url]) => (
+ String(url).startsWith('/news/api/feed?')
+ )).length;
+ await window.selectSubscription('saved');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(1);
+ expect(document.querySelector('.ldr-feed-header h2').textContent).toBe('Saved Items');
+ expect(fetchMock.mock.calls.filter(([url]) => (
+ String(url).startsWith('/news/api/feed?')
+ ))).toHaveLength(feedCallsBeforeSaved);
+
+ window.toggleSaveItem('news-one');
+ await window.selectSubscription('saved');
+ expect(document.getElementById('news-feed-content').textContent)
+ .toContain('No saved items');
+
+ await window.selectSubscription('all');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ expect(document.querySelector('.ldr-feed-header h2').textContent).toBe('All News');
+});
+
+it('expands, collapses, and hides owned cards while keeping bulk counts current', async () => {
+ window.expandAll();
+ expect([...document.querySelectorAll('.ldr-news-item')].every(item => (
+ item.classList.contains('ldr-is-expanded')
+ ))).toBe(true);
+
+ window.collapseAll();
+ expect([...document.querySelectorAll('.ldr-news-item')].every(item => (
+ !item.classList.contains('ldr-is-expanded')
+ ))).toBe(true);
+
+ window.hideNewsItem('news-two');
+ expect(document.querySelector('[data-news-id="news-two"]').style.opacity)
+ .toBe('0');
+ await vi.advanceTimersByTimeAsync(300);
+ expect(document.querySelector('[data-news-id="news-two"]')).toBeNull();
+ expect(document.querySelector('.ldr-bulk-actions-bar').textContent)
+ .toContain('1 total');
+
+ await window.selectSubscription('all');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+});
+
+it('copies and exports canonical absolute URLs, falling back from unsafe sources', async () => {
+ clipboardWrite.mockClear();
+ window.copyNewsLink('news-one');
+ window.shareNews('news-two');
+ await Promise.resolve();
+
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ 'https://publisher.example/article?id=3299',
+ );
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ `Older economy briefing\n\n${window.location.origin}/results/research%2Ftwo`,
+ );
+
+ createdBlob = null;
+ downloadedFilename = null;
+ window.exportToMarkdown('news-one');
+ expect(URL.createObjectURL).toHaveBeenCalledOnce();
+ expect(createdBlob.type).toBe('text/markdown');
+ expect(downloadedFilename)
+ .toBe('fastapi_migration_reaches_production.md');
+ expect(await createdBlob.text()).toContain(
+ '[View Full Report](https://publisher.example/article?id=3299)',
+ );
+});
+
+it('runs text search from the real mode controls and posts history with CSRF', async () => {
+ document.querySelector('[data-mode="text"]')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(document.getElementById('news-search-mode-btn').textContent)
+ .toContain('Text Only');
+ expect(document.getElementById('news-search').placeholder)
+ .toContain('Text:');
+
+ document.getElementById('news-search').value = 'FastAPI';
+ document.getElementById('search-btn').click();
+ await vi.waitFor(() => {
+ expect(fetchMock.mock.calls.some(([url]) => (
+ String(url).includes('focus=FastAPI')
+ ))).toBe(true);
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(1);
+ });
+ const historyPost = fetchMock.mock.calls.find(([url, options]) => {
+ if (url !== '/news/api/search-history' || options.method !== 'POST') {
+ return false;
+ }
+ return JSON.parse(options.body).query === 'FastAPI';
+ });
+ expect(historyPost[1].credentials).toBe('same-origin');
+ expect(historyPost[1].headers['X-CSRFToken']).toBe('csrf-news-direct');
+ expect(JSON.parse(historyPost[1].body)).toMatchObject({
+ query: 'FastAPI',
+ type: 'filter',
+ resultCount: 2,
+ });
+
+ const clearSearchControl = document.querySelector(
+ '[data-news-page-action="clear-search"]',
+ );
+ expect(clearSearchControl).not.toBeNull();
+ expect(clearSearchControl.getAttribute('onclick')).toBeNull();
+ clearSearchControl.querySelector('i')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('news-search').value).toBe('');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ });
+});
+
+it('does not let a history body captured before Clear All restore deleted rows', async () => {
+ const staleBody = deferred();
+ const originalFetch = fetchMock.getMockImplementation();
+ const originalConfirm = Object.getOwnPropertyDescriptor(window, 'confirm');
+ Object.defineProperty(window, 'confirm', {
+ configurable: true,
+ value: vi.fn(() => true),
+ });
+ const staleResponse = {
+ ok: true,
+ status: 200,
+ headers: {},
+ json: vi.fn(() => staleBody.promise),
+ text: vi.fn().mockResolvedValue(''),
+ };
+
+ fetchMock.mockImplementation((input, options = {}) => {
+ const url = String(input);
+ if (url === '/news/api/search-history' && options.method === 'GET') {
+ return Promise.resolve(staleResponse);
+ }
+ if (url === '/news/api/search-history' && options.method === 'DELETE') {
+ return Promise.resolve(response({ status: 'success' }));
+ }
+ return originalFetch(input, options);
+ });
+
+ try {
+ // This models the unawaited bootstrap load: its response has arrived,
+ // but decoding the pre-delete snapshot is still in flight.
+ const staleLoad = window.loadSearchHistory();
+ await vi.waitFor(() => expect(staleResponse.json).toHaveBeenCalledOnce());
+
+ await window.clearSearchHistory();
+ expect(document.getElementById('recent-searches').textContent)
+ .toContain('Your recent news searches will appear here');
+
+ staleBody.resolve({
+ search_history: [{
+ id: 'deleted-search',
+ query: 'This row was deleted',
+ type: 'quick',
+ timestamp: NOW.toISOString(),
+ resultCount: 1,
+ }],
+ });
+ await staleLoad;
+
+ expect(document.getElementById('recent-searches').textContent)
+ .not.toContain('This row was deleted');
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/search-history', {
+ method: 'DELETE',
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': 'csrf-news-direct' },
+ });
+ } finally {
+ fetchMock.mockImplementation(originalFetch);
+ if (originalConfirm) {
+ Object.defineProperty(window, 'confirm', originalConfirm);
+ } else {
+ delete window.confirm;
+ }
+ await window.loadSearchHistory();
+ }
+});
+
+it('drives the report-link, topic-clear, and recent-search public actions', async () => {
+ setReadState('news-one', true);
+ window.toggleReadStatus('news-one');
+ expect(document.querySelector('[data-news-id="news-one"]')
+ .classList.contains('ldr-is-unread')).toBe(true);
+ expect(window.markAsReadOnClick('news-one')).toBe(true);
+ expect(document.querySelector('[data-news-id="news-one"]')
+ .classList.contains('ldr-is-read')).toBe(true);
+ expect(JSON.parse(localStorage.getItem('news_read_ids'))).toContain('news-one');
+
+ window.filterByTopic('Economy');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(1);
+ window.clearTopicFilter();
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ expect(document.querySelector('.ldr-active-filter-bar')).toBeNull();
+
+ const recentSearch = [...document.querySelectorAll('.ldr-recent-search-item')]
+ .find(item => item.querySelector('.ldr-search-query')?.textContent === (
+ 'FastAPI migration'
+ ));
+ expect(recentSearch).toBeDefined();
+ expect(recentSearch.getAttribute('onclick')).toBeNull();
+ expect(recentSearch.dataset).toMatchObject({
+ newsPageAction: 'rerun-search',
+ query: 'FastAPI migration',
+ searchType: 'table',
+ });
+ recentSearch.querySelector('.bi-arrow-repeat')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ await vi.waitFor(() => {
+ expect(document.getElementById('news-search').value)
+ .toBe('FastAPI migration');
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(1);
+ expect(document.querySelector('[data-news-id="news-one"]')).not.toBeNull();
+ });
+
+ document.getElementById('news-search').value = '';
+ document.getElementById('search-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ });
+});
+
+it('falls back to the temporary-textarea copy path after clipboard rejection', async () => {
+ clipboardWrite.mockRejectedValueOnce(new Error('clipboard denied'));
+ const execCommand = vi.fn(() => true);
+ Object.defineProperty(document, 'execCommand', {
+ configurable: true,
+ value: execCommand,
+ });
+
+ window.copyNewsLink('news-one');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(execCommand).toHaveBeenCalledWith('copy');
+ expect(document.querySelector('textarea[style*="position: fixed"]')).toBeNull();
+ expect(document.getElementById('news-alert').textContent)
+ .toBe('Copied to clipboard');
+});
+
+it('loads and copies the checked-in query template through public controls', async () => {
+ window.loadNewsTableQuery();
+ const template = document.getElementById('query-template');
+ expect(template.style.display).toBe('block');
+ expect(template.textContent).toContain('DIVERSITY IS MANDATORY');
+
+ window.useQueryTemplate();
+ expect(document.getElementById('news-query').value)
+ .toContain('START YOUR RESPONSE DIRECTLY WITH THE TABLE');
+ expect(template.style.display).toBe('none');
+ expect(document.getElementById('table-view-toggle').checked).toBe(true);
+
+ clipboardWrite.mockClear();
+ await window.copyQueryTemplate();
+ expect(clipboardWrite).toHaveBeenCalledWith(
+ expect.stringContaining('PRIORITIZE BY REAL-WORLD IMPACT'),
+ );
+});
+
+it('loads safe folder options and submits the template modal through the migrated create contract', async () => {
+ document.getElementById('create-subscription-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('#news-subscription-folder option'))
+ .toHaveLength(2);
+ });
+ expect(document.getElementById('newsSubscriptionModal').dataset.shown)
+ .toBe('true');
+ const folderOption = document.querySelector(
+ '#news-subscription-folder option[value="folder-3299"]',
+ );
+ expect(folderOption.textContent).toContain('Migration');
+ expect(folderOption.querySelector('img')).toBeNull();
+ expect(window.__newsActionXss).toBeUndefined();
+
+ document.getElementById('news-subscription-query').value = 'Migration releases';
+ document.getElementById('news-subscription-name').value = 'Release watch';
+ document.getElementById('news-subscription-folder').value = 'folder-3299';
+ document.getElementById('news-subscription-model').value = 'OLLAMA:llama3';
+ document.getElementById('news-subscription-strategy').value = 'source-based';
+
+ await window.handleNewsSubscriptionSubmit(new Event('submit'));
+
+ const createCall = fetchMock.mock.calls.find(([url, options = {}]) => {
+ if (url !== '/news/api/subscribe' || options.method !== 'POST') {
+ return false;
+ }
+ return JSON.parse(options.body).name === 'Release watch';
+ });
+ expect(createCall).toBeDefined();
+ expect(createCall[1].headers['X-CSRFToken']).toBe('csrf-news-direct');
+ expect(JSON.parse(createCall[1].body)).toEqual({
+ query: 'Migration releases',
+ name: 'Release watch',
+ subscription_type: 'search',
+ refresh_minutes: 240,
+ folder_id: 'folder-3299',
+ is_active: true,
+ model_provider: 'OLLAMA',
+ model: 'OLLAMA:llama3',
+ search_strategy: 'source-based',
+ });
+ expect(document.getElementById('newsSubscriptionModal').dataset.hidden)
+ .toBe('true');
+ expect(document.getElementById('news-alert').textContent)
+ .toBe('Subscription created successfully!');
+});
+
+it('builds an encoded migrated subscription-form URL from a rendered news item', () => {
+ window.createSubscriptionFromItem('news-one');
+
+ const target = new URL(window.location.href);
+ expect(target.pathname).toBe('/news/subscriptions/new');
+ expect(target.searchParams.get('query'))
+ .toBe('FastAPI migration reaches production');
+ expect(target.searchParams.get('name'))
+ .toBe('Subscription: FastAPI migration reaches production...');
+ expect(target.searchParams.get('research_id')).toBe('research-one');
+
+ history.replaceState({}, '', '/');
+ window.createSubscriptionFromItem('missing-news');
+ expect(document.getElementById('news-alert').textContent)
+ .toBe('News item not found');
+});
+
+it('routes checked-in and prompted templates to the encoded subscription form', () => {
+ window.useNewsTemplate('breaking-news');
+ let target = new URL(window.location.href);
+ expect(target.pathname).toBe('/news/subscriptions/new');
+ expect(target.searchParams.get('template')).toBe('breaking-news');
+ expect(target.searchParams.get('name')).toContain('dynamic dates');
+ expect(target.searchParams.get('query')).toContain('YYYY-MM-DD');
+
+ history.replaceState({}, '', '/');
+ vi.stubGlobal('prompt', vi.fn(() => '<script>Quantum policy</script>'));
+ window.useNewsTemplate('topic-news');
+ target = new URL(window.location.href);
+ expect(target.pathname).toBe('/news/subscriptions/new');
+ expect(target.searchParams.get('template')).toBe('topic-news');
+ expect(target.searchParams.get('query'))
+ .toContain('<script>Quantum policy</script>');
+ expect(window.__newsActionXss).toBeUndefined();
+
+ history.replaceState({}, '', '/');
+ window.useNewsTemplate('custom');
+ expect(window.location.pathname).toBe('/news/subscriptions/new');
+ expect(window.location.search).toBe('');
+ history.replaceState({}, '', '/');
+});
+
+it('starts and stops auto-refresh without replacing an active text search', async () => {
+ document.getElementById('table-view-toggle').checked = false;
+ const toggle = document.getElementById('auto-refresh');
+ const feedCallCount = () => fetchMock.mock.calls.filter(([url]) => (
+ String(url).startsWith('/news/api/feed?')
+ )).length;
+ const beforeRefresh = feedCallCount();
+
+ toggle.checked = true;
+ toggle.dispatchEvent(new Event('change'));
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+ await vi.waitFor(() => expect(feedCallCount()).toBeGreaterThan(beforeRefresh));
+ expect(document.querySelector('label[for="auto-refresh"]').textContent)
+ .toContain('Auto-refresh');
+
+ document.getElementById('news-search').value = 'do not replace this search';
+ const withSearch = feedCallCount();
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+ expect(feedCallCount()).toBe(withSearch);
+
+ toggle.checked = false;
+ toggle.dispatchEvent(new Event('change'));
+ document.getElementById('news-search').value = '';
+});
+
+it('refreshes from the real template button without relying on inline JavaScript', async () => {
+ document.getElementById('news-search').value = '';
+ const feedCallCount = () => fetchMock.mock.calls.filter(([url]) => (
+ String(url).startsWith('/news/api/feed?')
+ )).length;
+ const beforeRefresh = feedCallCount();
+
+ document.getElementById('refresh-feed-btn').click();
+
+ await vi.waitFor(() => expect(feedCallCount()).toBeGreaterThan(beforeRefresh));
+ expect(document.getElementById('news-alert').textContent).toBe('Feed refreshed');
+});
+
+it('runs advanced news and creates its follow-on subscription through migrated contracts', async () => {
+ const query = 'FastAPI follow-on subscriptions';
+ const currentSubscriptionsBefore = fetchMock.mock.calls.filter(([url]) => (
+ url === '/news/api/subscriptions/current'
+ )).length;
+ document.getElementById('news-subscription-query').value = query;
+
+ document.getElementById('run-template-btn').click();
+
+ await vi.waitFor(() => {
+ const subscribeCall = fetchMock.mock.calls.find(([url, options = {}]) => {
+ if (url !== '/news/api/subscribe' || options.method !== 'POST') return false;
+ return JSON.parse(options.body).metadata?.is_advanced_query === true;
+ });
+ expect(subscribeCall).toBeDefined();
+ expect(fetchMock.mock.calls.filter(([url]) => (
+ url === '/news/api/subscriptions/current'
+ ))).toHaveLength(currentSubscriptionsBefore + 1);
+ });
+
+ expect(fetchMock).toHaveBeenCalledWith('/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-direct',
+ },
+ body: JSON.stringify({
+ query,
+ mode: 'quick',
+ strategy: 'source-based',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ triggered_by: 'test_run',
+ },
+ }),
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-direct',
+ },
+ body: JSON.stringify({
+ query,
+ subscription_type: 'search',
+ refresh_minutes: 60,
+ metadata: {
+ research_id: 'advanced-news-3299',
+ is_advanced_query: true,
+ },
+ }),
+ });
+ expect(document.getElementById('news-alert').textContent)
+ .toBe('Advanced news subscription created!');
+});
+
+it('coalesces rapid Run Once clicks into one advanced research request', async () => {
+ const startRequest = deferred();
+ const originalFetch = fetchMock.getMockImplementation();
+ const startCallCount = () => fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/api/start_research' && options.method === 'POST'
+ )).length;
+ const subscriptionCallCount = () => fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/news/api/subscribe' && options.method === 'POST' &&
+ JSON.parse(options.body).metadata?.is_advanced_query === true
+ )).length;
+ const startsBefore = startCallCount();
+ const subscriptionsBefore = subscriptionCallCount();
+
+ fetchMock.mockImplementation((input, options = {}) => {
+ if (String(input) === '/api/start_research' && options.method === 'POST') {
+ return startRequest.promise;
+ }
+ return originalFetch(input, options);
+ });
+
+ try {
+ document.getElementById('news-subscription-query').value = (
+ 'One owned advanced migration search'
+ );
+ const runButton = document.getElementById('run-template-btn');
+ runButton.click();
+ runButton.click();
+
+ await vi.waitFor(() => expect(startCallCount()).toBe(startsBefore + 1));
+ expect(subscriptionCallCount()).toBe(subscriptionsBefore);
+
+ startRequest.resolve(response({
+ status: 'queued',
+ research_id: 'single-flight-news-3299',
+ }));
+ await vi.waitFor(() => {
+ expect(subscriptionCallCount()).toBe(subscriptionsBefore + 1);
+ });
+
+ expect(startCallCount()).toBe(startsBefore + 1);
+ const newSubscriptionCalls = fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/news/api/subscribe' && options.method === 'POST' &&
+ JSON.parse(options.body).metadata?.research_id === 'single-flight-news-3299'
+ ));
+ expect(newSubscriptionCalls).toHaveLength(1);
+ } finally {
+ fetchMock.mockImplementation(originalFetch);
+ }
+});
+
+it('keeps distinct Run Once queries concurrent', async () => {
+ const firstStart = deferred();
+ const secondStart = deferred();
+ const originalFetch = fetchMock.getMockImplementation();
+ const firstQuery = 'First concurrent migration query';
+ const secondQuery = 'Second concurrent migration query';
+ const startsBefore = fetchMock.mock.calls.filter(([url, options = {}]) => (
+ url === '/api/start_research' && options.method === 'POST'
+ )).length;
+
+ fetchMock.mockImplementation((input, options = {}) => {
+ if (String(input) === '/api/start_research' && options.method === 'POST') {
+ const { query } = JSON.parse(options.body);
+ if (query === firstQuery) return firstStart.promise;
+ if (query === secondQuery) return secondStart.promise;
+ }
+ return originalFetch(input, options);
+ });
+
+ try {
+ const queryInput = document.getElementById('news-subscription-query');
+ const runButton = document.getElementById('run-template-btn');
+ queryInput.value = firstQuery;
+ runButton.click();
+ queryInput.value = secondQuery;
+ runButton.click();
+
+ await vi.waitFor(() => {
+ const newStartCalls = fetchMock.mock.calls
+ .filter(([url, options = {}]) => (
+ url === '/api/start_research' && options.method === 'POST'
+ ))
+ .slice(startsBefore);
+ expect(newStartCalls).toHaveLength(2);
+ expect(newStartCalls.map(([, options]) => (
+ JSON.parse(options.body).query
+ ))).toEqual([firstQuery, secondQuery]);
+ });
+
+ secondStart.resolve(response({
+ status: 'queued',
+ research_id: 'second-concurrent-news-3299',
+ }));
+ firstStart.resolve(response({
+ status: 'queued',
+ research_id: 'first-concurrent-news-3299',
+ }));
+ await vi.waitFor(() => {
+ const researchIds = fetchMock.mock.calls
+ .filter(([url, options = {}]) => (
+ url === '/news/api/subscribe' && options.method === 'POST'
+ ))
+ .map(([, options]) => JSON.parse(options.body).metadata?.research_id);
+ expect(researchIds).toContain('first-concurrent-news-3299');
+ expect(researchIds).toContain('second-concurrent-news-3299');
+ });
+ } finally {
+ fetchMock.mockImplementation(originalFetch);
+ }
+});
diff --git a/tests/js/pages/news-advanced-search-runtime.test.js b/tests/js/pages/news-advanced-search-runtime.test.js
new file mode 100644
index 0000000000..b50212cb38
--- /dev/null
+++ b/tests/js/pages/news-advanced-search-runtime.test.js
@@ -0,0 +1,280 @@
+/** Runtime contracts for the news page's advanced research entry point. */
+
+import { resolve } from 'node:path';
+
+import '@js/security/xss-protection.js';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function response(payload, { ok = true, status = 200, statusText = '' } = {}) {
+ return {
+ ok,
+ status,
+ statusText,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolveDeferred, rejectDeferred) => {
+ resolvePromise = resolveDeferred;
+ rejectPromise = rejectDeferred;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+function compileAdvancedSearchRuntime() {
+ const showAlert = vi.fn();
+ const pollForNewsResearchResults = vi.fn();
+ const createSubscriptionFromSearch = vi.fn().mockResolvedValue(undefined);
+ const safeLogger = {
+ log: vi.fn(),
+ error: vi.fn(),
+ };
+ const { performAdvancedNewsSearch } = compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: [
+ 'advancedNewsSearchKey',
+ 'performAdvancedNewsSearch',
+ 'executeAdvancedNewsSearch',
+ ],
+ dependencies: {
+ URLS: { API: { START_RESEARCH: '/api/start_research' } },
+ getCSRFToken: () => window.api.getCsrfToken(),
+ showAlert,
+ SafeLogger: safeLogger,
+ escapeHtml: window.escapeHtml,
+ pollForNewsResearchResults,
+ createSubscriptionFromSearch,
+ },
+ preamble: 'const activeAdvancedNewsSearches = new Map();',
+ returnExpression: '({ performAdvancedNewsSearch })',
+ });
+ return {
+ performAdvancedNewsSearch,
+ showAlert,
+ pollForNewsResearchResults,
+ createSubscriptionFromSearch,
+ safeLogger,
+ };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = '<section id="news-feed-content">Old feed</section>';
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ window.api = {
+ getCsrfToken: vi.fn(() => 'csrf-advanced-news'),
+ redirectToLogin: vi.fn(),
+ };
+ delete window.__newsXss;
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.RESEARCH_STATUS;
+ delete window.api;
+ delete window.__newsXss;
+});
+
+it('starts advanced research with CSRF and hands an inert owned card to polling', async () => {
+ const runtime = compileAdvancedSearchRuntime();
+ const researchId = 'research-1" onmouseover="window.__newsXss=true';
+ const query = '<img src=x onerror="window.__newsXss=true"> migration news';
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ status: 'queued',
+ research_id: researchId,
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await runtime.performAdvancedNewsSearch(query, 'source-based', {
+ provider: 'openrouter',
+ model: 'model/x',
+ customEndpoint: 'https://models.example/v1',
+ searchEngine: 'serper',
+ iterations: 2,
+ questions: 3,
+ });
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/start_research');
+ expect(options).toMatchObject({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-advanced-news',
+ },
+ });
+ expect(JSON.parse(options.body)).toEqual({
+ query,
+ mode: 'quick',
+ strategy: 'source-based',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ triggered_by: 'test_run',
+ },
+ model_provider: 'openrouter',
+ model: 'model/x',
+ custom_endpoint: 'https://models.example/v1',
+ search_engine: 'serper',
+ iterations: 2,
+ questions_per_iteration: 3,
+ });
+
+ const card = document.querySelector('.ldr-active-research-card');
+ expect(card).not.toBeNull();
+ expect(card.dataset.researchId).toBe(researchId);
+ expect(card.hasAttribute('onmouseover')).toBe(false);
+ expect(card.querySelector('img')).toBeNull();
+ expect(window.__newsXss).toBeUndefined();
+ expect(runtime.pollForNewsResearchResults)
+ .toHaveBeenCalledWith(researchId, query);
+ expect(runtime.createSubscriptionFromSearch)
+ .toHaveBeenCalledWith(query, researchId);
+ expect(runtime.showAlert).toHaveBeenLastCalledWith(
+ 'Analyzing news... Results will appear below when ready.',
+ 'info',
+ );
+});
+
+it('renders a FastAPI detail error without starting polling or a subscription', async () => {
+ const runtime = compileAdvancedSearchRuntime();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response(
+ { detail: 'Search strategy is invalid' },
+ { ok: false, status: 422, statusText: 'Unprocessable Entity' },
+ )));
+
+ await runtime.performAdvancedNewsSearch('migration news');
+
+ expect(runtime.showAlert).toHaveBeenLastCalledWith(
+ 'Search strategy is invalid',
+ 'error',
+ );
+ expect(runtime.pollForNewsResearchResults).not.toHaveBeenCalled();
+ expect(runtime.createSubscriptionFromSearch).not.toHaveBeenCalled();
+ expect(document.getElementById('news-feed-content').textContent)
+ .toBe('Old feed');
+});
+
+it('uses the shared login redirect after an unauthorized advanced search', async () => {
+ vi.useFakeTimers();
+ const runtime = compileAdvancedSearchRuntime();
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response(
+ { detail: 'Not authenticated' },
+ { ok: false, status: 401, statusText: 'Unauthorized' },
+ )));
+
+ await runtime.performAdvancedNewsSearch('private migration news');
+
+ expect(runtime.showAlert).toHaveBeenLastCalledWith(
+ 'Authentication required. Please log in to perform research.',
+ 'error',
+ );
+ expect(window.api.redirectToLogin).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(2000);
+ expect(window.api.redirectToLogin).toHaveBeenCalledOnce();
+ expect(runtime.pollForNewsResearchResults).not.toHaveBeenCalled();
+ expect(runtime.createSubscriptionFromSearch).not.toHaveBeenCalled();
+});
+
+it('keeps duplicate callers on the active request and releases after an unreadable error body', async () => {
+ const errorBody = deferred();
+ const runtime = compileAdvancedSearchRuntime();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 422,
+ statusText: 'Unprocessable Entity',
+ json: vi.fn(() => errorBody.promise),
+ })
+ .mockResolvedValueOnce(response({
+ status: 'queued',
+ research_id: 'retry-news-3299',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const firstSearch = runtime.performAdvancedNewsSearch('first migration search');
+ const duplicateSearch = runtime.performAdvancedNewsSearch('first migration search');
+ let duplicateSettled = false;
+ duplicateSearch.then(() => {
+ duplicateSettled = true;
+ });
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ await Promise.resolve();
+ expect(duplicateSettled).toBe(false);
+
+ errorBody.reject(new Error('response body was not JSON'));
+ await Promise.all([firstSearch, duplicateSearch]);
+ expect(runtime.showAlert).toHaveBeenLastCalledWith(
+ 'Error starting research: Unprocessable Entity',
+ 'error',
+ );
+
+ await runtime.performAdvancedNewsSearch('retry migration search');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(runtime.pollForNewsResearchResults).toHaveBeenCalledOnce();
+ expect(runtime.pollForNewsResearchResults).toHaveBeenCalledWith(
+ 'retry-news-3299',
+ 'retry migration search',
+ );
+});
+
+it('keys active searches canonically while preserving distinct invocations', async () => {
+ const requests = [];
+ const runtime = compileAdvancedSearchRuntime();
+ const fetchMock = vi.fn(() => {
+ const request = deferred();
+ requests.push(request);
+ return request.promise;
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const sharedConfig = {
+ provider: 'openai',
+ model: 'embedding-news-v1',
+ iterations: 2,
+ };
+ const sameConfigDifferentOrder = {
+ iterations: 2,
+ model: 'embedding-news-v1',
+ provider: 'openai',
+ };
+ const searches = [
+ runtime.performAdvancedNewsSearch('shared query', 'source-based', sharedConfig),
+ runtime.performAdvancedNewsSearch(
+ 'shared query',
+ 'source-based',
+ sameConfigDifferentOrder,
+ ),
+ runtime.performAdvancedNewsSearch('different query', 'source-based', sharedConfig),
+ runtime.performAdvancedNewsSearch('shared query', 'focused', sharedConfig),
+ runtime.performAdvancedNewsSearch('shared query', 'source-based', {
+ ...sharedConfig,
+ model: 'embedding-news-v2',
+ }),
+ ];
+
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ for (const request of requests) {
+ request.resolve(response(
+ { detail: 'End the concurrency fixture' },
+ { ok: false, status: 422, statusText: 'Unprocessable Entity' },
+ ));
+ }
+ await Promise.all(searches);
+});
diff --git a/tests/js/pages/news-enhancements-runtime.test.js b/tests/js/pages/news-enhancements-runtime.test.js
new file mode 100644
index 0000000000..6e8fcc32bd
--- /dev/null
+++ b/tests/js/pages/news-enhancements-runtime.test.js
@@ -0,0 +1,133 @@
+/** Direct contracts for the optional News design-enhancement runtime. */
+
+let voteButton;
+let topicPill;
+let refreshButton;
+let refreshListener;
+let inlineRefresh;
+let initialImpactWidth;
+
+beforeAll(async () => {
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <article class="ldr-news-item" id="news-a"></article>
+ <article class="ldr-news-item" id="news-b"></article>
+ <button class="ldr-vote-btn" id="vote"></button>
+ <button class="ldr-topic-pill" id="topic"></button>
+ <div class="ldr-news-cards-container"></div>
+ <button id="refresh-feed-btn"></button>
+ <label id="search-wrapper"><input id="news-search"></label>
+ <div class="ldr-impact-fill" style="width: 72%"></div>
+ <header class="ldr-feed-header-section"></header>
+ `;
+
+ voteButton = document.getElementById('vote');
+ topicPill = document.getElementById('topic');
+ refreshButton = document.getElementById('refresh-feed-btn');
+ vi.spyOn(voteButton, 'getBoundingClientRect').mockReturnValue({
+ width: 40,
+ height: 20,
+ left: 10,
+ top: 20,
+ right: 50,
+ bottom: 40,
+ x: 10,
+ y: 20,
+ toJSON: () => ({}),
+ });
+
+ // news.js owns refresh through addEventListener; some deployments may
+ // also provide a legacy inline callback. The enhancement must preserve
+ // both ownership paths while adding only visual state.
+ refreshListener = vi.fn();
+ inlineRefresh = vi.fn();
+ refreshButton.addEventListener('click', refreshListener);
+ refreshButton.onclick = inlineRefresh;
+
+ await import('@js/news-enhancements.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ initialImpactWidth = document.querySelector('.ldr-impact-fill').style.width;
+});
+
+afterAll(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ document.body.innerHTML = '';
+ document.head.querySelectorAll('style').forEach(style => {
+ if (style.textContent.includes('ripple-animation')) style.remove();
+ });
+});
+
+it('initializes stagger, hover, search, impact, and parallax behavior', async () => {
+ const [firstItem, secondItem] = document.querySelectorAll('.ldr-news-item');
+ expect(firstItem.style.animationDelay).toBe('0s');
+ expect(secondItem.style.animationDelay).toBe('0.1s');
+
+ firstItem.dispatchEvent(new MouseEvent('mouseenter'));
+ expect(firstItem.style.transform).toBe('translateY(-4px)');
+ firstItem.dispatchEvent(new MouseEvent('mouseleave'));
+ expect(firstItem.style.transform).toBe('translateY(0)');
+
+ const search = document.getElementById('news-search');
+ search.dispatchEvent(new Event('focus'));
+ expect(document.getElementById('search-wrapper').style.transform)
+ .toBe('scale(1.02)');
+ search.dispatchEvent(new Event('blur'));
+ expect(document.getElementById('search-wrapper').style.transform)
+ .toBe('scale(1)');
+
+ const impact = document.querySelector('.ldr-impact-fill');
+ // Capture the one-time bootstrap state before another shuffled test can
+ // advance the suite's shared fake clock past this animation timeout.
+ expect(initialImpactWidth).toBe('0px');
+ await vi.advanceTimersByTimeAsync(500);
+ expect(impact.style.width).toBe('72%');
+
+ Object.defineProperty(window, 'pageYOffset', {
+ configurable: true,
+ value: 250,
+ });
+ window.dispatchEvent(new Event('scroll'));
+ expect(document.querySelector('.ldr-feed-header-section').style.transform)
+ .toBe('translateY(-25px)');
+});
+
+it('owns temporary click effects and removes them on schedule', async () => {
+ voteButton.dispatchEvent(new MouseEvent('click', {
+ bubbles: true,
+ clientX: 30,
+ clientY: 30,
+ }));
+ const ripple = voteButton.querySelector('.ldr-ripple');
+ expect(ripple).not.toBeNull();
+ expect(ripple.style.width).toBe('40px');
+ expect(ripple.style.height).toBe('40px');
+ expect(ripple.style.left).toBe('0px');
+ expect(ripple.style.top).toBe('-10px');
+
+ topicPill.click();
+ expect(topicPill.style.transform).toBe('scale(0.95)');
+ await vi.advanceTimersByTimeAsync(150);
+ expect(topicPill.style.transform).toBe('scale(1)');
+ await vi.advanceTimersByTimeAsync(450);
+ expect(voteButton.querySelector('.ldr-ripple')).toBeNull();
+
+ expect(document.head.querySelector('style').textContent)
+ .toContain('pointer-events: none');
+});
+
+it('adds and releases refresh skeleton state without stealing refresh ownership', async () => {
+ const container = document.querySelector('.ldr-news-cards-container');
+
+ refreshButton.click();
+
+ expect(refreshListener).toHaveBeenCalledOnce();
+ expect(inlineRefresh).toHaveBeenCalledOnce();
+ expect(container.style.opacity).toBe('0.5');
+ expect(container.classList.contains('ldr-skeleton-loader')).toBe(true);
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(container.style.opacity).toBe('1');
+ expect(container.classList.contains('ldr-skeleton-loader')).toBe(false);
+});
diff --git a/tests/js/pages/news-feed-ownership-runtime.test.js b/tests/js/pages/news-feed-ownership-runtime.test.js
new file mode 100644
index 0000000000..f7a0de4dc4
--- /dev/null
+++ b/tests/js/pages/news-feed-ownership-runtime.test.js
@@ -0,0 +1,329 @@
+/** Runtime ownership coverage for subscription-driven news feed loads. */
+
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function response(payload) {
+ return {
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function compileFeedRuntime() {
+ const clearSemanticState = vi.fn();
+ const renderNewsItems = vi.fn();
+ const extractTrendingTopics = vi.fn();
+ const updateBulkActionsBar = vi.fn();
+ const loadVotesForNewsItems = vi.fn().mockResolvedValue(undefined);
+ const showAlert = vi.fn();
+
+ const runtime = compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: [
+ 'stopNewsResearchPoll',
+ 'beginNewsResearchPoll',
+ 'isCurrentNewsResearchPoll',
+ 'clearStoredNewsResearch',
+ 'findNewsResearchCard',
+ 'removeNewsResearchCards',
+ 'endNewsResearchPollWithFeed',
+ 'completeNewsResearchPoll',
+ 'selectSubscription',
+ 'loadNewsFeed',
+ ],
+ dependencies: {
+ clearSemanticState,
+ showAlert,
+ safeRenderHTML: (container, content) => {
+ container.textContent = content;
+ },
+ updateFeedHeader: vi.fn(),
+ loadSavedNewsFeed: vi.fn(),
+ renderNewsItems,
+ extractTrendingTopics,
+ updateBulkActionsBar,
+ loadVotesForNewsItems,
+ SafeLogger: {
+ log: vi.fn(),
+ error: vi.fn(),
+ },
+ },
+ preamble: `
+ let activeSubscription = 'all';
+ let newsItems = [];
+ let newsSemanticMatches = null;
+ let newsFeedRequestId = 0;
+ let newsFeedRequestIntent = 'generic';
+ let newsResearchPollId = 0;
+ let activeNewsResearchPoll = null;
+ let newsResearchReloadTimer = null;
+ let newsResearchRestoreId = 0;
+ `,
+ returnExpression: `({
+ selectSubscription,
+ loadNewsFeed,
+ beginNewsResearchPoll,
+ endNewsResearchPollWithFeed,
+ completeNewsResearchPoll,
+ getActiveSubscription: () => activeSubscription,
+ getNewsItems: () => newsItems,
+ })`,
+ });
+
+ return {
+ ...runtime,
+ clearSemanticState,
+ renderNewsItems,
+ extractTrendingTopics,
+ updateBulkActionsBar,
+ loadVotesForNewsItems,
+ showAlert,
+ };
+}
+
+beforeEach(() => {
+ document.body.innerHTML = '<section id="news-feed-content"></section>';
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('keeps a slow older subscription feed from replacing the newer selection', async () => {
+ const olderFetch = deferred();
+ const olderResponse = response({
+ news_items: [{ id: 'old-news', headline: 'Old subscription' }],
+ });
+ const newerResponse = response({
+ news_items: [{ id: 'new-news', headline: 'New subscription' }],
+ });
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderFetch.promise)
+ .mockResolvedValueOnce(newerResponse);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const olderLoad = runtime.selectSubscription('subscription-old');
+ const newerLoad = runtime.selectSubscription('subscription-new');
+ await newerLoad;
+
+ olderFetch.resolve(olderResponse);
+ await olderLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feed?limit=20&use_cache=true&subscription_id=subscription-old',
+ '/news/api/feed?limit=20&use_cache=true&subscription_id=subscription-new',
+ ]);
+ expect(runtime.getActiveSubscription()).toBe('subscription-new');
+ expect(runtime.getNewsItems()).toEqual([
+ { id: 'new-news', headline: 'New subscription' },
+ ]);
+ expect(newerResponse.json).toHaveBeenCalledOnce();
+ expect(olderResponse.json).not.toHaveBeenCalled();
+ expect(runtime.renderNewsItems).toHaveBeenCalledOnce();
+ expect(runtime.extractTrendingTopics).toHaveBeenCalledOnce();
+ expect(runtime.updateBulkActionsBar).toHaveBeenCalledOnce();
+ expect(runtime.loadVotesForNewsItems).toHaveBeenCalledOnce();
+ expect(runtime.clearSemanticState).toHaveBeenCalledTimes(2);
+});
+
+it('drops an older payload that finishes JSON parsing after the newer feed', async () => {
+ const olderJson = deferred();
+ const olderResponse = {
+ ok: true,
+ status: 200,
+ json: vi.fn(() => olderJson.promise),
+ };
+ const newerResponse = response({
+ news_items: [{ id: 'newest-news', headline: 'Newest selection' }],
+ });
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(olderResponse)
+ .mockResolvedValueOnce(newerResponse);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const olderLoad = runtime.selectSubscription('subscription-parsing');
+ await vi.waitFor(() => expect(olderResponse.json).toHaveBeenCalledOnce());
+
+ await runtime.selectSubscription('subscription-newest');
+ olderJson.resolve({
+ news_items: [{ id: 'parsed-too-late', headline: 'Stale payload' }],
+ });
+ await olderLoad;
+
+ expect(runtime.getNewsItems()).toEqual([
+ { id: 'newest-news', headline: 'Newest selection' },
+ ]);
+ expect(runtime.renderNewsItems).toHaveBeenCalledOnce();
+ expect(runtime.loadVotesForNewsItems).toHaveBeenCalledOnce();
+});
+
+it('does not let a delayed completion reload supersede a newer focused feed', async () => {
+ vi.useFakeTimers();
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ news_items: [{ id: 'focused', headline: 'Migration focused result' }],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const poll = runtime.beginNewsResearchPoll('completed-run');
+ runtime.completeNewsResearchPoll(poll, 'Completed');
+ await runtime.loadNewsFeed('migration');
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/feed?limit=20&use_cache=true&focus=migration',
+ );
+ expect(runtime.getNewsItems()).toEqual([
+ { id: 'focused', headline: 'Migration focused result' },
+ ]);
+ expect(runtime.showAlert).toHaveBeenCalledWith('Completed', 'success');
+ vi.useRealTimers();
+});
+
+it.each(['completion', 'failure'])(
+ 'preserves a focused feed started before poll %s cleanup',
+ async mode => {
+ vi.useFakeTimers();
+ const focusedResponse = deferred();
+ const fetchMock = vi.fn(() => focusedResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const poll = runtime.beginNewsResearchPoll(`terminal-${mode}`);
+ const focusedLoad = runtime.loadNewsFeed('migration');
+ if (mode === 'completion') {
+ runtime.completeNewsResearchPoll(poll, 'Completed');
+ await vi.advanceTimersByTimeAsync(1000);
+ } else {
+ runtime.endNewsResearchPollWithFeed(poll, 'Failed');
+ }
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ focusedResponse.resolve(response({
+ news_items: [{
+ id: `focused-${mode}`,
+ headline: 'Migration focus survives',
+ }],
+ }));
+ await focusedLoad;
+
+ expect(runtime.getNewsItems()).toEqual([{
+ id: `focused-${mode}`,
+ headline: 'Migration focus survives',
+ }]);
+ expect(runtime.renderNewsItems).toHaveBeenCalledOnce();
+ },
+);
+
+it.each(['completion', 'failure'])(
+ 'preserves a subscription feed started before poll %s cleanup',
+ async mode => {
+ vi.useFakeTimers();
+ const subscriptionResponse = deferred();
+ const fetchMock = vi.fn(() => subscriptionResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const poll = runtime.beginNewsResearchPoll(`subscription-${mode}`);
+ const subscriptionLoad = runtime.selectSubscription('migration-news');
+ if (mode === 'completion') {
+ runtime.completeNewsResearchPoll(poll, 'Completed');
+ await vi.advanceTimersByTimeAsync(1000);
+ } else {
+ runtime.endNewsResearchPollWithFeed(poll, 'Failed');
+ }
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ subscriptionResponse.resolve(response({
+ news_items: [{
+ id: `subscription-${mode}`,
+ headline: 'Selected subscription survives',
+ }],
+ }));
+ await subscriptionLoad;
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/feed?limit=20&use_cache=true&subscription_id=migration-news',
+ );
+ expect(runtime.getNewsItems()).toEqual([{
+ id: `subscription-${mode}`,
+ headline: 'Selected subscription survives',
+ }]);
+ expect(runtime.renderNewsItems).toHaveBeenCalledOnce();
+ },
+);
+
+it.each(['completion', 'failure'])(
+ 'refreshes a generic feed that started before poll %s cleanup',
+ async mode => {
+ vi.useFakeTimers();
+ const preTerminalResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => preTerminalResponse.promise)
+ .mockResolvedValueOnce(response({
+ news_items: [{
+ id: `post-terminal-${mode}`,
+ headline: 'Post-terminal result',
+ }],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileFeedRuntime();
+
+ const poll = runtime.beginNewsResearchPoll(`generic-${mode}`);
+ const preTerminalLoad = runtime.loadNewsFeed();
+ if (mode === 'completion') {
+ runtime.completeNewsResearchPoll(poll, 'Completed');
+ await vi.advanceTimersByTimeAsync(1000);
+ } else {
+ runtime.endNewsResearchPollWithFeed(poll, 'Failed');
+ }
+
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ await vi.waitFor(() => {
+ expect(runtime.getNewsItems()).toEqual([{
+ id: `post-terminal-${mode}`,
+ headline: 'Post-terminal result',
+ }]);
+ });
+
+ const staleResponse = response({
+ news_items: [{ id: 'pre-terminal', headline: 'Stale result' }],
+ });
+ preTerminalResponse.resolve(staleResponse);
+ await preTerminalLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feed?limit=20&use_cache=true',
+ '/news/api/feed?limit=20&use_cache=true',
+ ]);
+ expect(staleResponse.json).not.toHaveBeenCalled();
+ expect(runtime.getNewsItems()).toEqual([{
+ id: `post-terminal-${mode}`,
+ headline: 'Post-terminal result',
+ }]);
+ expect(runtime.renderNewsItems).toHaveBeenCalledOnce();
+ },
+);
diff --git a/tests/js/pages/news-lifecycle-runtime.test.js b/tests/js/pages/news-lifecycle-runtime.test.js
new file mode 100644
index 0000000000..6a4dd67812
--- /dev/null
+++ b/tests/js/pages/news-lifecycle-runtime.test.js
@@ -0,0 +1,158 @@
+/** Isolated terminal lifecycle coverage for the real news page runtime. */
+
+const NOW = new Date('2026-09-01T12:00:00.000Z');
+
+function response(payload) {
+ return {
+ ok: true,
+ status: 200,
+ headers: {},
+ json: vi.fn().mockResolvedValue(payload),
+ text: vi.fn().mockResolvedValue(JSON.stringify(payload)),
+ };
+}
+
+function installDom() {
+ document.body.innerHTML = `
+ <header class="ldr-feed-header"><h2>News</h2></header>
+ <section id="news-feed-content"></section>
+ <input id="table-view-toggle" type="checkbox">
+ <input id="news-search" type="search">
+ <button id="search-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <button id="run-template-btn"></button>
+ <input id="impact-filter" type="range" min="0" max="10" value="0">
+ <span class="ldr-impact-value">0+</span>
+ <section id="news-semantic-results"></section>
+ <input id="news-query">
+ <div id="newsSubscriptionModal"></div>
+ <textarea id="news-subscription-query"></textarea>
+ <div class="ldr-time-filter-group">
+ <button class="ldr-filter-btn active" data-time="all"></button>
+ </div>
+ <input id="auto-refresh" type="checkbox">
+ <button id="refresh-feed-btn"></button>
+ <div id="recent-searches"></div>
+ <div id="trending-topics"></div>
+ <div id="priority-status" style="display: none">
+ <span id="priority-message"></span>
+ </div>
+ <div id="news-alert"></div>
+ `;
+}
+
+let fetchMock;
+
+beforeAll(async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ localStorage.clear();
+ sessionStorage.clear();
+ installDom();
+
+ const purify = {
+ addHook: vi.fn(),
+ sanitize: vi.fn(dirty => {
+ const template = document.createElement('template');
+ // eslint-disable-next-line no-unsanitized/property -- controlled test-only HTML fixture.
+ template.innerHTML = String(dirty);
+ return template.content.cloneNode(true);
+ }),
+ };
+ globalThis.DOMPurify = purify;
+ window.DOMPurify = purify;
+ window.RESEARCH_STATUS = {
+ IN_PROGRESS: 'in_progress',
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ SUSPENDED: 'suspended',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'failed', 'error', 'cancelled', 'suspended',
+ ]);
+
+ const feedItems = [{
+ id: 'news-one',
+ research_id: 'research-one',
+ headline: 'FastAPI migration reaches production',
+ impact_score: 9,
+ created_at: NOW.toISOString(),
+ topics: [],
+ links: [],
+ }, {
+ id: 'news-two',
+ research_id: 'research-two',
+ headline: 'Realtime migration follow-up',
+ impact_score: 5,
+ created_at: NOW.toISOString(),
+ topics: [],
+ links: [],
+ }];
+
+ fetchMock = vi.fn(async input => {
+ const url = String(input);
+ if (url === '/news/api/subscriptions/current') {
+ return response({ subscriptions: [] });
+ }
+ if (url.startsWith('/news/api/feed?')) {
+ return response({ news_items: feedItems });
+ }
+ if (url === '/news/api/feedback/batch') {
+ return response({ votes: {} });
+ }
+ if (url === '/news/api/search-history') {
+ return response({ search_history: [] });
+ }
+ if (url === '/history/api') return response({ items: [] });
+ return response({});
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/config/constants.js');
+ await import('@js/config/urls.js');
+ await import('@js/security/url-validator.js');
+ await import('@js/security/xss-protection.js');
+ await import('@js/pages/news.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-news-item')).toHaveLength(2);
+ expect(fetchMock).toHaveBeenCalledWith('/history/api');
+ });
+});
+
+afterAll(() => {
+ window.dispatchEvent(new Event('pagehide'));
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ sessionStorage.clear();
+ document.body.replaceChildren();
+ delete window.DOMPurify;
+});
+
+it('persists visit/read state and retires scheduled work on page exit', async () => {
+ window.markAllAsRead();
+ localStorage.removeItem('news_read_ids');
+
+ const unloadTime = new Date().toISOString();
+ window.dispatchEvent(new Event('beforeunload'));
+ expect(localStorage.getItem('news_last_visit')).toBe(unloadTime);
+ expect(JSON.parse(localStorage.getItem('news_read_ids')))
+ .toEqual(expect.arrayContaining(['news-one', 'news-two']));
+
+ const priorityCalls = fetchMock.mock.calls.filter(([url]) => (
+ url === '/history/api'
+ )).length;
+ window.dispatchEvent(new Event('pagehide'));
+ await vi.advanceTimersByTimeAsync(30000);
+ expect(fetchMock.mock.calls.filter(([url]) => (
+ url === '/history/api'
+ ))).toHaveLength(priorityCalls);
+});
diff --git a/tests/js/pages/news-priority-status.test.js b/tests/js/pages/news-priority-status.test.js
new file mode 100644
index 0000000000..c9edecbf77
--- /dev/null
+++ b/tests/js/pages/news-priority-status.test.js
@@ -0,0 +1,158 @@
+/**
+ * Behavior coverage for the non-news research banner on the news page.
+ *
+ * checkPriorityStatus is intentionally private, so these tests enter through
+ * the real DOMContentLoaded initialization and retain the polling callback
+ * that initializeNewsPage registers for subsequent checks.
+ */
+
+import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
+
+let fetchMock;
+let historyPayload = { items: [] };
+let originalFetch;
+let priorityPoll;
+let setIntervalSpy;
+
+function response(body) {
+ return {
+ ok: true,
+ status: 200,
+ headers: {},
+ json: () => Promise.resolve(body),
+ text: () => Promise.resolve(''),
+ };
+}
+
+async function checkPriorityWith(items) {
+ historyPayload = { items };
+ fetchMock.mockClear();
+ await priorityPoll();
+}
+
+beforeAll(async () => {
+ originalFetch = globalThis.fetch;
+ localStorage.clear();
+ sessionStorage.clear();
+
+ window.RESEARCH_STATUS = {
+ IN_PROGRESS: 'in_progress',
+ QUEUED: 'queued',
+ PENDING: 'pending',
+ COMPLETED: 'completed',
+ FAILED: 'failed',
+ ERROR: 'error',
+ CANCELLED: 'cancelled',
+ SUSPENDED: 'suspended',
+ };
+ window.RESEARCH_TERMINAL_STATES = new Set([
+ 'completed', 'failed', 'error', 'cancelled', 'suspended',
+ ]);
+ fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url === '/history/api') return Promise.resolve(response(historyPayload));
+ if (url.includes('/news/api/subscriptions/current')) {
+ return Promise.resolve(response({ subscriptions: [] }));
+ }
+ if (url.includes('/news/api/feed')) {
+ return Promise.resolve(response({ news_items: [] }));
+ }
+ if (url.includes('/news/api/search-history')) {
+ return Promise.resolve(response({ search_history: [] }));
+ }
+ return Promise.resolve(response({}));
+ });
+ globalThis.fetch = fetchMock;
+
+ setIntervalSpy = vi.spyOn(globalThis, 'setInterval').mockImplementation((callback, delay) => {
+ if (delay === 30000) priorityPoll = callback;
+ return 1;
+ });
+
+ document.body.innerHTML = `
+ <div class="ldr-feed-header"><h2>News</h2></div>
+ <div id="news-feed-content"></div>
+ <input id="table-view-toggle" type="checkbox">
+ <table><tbody id="news-table-body"></tbody></table>
+ <input id="news-search" type="text">
+ <button id="search-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <button id="run-template-btn"></button>
+ <input id="impact-filter" type="range" min="0" max="10" value="0">
+ <span class="ldr-impact-value"></span>
+ <div id="news-semantic-results"></div>
+ <div id="news-query"></div>
+ <div id="newsSubscriptionModal"></div>
+ <div id="news-subscription-query"></div>
+ <div class="ldr-time-filter-group"><button class="ldr-filter-btn"></button></div>
+ <input id="auto-refresh" type="checkbox">
+ <button id="refresh-feed-btn"></button>
+ <div id="recent-searches"></div>
+ <div id="trending-topics"></div>
+ <div id="priority-status" style="display: none">
+ <span id="priority-message"></span>
+ </div>
+ `;
+
+ await import('@js/config/constants.js');
+ await import('@js/security/xss-protection.js');
+ await import('@js/pages/news.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(priorityPoll).toEqual(expect.any(Function));
+ expect(fetchMock).toHaveBeenCalledWith('/history/api');
+ });
+});
+
+afterAll(() => {
+ window.dispatchEvent(new Event('pagehide'));
+ setIntervalSpy.mockRestore();
+ globalThis.fetch = originalFetch;
+ document.body.replaceChildren();
+});
+
+describe('pages/news.js priority status', () => {
+ it('uses the canonical history endpoint and shows an active non-news item from the items envelope', async () => {
+ await checkPriorityWith([{
+ id: 'research-42',
+ query: 'Investigate the migration behavior',
+ status: 'in_progress',
+ metadata: { is_news_search: false },
+ }]);
+
+ const requestedUrls = fetchMock.mock.calls.map(([url]) => String(url));
+ expect(requestedUrls).toEqual(['/history/api']);
+ expect(requestedUrls).not.toContain('/api/history');
+
+ const status = document.getElementById('priority-status');
+ const message = document.getElementById('priority-message');
+ const link = message.querySelector('a');
+ expect(status.style.display).toBe('block');
+ expect(message.textContent).toContain('Investigate the migration behavior');
+ expect(link?.getAttribute('href')).toBe('/progress/research-42');
+ });
+
+ it('hides the banner when the only active item is a news search', async () => {
+ const status = document.getElementById('priority-status');
+ status.style.display = 'block';
+
+ await checkPriorityWith([{
+ id: 'news-17',
+ query: 'Today in technology',
+ status: 'queued',
+ metadata: { is_news_search: true },
+ }]);
+
+ expect(status.style.display).toBe('none');
+ });
+
+ it('hides the banner when the items envelope is empty', async () => {
+ const status = document.getElementById('priority-status');
+ status.style.display = 'block';
+
+ await checkPriorityWith([]);
+
+ expect(status.style.display).toBe('none');
+ });
+});
diff --git a/tests/js/pages/news-research-monitor-runtime.test.js b/tests/js/pages/news-research-monitor-runtime.test.js
new file mode 100644
index 0000000000..e474108087
--- /dev/null
+++ b/tests/js/pages/news-research-monitor-runtime.test.js
@@ -0,0 +1,447 @@
+/** Runtime ownership and recovery coverage for monitorResearch(). */
+
+import { resolve } from 'node:path';
+
+import '@js/config/urls.js';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function response(payload, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function compileMonitorRuntime() {
+ const showAlert = vi.fn();
+ const loadNewsFeed = vi.fn().mockResolvedValue(undefined);
+ const ResearchStates = {
+ isInProgress: status => status === 'in_progress',
+ isActive: status => ['queued', 'pending', 'in_progress'].includes(status),
+ isCompleted: status => status === 'completed',
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'error',
+ 'cancelled',
+ ].includes(status),
+ };
+
+ const runtime = compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: [
+ 'cleanupNewsPage',
+ 'stopNewsResearchPoll',
+ 'beginNewsResearchPoll',
+ 'isCurrentNewsResearchPoll',
+ 'clearStoredNewsResearch',
+ 'findNewsResearchCard',
+ 'removeNewsResearchCards',
+ 'endNewsResearchPollWithFeed',
+ 'completeNewsResearchPoll',
+ 'monitorResearch',
+ 'checkActiveNewsResearch',
+ 'pollForNewsResearchResults',
+ ],
+ dependencies: {
+ showAlert,
+ loadNewsFeed,
+ ResearchStates,
+ URLBuilder: window.URLBuilder,
+ escapeHtml: value => String(value),
+ SafeLogger: {
+ log: vi.fn(),
+ error: vi.fn(),
+ warn: vi.fn(),
+ },
+ },
+ preamble: `
+ let autoRefreshInterval = null;
+ let priorityCheckInterval = null;
+ let refreshIndicatorInterval = null;
+ let newsSemanticTimer = null;
+ let newsFeedRequestId = 0;
+ let newsFeedRequestIntent = 'generic';
+ let newsResearchPollId = 0;
+ let activeNewsResearchPoll = null;
+ let newsResearchReloadTimer = null;
+ let newsResearchRestoreId = 0;
+ let searchHistoryLoadRequestId = 0;
+ `,
+ returnExpression: `({
+ cleanupNewsPage,
+ monitorResearch,
+ checkActiveNewsResearch,
+ pollForNewsResearchResults,
+ })`,
+ });
+
+ return { ...runtime, showAlert, loadNewsFeed };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ localStorage.clear();
+ document.body.innerHTML = `
+ <section id="news-feed-content">
+ <article id="existing-news">Existing news</article>
+ </section>
+ `;
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ document.body.replaceChildren();
+});
+
+it('allows only one monitor status request in flight and settles once', async () => {
+ const pendingStatus = deferred();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'in_progress',
+ progress: 15,
+ query: 'Migration monitor',
+ }))
+ .mockImplementationOnce(() => pendingStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ await runtime.monitorResearch('monitor-3299');
+ expect(document.querySelector('[data-research-id="monitor-3299"]'))
+ .not.toBeNull();
+
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ vi.advanceTimersByTime(6000);
+ await Promise.resolve();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+
+ pendingStatus.resolve(response({
+ status: 'completed',
+ progress: 100,
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Test run completed! Loading results...',
+ 'success',
+ );
+
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+});
+
+it('cleans monitor state and restores the feed after a status network error', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'in_progress',
+ progress: 25,
+ query: 'Network recovery',
+ }))
+ .mockRejectedValueOnce(new Error('offline'));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ await runtime.monitorResearch('monitor-network');
+ expect(localStorage.getItem('active_news_research')).not.toBeNull();
+ expect(document.querySelector('[data-research-id="monitor-network"]'))
+ .not.toBeNull();
+
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Error checking research status. Please try again.',
+ 'error',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(9000);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+});
+
+it('retires an in-flight monitor on page cleanup without repainting after it settles', async () => {
+ const pendingStatus = deferred();
+ const fetchMock = vi.fn(() => pendingStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ const monitoring = runtime.monitorResearch('cleanup-live', 'Leave the page');
+ await Promise.resolve();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'cleanup-live' });
+ expect(vi.getTimerCount()).toBe(1);
+
+ runtime.cleanupNewsPage();
+
+ expect(vi.getTimerCount()).toBe(0);
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'cleanup-live' });
+
+ pendingStatus.resolve(response({
+ status: 'completed',
+ progress: 100,
+ }));
+ await monitoring;
+
+ expect(runtime.showAlert).not.toHaveBeenCalled();
+ expect(runtime.loadNewsFeed).not.toHaveBeenCalled();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'cleanup-live' });
+});
+
+it.each(['completed', 'in_progress'])(
+ 'does not let stale restored %s run A replace a directly started run B',
+ async staleStatus => {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: 'restore-a',
+ query: 'Old restored run',
+ startTime: new Date().toISOString(),
+ }));
+ const staleRestore = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => staleRestore.promise)
+ .mockResolvedValueOnce(response({
+ status: 'in_progress',
+ progress: 30,
+ query: 'Current direct run',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ const restoring = runtime.checkActiveNewsResearch();
+ await runtime.monitorResearch('direct-b', 'Current direct run');
+ staleRestore.resolve(response({
+ status: staleStatus,
+ progress: staleStatus === 'completed' ? 100 : 20,
+ query: 'Old restored run',
+ }));
+ await restoring;
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'direct-b' });
+ expect(document.querySelector('[data-research-id="direct-b"]'))
+ .not.toBeNull();
+ expect(document.querySelector('[data-research-id="restore-a"]'))
+ .toBeNull();
+ expect(runtime.showAlert).not.toHaveBeenCalledWith(
+ 'Your news analysis has completed! Loading results...',
+ 'success',
+ );
+ },
+);
+
+it.each(['queued', 'pending'])(
+ 'resumes a stored %s run using the production active-state semantics',
+ async activeStatus => {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: `restore-${activeStatus}`,
+ query: `${activeStatus} migration news`,
+ startTime: new Date().toISOString(),
+ }));
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({ status: activeStatus, progress: 0 }))
+ .mockResolvedValueOnce(response({
+ status: activeStatus,
+ progress: 0,
+ query: `${activeStatus} migration news`,
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ await runtime.checkActiveNewsResearch();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: `restore-${activeStatus}` });
+ await vi.waitFor(() => {
+ expect(document.querySelector(
+ `[data-research-id="restore-${activeStatus}"]`,
+ )).not.toBeNull();
+ });
+ },
+);
+
+it('does not duplicate a run that is already monitoring during page restore', async () => {
+ const initialStatus = deferred();
+ const fetchMock = vi.fn(() => initialStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ const monitoring = runtime.monitorResearch('already-live', 'Live run');
+ await runtime.checkActiveNewsResearch();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ initialStatus.resolve(response({
+ status: 'in_progress',
+ progress: 5,
+ query: 'Live run',
+ }));
+ await monitoring;
+ expect(document.querySelector('[data-research-id="already-live"]'))
+ .not.toBeNull();
+});
+
+it('times out a monitor whose initial status request never settles', async () => {
+ const initialStatus = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => initialStatus.promise));
+ const runtime = compileMonitorRuntime();
+
+ const monitoring = runtime.monitorResearch('hung-initial', 'Hung run');
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Research monitoring timed out. Please try again.',
+ 'warning',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ initialStatus.resolve(response({ status: 'in_progress', progress: 10 }));
+ await monitoring;
+ expect(document.querySelector('[data-research-id="hung-initial"]'))
+ .toBeNull();
+});
+
+it('bounds a hung page-restore probe without discarding resumable state', async () => {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: 'hung-restore',
+ query: 'Retry this restore later',
+ startTime: new Date().toISOString(),
+ }));
+ let restoreSignal;
+ const fetchMock = vi.fn((url, options) => {
+ restoreSignal = options.signal;
+ return new Promise(() => {});
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ const restoring = runtime.checkActiveNewsResearch();
+ await vi.advanceTimersByTimeAsync(10000);
+ await restoring;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(restoreSignal.aborted).toBe(true);
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'hung-restore' });
+ expect(runtime.showAlert).not.toHaveBeenCalled();
+ expect(runtime.loadNewsFeed).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('keeps the restore deadline active while the status body is hung', async () => {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: 'hung-restore-body',
+ query: 'Retry the body later',
+ startTime: new Date().toISOString(),
+ }));
+ const statusBody = deferred();
+ let restoreSignal;
+ const fetchMock = vi.fn((url, options) => {
+ restoreSignal = options.signal;
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: vi.fn(() => statusBody.promise),
+ });
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ const restoring = runtime.checkActiveNewsResearch();
+ await vi.advanceTimersByTimeAsync(10000);
+ await restoring;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ 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.loadNewsFeed).not.toHaveBeenCalled();
+ expect(vi.getTimerCount()).toBe(0);
+});
+
+it('hands an active restore to monitoring without blocking page bootstrap', async () => {
+ localStorage.setItem('active_news_research', JSON.stringify({
+ researchId: 'active-restore-handoff',
+ query: 'Continue in the background',
+ startTime: new Date().toISOString(),
+ }));
+ const monitorStatus = deferred();
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({ status: 'queued', progress: 0 }))
+ .mockImplementationOnce(() => monitorStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+
+ await expect(runtime.checkActiveNewsResearch()).resolves.toBeUndefined();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({ researchId: 'active-restore-handoff' });
+ expect(runtime.showAlert).not.toHaveBeenCalled();
+ expect(runtime.loadNewsFeed).not.toHaveBeenCalled();
+});
+
+it('uses a wall-clock timeout while a subscription status request is hung', async () => {
+ const pendingStatus = deferred();
+ const fetchMock = vi.fn(() => pendingStatus.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileMonitorRuntime();
+ const activeCard = document.createElement('article');
+ activeCard.className = 'ldr-active-research-card';
+ activeCard.dataset.researchId = 'hung-subscription';
+ document.getElementById('news-feed-content').prepend(activeCard);
+
+ await runtime.pollForNewsResearchResults(
+ 'hung-subscription',
+ 'Hung subscription',
+ );
+ await vi.advanceTimersByTimeAsync(5 * 60 * 1000);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('[data-research-id="hung-subscription"]'))
+ .toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Research taking too long. Check the progress page.',
+ 'warning',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ pendingStatus.resolve(response({ status: 'completed', progress: 100 }));
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(runtime.showAlert).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/pages/news-search-history-mutations.test.js b/tests/js/pages/news-search-history-mutations.test.js
new file mode 100644
index 0000000000..5a8f0c3b7f
--- /dev/null
+++ b/tests/js/pages/news-search-history-mutations.test.js
@@ -0,0 +1,189 @@
+/**
+ * Runtime contracts for the two mutating consumers of the migrated news
+ * search-history endpoint. The functions are executed from the shipped page
+ * source so method, CSRF, credentials, and body drift fail together.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`async\\s+function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in news.js`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function compileHarness(overrides = {}) {
+ const source = readFileSync(NEWS_SOURCE_PATH, 'utf8');
+ const functions = ['saveSearchHistory', 'clearSearchHistory', 'loadSearchHistory', 'addToSearchHistory']
+ .map(name => extractFunction(source, name))
+ .join('\n');
+ const factory = new Function( // eslint-disable-line no-new-func
+ 'getCSRFToken',
+ 'displayRecentSearches',
+ 'showAlert',
+ 'SafeLogger',
+ `
+ let searchHistory = [{ query: 'existing search' }];
+ let searchHistoryMutationGeneration = 0;
+ let searchHistoryLoadRequestId = 0;
+ let searchHistoryWriteQueue = Promise.resolve();
+ let newsItems = [];
+ ${functions}
+ return {
+ saveSearchHistory,
+ clearSearchHistory,
+ addToSearchHistory,
+ getSearchHistory: () => searchHistory,
+ };
+ `,
+ );
+ return factory(
+ overrides.getCSRFToken || (() => 'history-csrf'),
+ overrides.displayRecentSearches || vi.fn(),
+ overrides.showAlert || vi.fn(),
+ overrides.SafeLogger || { log: vi.fn(), error: vi.fn() },
+ );
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it('posts the current query, type, and count with same-origin CSRF', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ status: 200,
+ json: vi.fn().mockResolvedValue({ success: true }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const harness = compileHarness();
+
+ await harness.saveSearchHistory('FastAPI migrations', 'deep', 17);
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/search-history', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'history-csrf',
+ },
+ credentials: 'same-origin',
+ body: JSON.stringify({
+ query: 'FastAPI migrations',
+ type: 'deep',
+ resultCount: 17,
+ }),
+ });
+});
+
+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();
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('confirm', vi.fn().mockReturnValue(true));
+ const harness = compileHarness({ displayRecentSearches, showAlert });
+
+ await harness.clearSearchHistory();
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/search-history', {
+ method: 'DELETE',
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': 'history-csrf' },
+ });
+ expect(harness.getSearchHistory()).toEqual([]);
+ expect(displayRecentSearches).toHaveBeenCalledOnce();
+ expect(showAlert).toHaveBeenCalledWith(
+ 'Search history cleared',
+ 'success',
+ );
+});
+
+it('orders old insert, clear, and a newer search by user intent', async () => {
+ let releaseInsert;
+ const insertion = new Promise(resolveInsert => { releaseInsert = resolveInsert; });
+ let server = [{ query: 'existing' }];
+ const writes = [];
+ vi.stubGlobal('confirm', () => true);
+ vi.stubGlobal('fetch', vi.fn(async (_url, options) => {
+ if (options.method === 'POST') {
+ const query = JSON.parse(options.body).query;
+ writes.push(`POST ${query}`);
+ if (query === 'older') await insertion;
+ server.push({ query });
+ } else if (options.method === 'DELETE') {
+ writes.push('DELETE');
+ server = [];
+ }
+ const snapshot = [...server];
+ return { ok: true, status: 200, json: async () => ({ search_history: snapshot }) };
+ }));
+ const harness = compileHarness();
+ const older = harness.addToSearchHistory('older');
+ await Promise.resolve();
+ const clear = harness.clearSearchHistory();
+ const newer = harness.addToSearchHistory('newer');
+ await Promise.resolve();
+ expect(writes).toEqual(['POST older']);
+ releaseInsert();
+ await Promise.all([older, clear, newer]);
+ expect(writes).toEqual(['POST older', 'DELETE', 'POST newer']);
+ expect(server).toEqual([{ query: 'newer' }]);
+ expect(harness.getSearchHistory()).toEqual(server);
+});
+
+it('releases the history queue after a failed insert or delete', async () => {
+ vi.stubGlobal('confirm', () => true);
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(new Error('insert failed'))
+ .mockRejectedValueOnce(new Error('delete failed'))
+ .mockResolvedValueOnce({ status: 200, json: async () => ({ status: 'success' }) });
+ vi.stubGlobal('fetch', fetchMock);
+ const harness = compileHarness();
+ await Promise.all([
+ harness.saveSearchHistory('first', 'quick', 0),
+ harness.clearSearchHistory(),
+ harness.saveSearchHistory('last', 'quick', 0),
+ ]);
+ expect(fetchMock.mock.calls.map(([, options]) => options.method)).toEqual(['POST', 'DELETE', 'POST']);
+});
+
+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 confirmMock = vi.fn().mockReturnValueOnce(false).mockReturnValue(true);
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('confirm', confirmMock);
+ const harness = compileHarness({ displayRecentSearches, showAlert });
+
+ await harness.clearSearchHistory();
+ expect(fetchMock).not.toHaveBeenCalled();
+
+ await harness.clearSearchHistory();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(harness.getSearchHistory()).toEqual([
+ { query: 'existing search' },
+ ]);
+ expect(displayRecentSearches).not.toHaveBeenCalled();
+ expect(showAlert).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.js
new file mode 100644
index 0000000000..f65d574207
--- /dev/null
+++ b/tests/js/pages/news-semantic-search-runtime.test.js
@@ -0,0 +1,271 @@
+/**
+ * Runtime contracts for the news page's migrated collection-search consumers.
+ *
+ * The checked-in functions are executed with the production URL builder and
+ * semantic merge helper. This pins the FastAPI request, result filtering,
+ * tier ordering, and in-flight request ownership without copying the browser
+ * implementation into the fixture.
+ */
+
+import { resolve } from 'node:path';
+
+import '@js/config/urls.js';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function response(payload, ok = true) {
+ return {
+ ok,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((fulfill, reject) => {
+ resolvePromise = fulfill;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
+function compileNewsSearchRuntime({
+ items,
+ collectionId = 'news-collection-3299',
+ csrfToken = 'csrf-news-search',
+ renderNewsItems = vi.fn(),
+ showAlert = vi.fn(),
+} = {}) {
+ const newsCardConfig = {
+ getId: result => result.research_id || '',
+ getTitle: result => result.research_title || 'Untitled',
+ getUrl: () => '#',
+ getBadges: () => [{ icon: 'newspaper', label: 'News' }],
+ getDate: result => result.research_created_at,
+ getSubtitle: () => null,
+ };
+
+ return compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: ['runNewsSemanticSearch', 'runNewsHybridSearch'],
+ dependencies: {
+ initialItems: items || [],
+ initialCollectionId: collectionId,
+ csrfToken,
+ renderNewsItems,
+ showAlert,
+ NEWS_CARD_CONFIG: newsCardConfig,
+ URLBuilder: window.URLBuilder,
+ URLS: window.URLS,
+ },
+ preamble: `
+ const NEWS_SM = {
+ HYBRID: 'hybrid',
+ TEXT: 'text',
+ SEMANTIC: 'semantic',
+ };
+ let newsSearchMode = NEWS_SM.HYBRID;
+ let newsCollectionId = initialCollectionId;
+ let newsSearchId = 0;
+ let newsItems = initialItems;
+ let newsSemanticMatches = null;
+ const getCSRFToken = () => csrfToken;
+ `,
+ returnExpression: `({
+ runNewsSemanticSearch,
+ runNewsHybridSearch,
+ setMode: value => { newsSearchMode = value; },
+ getItems: () => newsItems,
+ getMatches: () => newsSemanticMatches,
+ })`,
+ });
+}
+
+function renderSearchSurface() {
+ document.body.innerHTML = `
+ <section id="news-feed-content"></section>
+ <section id="news-semantic-results" style="display: none"></section>
+ `;
+}
+
+beforeEach(() => {
+ renderSearchSurface();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('posts semantic searches with CSRF and renders only current news results', async () => {
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ success: true,
+ results: [
+ {
+ research_id: 'news-1',
+ research_title: 'Migration match',
+ similarity: 94,
+ },
+ {
+ research_id: 3299,
+ research_title: 'Numeric news ID',
+ similarity: 87,
+ },
+ {
+ research_id: 'unrelated-research',
+ research_title: 'Not in the news feed',
+ similarity: 99,
+ },
+ { research_title: 'Missing research ID', similarity: 100 },
+ ],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileNewsSearchRuntime({
+ items: [
+ { id: 'card-1', research_id: 'news-1' },
+ { id: 'card-2', research_id: 3299 },
+ ],
+ });
+ runtime.setMode('semantic');
+
+ await runtime.runNewsSemanticSearch('FastAPI migration');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/collections/news-collection-3299/search',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-search',
+ },
+ body: JSON.stringify({
+ query: 'FastAPI migration',
+ limit: 50,
+ }),
+ },
+ );
+ expect(document.getElementById('news-feed-content').style.display)
+ .toBe('none');
+ const cards = document.querySelectorAll(
+ '#news-semantic-results .ldr-semantic-result',
+ );
+ expect(Array.from(cards, card => card.dataset.id))
+ .toEqual(['news-1', '3299']);
+ expect(document.body.textContent).not.toContain('Not in the news feed');
+ expect(document.body.textContent).not.toContain('Missing research ID');
+});
+
+it('does not let a rejected stale semantic request replace newer results', async () => {
+ const olderRequest = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderRequest.promise)
+ .mockResolvedValueOnce(response({
+ success: true,
+ results: [{
+ research_id: 'news-new',
+ research_title: 'Newest result',
+ similarity: 91,
+ }],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileNewsSearchRuntime({
+ items: [{ id: 'new-card', research_id: 'news-new' }],
+ });
+ runtime.setMode('semantic');
+
+ const olderSearch = runtime.runNewsSemanticSearch('older query');
+ await runtime.runNewsSemanticSearch('newer query');
+ olderRequest.reject(new Error('older request lost its connection'));
+ await olderSearch;
+
+ const container = document.getElementById('news-semantic-results');
+ expect(container.textContent).toContain('Newest result');
+ expect(container.textContent).not.toContain('Error performing semantic search');
+});
+
+it('filters hybrid matches and applies the real tier-one/tier-two ordering', async () => {
+ const firstItem = { id: 'card-a', research_id: 'news-a' };
+ const secondItem = { id: 'card-b', research_id: 'news-b' };
+ const renderNewsItems = vi.fn();
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ success: true,
+ results: [
+ {
+ research_id: 'news-b',
+ similarity: 92,
+ snippet: 'Semantic match',
+ },
+ {
+ research_id: 'not-a-current-news-item',
+ similarity: 99,
+ snippet: 'Must be filtered',
+ },
+ ],
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileNewsSearchRuntime({
+ items: [firstItem, secondItem],
+ renderNewsItems,
+ });
+
+ await runtime.runNewsHybridSearch('ownership races');
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/collections/news-collection-3299/search',
+ expect.objectContaining({
+ method: 'POST',
+ body: JSON.stringify({ query: 'ownership races', limit: 50 }),
+ }),
+ );
+ expect(runtime.getItems()).toEqual([secondItem, firstItem]);
+ expect(Array.from(runtime.getMatches().entries())).toEqual([
+ ['news-b', { similarity: 92, snippet: 'Semantic match' }],
+ ]);
+ expect(renderNewsItems).toHaveBeenCalledOnce();
+ expect(renderNewsItems).toHaveBeenCalledWith('ownership races');
+ expect(document.getElementById('news-hybrid-loading')).toBeNull();
+ expect(document.querySelector('.ldr-hybrid-divider')).toBeNull();
+});
+
+it('keeps the newer hybrid loading state when an older request rejects', async () => {
+ const olderRequest = deferred();
+ const newerRequest = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderRequest.promise)
+ .mockImplementationOnce(() => newerRequest.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileNewsSearchRuntime({
+ items: [{ id: 'card-a', research_id: 'news-a' }],
+ });
+
+ const olderSearch = runtime.runNewsHybridSearch('older query');
+ const newerSearch = runtime.runNewsHybridSearch('newer query');
+ olderRequest.reject(new Error('stale request failed'));
+ await olderSearch;
+
+ expect(document.getElementById('news-hybrid-loading')).not.toBeNull();
+
+ newerRequest.resolve(response({
+ success: true,
+ results: [{ research_id: 'news-a', similarity: 88 }],
+ }));
+ await newerSearch;
+
+ expect(runtime.getMatches().get('news-a')).toEqual({
+ similarity: 88,
+ snippet: '',
+ });
+ expect(document.getElementById('news-hybrid-loading')).toBeNull();
+});
diff --git a/tests/js/pages/news-subscription-folder-loader.test.js b/tests/js/pages/news-subscription-folder-loader.test.js
new file mode 100644
index 0000000000..e263a89c33
--- /dev/null
+++ b/tests/js/pages/news-subscription-folder-loader.test.js
@@ -0,0 +1,138 @@
+/**
+ * Browser contract for the inline subscription-folder loader.
+ *
+ * The generic frontend route census only scans static/js. Extracting and
+ * executing the checked-in function keeps this test bound to the code the
+ * browser gets instead of copying its implementation into the fixture.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { extractTemplateFunction } from '../helpers/template-harness.js';
+
+const TEMPLATE_ROOT = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages',
+);
+
+function readTemplate(name) {
+ return readFileSync(resolve(TEMPLATE_ROOT, name), 'utf8');
+}
+
+function compileSubscriptionFolderLoader(subscriptionFolderId) {
+ const source = extractTemplateFunction(
+ readTemplate('news-subscription-form.html'),
+ 'loadSubscriptionFolders',
+ )
+ .replace(
+ /\{\{\s*subscription\.folder_id\s*\}\}/g,
+ String(subscriptionFolderId),
+ )
+ .replace(/\{%[\s\S]*?%\}/g, '');
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ return new Function(`return (${source});`)(); // eslint-disable-line no-new-func
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+describe('news-subscription-form.html folder bootstrap', () => {
+ it('loads the FastAPI array response and restores the edited folder', async () => {
+ const loadSubscriptionFolders =
+ compileSubscriptionFolderLoader('folder-2');
+ document.body.innerHTML = `
+ <select id="subscription-folder">
+ <option value="">No folder</option>
+ <option value="stale">Stale option</option>
+ </select>
+ `;
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue([
+ { id: 'folder-1', name: 'Daily briefings' },
+ { id: 'folder-2', name: 'Migration watch' },
+ ]),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await loadSubscriptionFolders();
+
+ expect(fetchMock).toHaveBeenCalledTimes(1);
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscription/folders',
+ { credentials: 'same-origin' },
+ );
+ const select = document.getElementById('subscription-folder');
+ expect(Array.from(select.options, option => [
+ option.value,
+ option.textContent,
+ ])).toEqual([
+ ['', 'No folder'],
+ ['folder-1', 'Daily briefings'],
+ ['folder-2', 'Migration watch'],
+ ]);
+ expect(select.value).toBe('folder-2');
+ });
+
+ it('accepts the wrapped folder response used by compatible API versions', async () => {
+ const loadSubscriptionFolders =
+ compileSubscriptionFolderLoader('folder-3');
+ document.body.innerHTML = `
+ <select id="subscription-folder">
+ <option value="">No folder</option>
+ </select>
+ `;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ folders: [
+ { id: 'folder-3', name: 'FastAPI migration' },
+ ],
+ }),
+ }));
+
+ await loadSubscriptionFolders();
+
+ const select = document.getElementById('subscription-folder');
+ expect(Array.from(select.options, option => [
+ option.value,
+ option.textContent,
+ ])).toEqual([
+ ['', 'No folder'],
+ ['folder-3', 'FastAPI migration'],
+ ]);
+ expect(select.value).toBe('folder-3');
+ });
+
+ it('preserves the existing choice when the folder endpoint rejects the request', async () => {
+ const loadSubscriptionFolders =
+ compileSubscriptionFolderLoader('folder-4');
+ document.body.innerHTML = `
+ <select id="subscription-folder">
+ <option value="folder-4" selected>Existing folder</option>
+ </select>
+ `;
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 503,
+ statusText: 'Unavailable',
+ }));
+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await loadSubscriptionFolders();
+
+ const select = document.getElementById('subscription-folder');
+ expect(select.value).toBe('folder-4');
+ expect(select.options).toHaveLength(1);
+ expect(error).toHaveBeenCalledWith(
+ 'Failed to load folders:',
+ 503,
+ 'Unavailable',
+ );
+ });
+});
diff --git a/tests/js/pages/news-subscription-jitter-runtime.test.js b/tests/js/pages/news-subscription-jitter-runtime.test.js
new file mode 100644
index 0000000000..ddb9a86c93
--- /dev/null
+++ b/tests/js/pages/news-subscription-jitter-runtime.test.js
@@ -0,0 +1,91 @@
+/** Checked-in template contracts for scheduler jitter guidance. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/news-subscription-form.html',
+);
+const TEMPLATE_SOURCE = readFileSync(TEMPLATE_PATH, 'utf8');
+
+function compileJitterLoader() {
+ return compileTemplateHarness({
+ templatePath: TEMPLATE_PATH,
+ functionNames: ['loadJitterInfo'],
+ dependencies: {
+ getCSRFToken: () => 'csrf-jitter',
+ },
+ returnExpression: 'loadJitterInfo',
+ });
+}
+
+beforeEach(() => {
+ // Scripts inserted through innerHTML remain inert; this mounts the exact
+ // checked-in element that loadJitterInfo updates in the browser.
+ // eslint-disable-next-line no-unsanitized/property -- repository-owned template fixture.
+ document.body.innerHTML = TEMPLATE_SOURCE;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.__jitterExecuted;
+ document.body.replaceChildren();
+});
+
+it.each([
+ {
+ maxJitter: 0,
+ expectedText: 'No jitter configured. Subscriptions will run exactly at scheduled times.',
+ },
+ {
+ maxJitter: 300,
+ expectedText: 'A random delay up to 5 minutes will be added',
+ },
+])('renders scheduler max jitter $maxJitter in the actual form hint', async ({
+ maxJitter,
+ expectedText,
+}) => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ config: { max_jitter_seconds: maxJitter },
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await compileJitterLoader()();
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/scheduler/status', {
+ credentials: 'same-origin',
+ headers: { 'X-CSRFToken': 'csrf-jitter' },
+ });
+ const hint = document.getElementById('subscription-jitter-info');
+ expect(hint).not.toBeNull();
+ expect(hint.textContent).toContain(expectedText);
+ expect(hint.querySelector('small')).toBeNull();
+ expect(hint.querySelector('a').getAttribute('href'))
+ .toBe('/settings#news_scheduler');
+});
+
+it('keeps a malformed scheduler jitter value inert and uses the safe default', async () => {
+ const hostileValue = '<img src=x onerror="window.__jitterExecuted=true">';
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ config: { max_jitter_seconds: hostileValue },
+ }),
+ }));
+ window.__jitterExecuted = false;
+
+ await compileJitterLoader()();
+
+ const hint = document.getElementById('subscription-jitter-info');
+ expect(hint.textContent).toContain('delay up to 5 minutes');
+ expect(hint.querySelector('img')).toBeNull();
+ expect(hint.innerHTML).not.toContain(hostileValue);
+ expect(window.__jitterExecuted).toBe(false);
+});
diff --git a/tests/js/pages/news-subscription-submit-runtime.test.js b/tests/js/pages/news-subscription-submit-runtime.test.js
new file mode 100644
index 0000000000..1f9ef14e53
--- /dev/null
+++ b/tests/js/pages/news-subscription-submit-runtime.test.js
@@ -0,0 +1,489 @@
+/**
+ * Runtime contracts for the news page's create-and-run subscription modal.
+ *
+ * These tests execute the checked-in submit and polling functions so the two
+ * migrated POSTs, research-id handoff, status polling, and terminal cleanup
+ * remain one coherent browser workflow.
+ */
+
+import { resolve } from 'node:path';
+
+import '@js/config/urls.js';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function response(payload, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function escapeHtml(value) {
+ return String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+}
+
+function compileSubscriptionRuntime({
+ showAlert = vi.fn(),
+ loadSubscriptions = vi.fn().mockResolvedValue(undefined),
+ loadNewsFeed = vi.fn().mockResolvedValue(undefined),
+} = {}) {
+ const hideModal = vi.fn();
+ const bootstrap = {
+ Modal: {
+ getInstance: vi.fn(() => ({ hide: hideModal })),
+ },
+ };
+ const ResearchStates = {
+ isCompleted: status => status === 'completed',
+ isTerminal: status => [
+ 'completed',
+ 'failed',
+ 'cancelled',
+ ].includes(status),
+ };
+
+ const runtime = compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: [
+ 'stopNewsResearchPoll',
+ 'beginNewsResearchPoll',
+ 'isCurrentNewsResearchPoll',
+ 'clearStoredNewsResearch',
+ 'findNewsResearchCard',
+ 'removeNewsResearchCards',
+ 'endNewsResearchPollWithFeed',
+ 'completeNewsResearchPoll',
+ 'pollForNewsResearchResults',
+ 'handleNewsSubscriptionSubmit',
+ ],
+ dependencies: {
+ showAlert,
+ loadSubscriptions,
+ loadNewsFeed,
+ escapeHtml,
+ bootstrap,
+ ResearchStates,
+ URLBuilder: window.URLBuilder,
+ getCSRFToken: () => 'csrf-news-subscription',
+ },
+ preamble: `
+ let newsFeedRequestId = 0;
+ let newsFeedRequestIntent = 'generic';
+ let newsResearchPollId = 0;
+ let activeNewsResearchPoll = null;
+ let newsResearchReloadTimer = null;
+ let newsResearchRestoreId = 0;
+ let activeNewsSubscriptionSubmit = null;
+ `,
+ returnExpression: `({
+ handleNewsSubscriptionSubmit,
+ pollForNewsResearchResults,
+ })`,
+ });
+
+ return {
+ ...runtime,
+ showAlert,
+ loadSubscriptions,
+ loadNewsFeed,
+ hideModal,
+ };
+}
+
+function renderSubscriptionModal() {
+ document.body.innerHTML = `
+ <div id="newsSubscriptionModal"></div>
+ <form id="news-subscription-form">
+ <textarea id="news-subscription-query">FastAPI migration status</textarea>
+ <input id="news-subscription-name" value="Migration watch">
+ <select id="news-subscription-frequency">
+ <option value="4" selected>Every 4 hours</option>
+ </select>
+ <select id="news-subscription-folder">
+ <option value="folder-3299" selected>Migration</option>
+ </select>
+ <input id="news-subscription-active" type="checkbox" checked>
+ <input id="news-subscription-run-now" type="checkbox" checked>
+ <input id="news-subscription-model" value="OLLAMA:llama3">
+ <select id="news-subscription-strategy">
+ <option value="source-based" selected>Source based</option>
+ </select>
+ <button id="news-subscription-submit" type="submit">
+ Create Subscription
+ </button>
+ </form>
+ <section id="news-feed-content">
+ <article id="existing-news">Existing news</article>
+ </section>
+ `;
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ renderSubscriptionModal();
+ localStorage.clear();
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ document.body.replaceChildren();
+});
+
+it('creates, runs, polls, and completes a subscription using the returned research ID', async () => {
+ const statuses = [
+ { status: 'in_progress', progress: 42 },
+ { status: 'completed', progress: 100 },
+ ];
+ const fetchMock = vi.fn((url) => {
+ if (url === '/news/api/subscribe') {
+ return Promise.resolve(response({
+ status: 'success',
+ subscription_id: 'subscription-3299',
+ }));
+ }
+ if (url === '/news/api/subscriptions/subscription-3299/run') {
+ return Promise.resolve(response({
+ status: 'success',
+ research_id: 'research-3299',
+ }));
+ }
+ if (url === '/api/research/research-3299/status') {
+ return Promise.resolve(response(statuses.shift()));
+ }
+ throw new Error(`Unexpected fetch: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+ const event = { preventDefault: vi.fn() };
+
+ await runtime.handleNewsSubscriptionSubmit(event);
+
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenNthCalledWith(1, '/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-subscription',
+ },
+ body: JSON.stringify({
+ query: 'FastAPI migration status',
+ name: 'Migration watch',
+ subscription_type: 'search',
+ refresh_minutes: 240,
+ folder_id: 'folder-3299',
+ is_active: true,
+ model_provider: 'OLLAMA',
+ model: 'OLLAMA:llama3',
+ search_strategy: 'source-based',
+ }),
+ });
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 2,
+ '/news/api/subscriptions/subscription-3299/run',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-subscription',
+ },
+ },
+ );
+ expect(runtime.hideModal).toHaveBeenCalledOnce();
+ expect(runtime.loadSubscriptions).toHaveBeenCalledOnce();
+ expect(document.querySelector('.ldr-active-research-card').textContent)
+ .toContain('research-3299');
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({
+ researchId: 'research-3299',
+ query: 'FastAPI migration status',
+ });
+
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 3,
+ '/api/research/research-3299/status',
+ );
+ const progress = document.querySelector('[role="progressbar"]');
+ expect(progress.getAttribute('aria-valuenow')).toBe('42');
+ expect(progress.firstElementChild.style.width).toBe('42%');
+
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 4,
+ '/api/research/research-3299/status',
+ );
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'News analysis completed! Loading results...',
+ 'success',
+ );
+
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+});
+
+it('gates a second submit until the owned create-and-run workflow settles', async () => {
+ const pendingCreate = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => pendingCreate.promise)
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ research_id: 'research-single-owner',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+ const firstEvent = { preventDefault: vi.fn() };
+ const secondEvent = { preventDefault: vi.fn() };
+
+ const firstSubmit = runtime.handleNewsSubscriptionSubmit(firstEvent);
+ const secondSubmit = runtime.handleNewsSubscriptionSubmit(secondEvent);
+
+ expect(firstEvent.preventDefault).toHaveBeenCalledOnce();
+ expect(secondEvent.preventDefault).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscribe',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(document.getElementById('news-subscription-submit').disabled)
+ .toBe(true);
+
+ await secondSubmit;
+ expect(document.getElementById('news-subscription-submit').disabled)
+ .toBe(true);
+
+ pendingCreate.resolve(response({
+ status: 'success',
+ subscription_id: 'subscription-single-owner',
+ }));
+ await firstSubmit;
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 2,
+ '/news/api/subscriptions/subscription-single-owner/run',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ expect(document.querySelectorAll('.ldr-active-research-card'))
+ .toHaveLength(1);
+ expect(runtime.hideModal).toHaveBeenCalledOnce();
+ expect(runtime.loadSubscriptions).toHaveBeenCalledOnce();
+ expect(document.getElementById('news-subscription-submit').disabled)
+ .toBe(false);
+});
+
+it.each([
+ ['missing', undefined],
+ ['blank', ' '],
+])('warns and does not monitor when a successful run has a %s research ID', async (
+ _label,
+ researchId,
+) => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ subscription_id: 'subscription-invalid-run',
+ }))
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ research_id: researchId,
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+
+ await runtime.handleNewsSubscriptionSubmit({ preventDefault: vi.fn() });
+ await vi.advanceTimersByTimeAsync(15000);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Subscription created, but its research run could not be started.',
+ 'warning',
+ );
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.loadNewsFeed).not.toHaveBeenCalled();
+ expect(document.getElementById('news-subscription-submit').disabled)
+ .toBe(false);
+});
+
+it('stops polling and restores the feed when research reaches a failed state', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ subscription_id: 'subscription-failed',
+ }))
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ research_id: 'research-failed',
+ }))
+ .mockResolvedValueOnce(response({
+ status: 'failed',
+ progress: 57,
+ metadata: { error: 'provider unavailable' },
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+
+ await runtime.handleNewsSubscriptionSubmit({ preventDefault: vi.fn() });
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(fetchMock).toHaveBeenNthCalledWith(
+ 3,
+ '/api/research/research-failed/status',
+ );
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Research failed: provider unavailable',
+ 'error',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+});
+
+it('reports an immediate-run failure without starting a status poll', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(response({
+ status: 'success',
+ subscription_id: 'subscription-no-run',
+ }))
+ .mockResolvedValueOnce(response(
+ { error: 'research queue full' },
+ false,
+ 409,
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+
+ await runtime.handleNewsSubscriptionSubmit({ preventDefault: vi.fn() });
+ await vi.advanceTimersByTimeAsync(15000);
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Subscription created, but its research run could not be started.',
+ 'warning',
+ );
+ expect(runtime.loadSubscriptions).toHaveBeenCalledOnce();
+});
+
+it('retires a superseded status request before it can contradict the newer run', async () => {
+ const staleStatus = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => staleStatus.promise)
+ .mockResolvedValueOnce(response({
+ status: 'completed',
+ progress: 100,
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+ const feed = document.getElementById('news-feed-content');
+ const olderCard = document.createElement('article');
+ olderCard.className = 'ldr-active-research-card';
+ olderCard.dataset.researchId = 'research-old';
+ feed.prepend(olderCard);
+
+ runtime.pollForNewsResearchResults('research-old', 'Old run');
+ vi.advanceTimersByTime(5000);
+ await Promise.resolve();
+ expect(fetchMock).toHaveBeenCalledOnce();
+
+ const newerCard = document.createElement('article');
+ newerCard.className = 'ldr-active-research-card';
+ newerCard.dataset.researchId = 'research-new';
+ feed.prepend(newerCard);
+ runtime.pollForNewsResearchResults('research-new', 'New run');
+ expect(document.querySelector('[data-research-id="research-old"]'))
+ .toBeNull();
+ expect(document.querySelector('[data-research-id="research-new"]'))
+ .not.toBeNull();
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'News analysis completed! Loading results...',
+ 'success',
+ );
+ expect(JSON.parse(localStorage.getItem('active_news_research') || 'null'))
+ .toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+
+ staleStatus.resolve(response({
+ status: 'failed',
+ metadata: { error: 'stale provider failure' },
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+ await vi.advanceTimersByTimeAsync(1000);
+
+ expect(runtime.showAlert).toHaveBeenCalledTimes(1);
+ expect(runtime.showAlert).not.toHaveBeenCalledWith(
+ 'Research failed: stale provider failure',
+ 'error',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+});
+
+it('cleans persisted and visible polling state after a status HTTP failure', async () => {
+ const activeCard = document.createElement('article');
+ activeCard.className = 'ldr-active-research-card';
+ activeCard.dataset.researchId = 'research-http-failure';
+ document.getElementById('news-feed-content').prepend(activeCard);
+
+ const fetchMock = vi.fn().mockResolvedValue(response(
+ { detail: 'status unavailable' },
+ false,
+ 503,
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileSubscriptionRuntime();
+
+ runtime.pollForNewsResearchResults(
+ 'research-http-failure',
+ 'Unavailable status',
+ );
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(localStorage.getItem('active_news_research')).toBeNull();
+ expect(document.querySelector('.ldr-active-research-card')).toBeNull();
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Failed to check research status. Please try again.',
+ 'error',
+ );
+ expect(runtime.loadNewsFeed).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(15000);
+ expect(fetchMock).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/pages/news-subscription-test-run-runtime.test.js b/tests/js/pages/news-subscription-test-run-runtime.test.js
new file mode 100644
index 0000000000..0239bf3e6e
--- /dev/null
+++ b/tests/js/pages/news-subscription-test-run-runtime.test.js
@@ -0,0 +1,528 @@
+/**
+ * Runtime contracts for the news subscription form's immediate-run workflow.
+ *
+ * The checked-in inline functions are executed to pin the FastAPI requests,
+ * normalized numeric configuration, storage handoff, and create-then-run
+ * sequencing used by the browser.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/news-subscription-form.html',
+);
+
+function extractFunction(source, name) {
+ const signature = new RegExp(`(?:async\\s+)?function\\s+${name}\\s*\\(`);
+ const match = signature.exec(source);
+ if (!match) throw new Error(`Function ${name} not found in template`);
+
+ const openBrace = source.indexOf('{', match.index + match[0].length);
+ let depth = 0;
+ for (let index = openBrace; index < source.length; index += 1) {
+ if (source[index] === '{') depth += 1;
+ if (source[index] === '}') {
+ depth -= 1;
+ if (depth === 0) return source.slice(match.index, index + 1);
+ }
+ }
+
+ throw new Error(`Function ${name} has an unterminated body`);
+}
+
+function renderCreateModeSubscriptionSubmit(source) {
+ const rendered = source
+ .replace(
+ /\{%\s*if subscription\s*%\}[\s\S]*?\{%\s*else\s*%\}([\s\S]*?)\{%\s*endif\s*%\}/g,
+ '$1',
+ )
+ .replace(
+ /\{\{\s*"updated"\s+if\s+subscription\s+else\s+"created"\s*\}\}/g,
+ 'created',
+ );
+
+ if (/\{[{%]/.test(rendered)) {
+ throw new Error('Unhandled Jinja remains in create-mode submit');
+ }
+ return rendered;
+}
+
+function compileSubscriptionRunner(dependencies) {
+ const template = readFileSync(TEMPLATE_PATH, 'utf8');
+ const functions = [
+ 'isValidResearchId',
+ 'scheduleSubscriptionRedirect',
+ 'handleSubscriptionSubmit',
+ 'handleTestRun',
+ 'handleCreateAndRun',
+ ]
+ .map(name => {
+ const source = extractFunction(template, name);
+ return name === 'handleSubscriptionSubmit'
+ ? renderCreateModeSubscriptionSubmit(source)
+ : source;
+ })
+ .join('\n');
+ const dependencyNames = Object.keys(dependencies);
+ // The extracted source is repository-owned production code from the
+ // template above, not user-controlled input.
+ const factory = new Function( // eslint-disable-line no-new-func
+ ...dependencyNames,
+ `let subscriptionActionInFlight = false;\nlet subscriptionNavigationPending = false;\n${functions}\nreturn { handleSubscriptionSubmit, handleTestRun, handleCreateAndRun };`,
+ );
+ return factory(...Object.values(dependencies));
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolveDeferred => {
+ resolvePromise = resolveDeferred;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function renderSubscriptionForm() {
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-news">';
+ document.body.innerHTML = `
+ <input id="subscription-query" value="FastAPI migration status">
+ <input id="subscription-name" value="Migration watch">
+ <input id="subscription-interval" value="45">
+ <select id="subscription-folder">
+ <option value="folder-2" selected>Migration</option>
+ </select>
+ <input id="subscription-active" type="checkbox" checked>
+ <input id="subscription-model_hidden" value="gpt-4.1-mini">
+ <select id="subscription-provider">
+ <option value="openai" selected>OpenAI</option>
+ </select>
+ <input id="subscription-custom-endpoint" value="">
+ <input id="subscription-search-engine_hidden" value="searxng">
+ <input id="subscription-search-engine" value="Visible fallback">
+ <input id="subscription-iterations" value="3">
+ <input id="subscription-questions" value="4">
+ <select id="subscription-strategy">
+ <option value="source-based" selected>Source based</option>
+ </select>
+ `;
+}
+
+function createDependencies() {
+ return {
+ showAlert: vi.fn(),
+ getCSRFToken: vi.fn(() => 'csrf-news'),
+ };
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ renderSubscriptionForm();
+ localStorage.clear();
+ sessionStorage.clear();
+ localStorage.setItem('userId', 'user-7');
+ window.sourceResearchId = 'source-12';
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.sourceResearchId;
+ localStorage.clear();
+ sessionStorage.clear();
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('starts a configured test run and hands its ID to the news page', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ research_id: 'research-3299',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+ const event = {
+ preventDefault: vi.fn(),
+ stopPropagation: vi.fn(),
+ };
+
+ await runner.handleTestRun(event);
+
+ expect(event.preventDefault).toHaveBeenCalledOnce();
+ expect(event.stopPropagation).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/api/start_research', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news',
+ },
+ body: JSON.stringify({
+ query: 'FastAPI migration status',
+ mode: 'quick',
+ strategy: 'source-based',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ triggered_by: 'subscription_test_run',
+ },
+ model_provider: 'openai',
+ model: 'gpt-4.1-mini',
+ search_engine: 'searxng',
+ iterations: 3,
+ questions_per_iteration: 4,
+ }),
+ });
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-3299');
+ expect(sessionStorage.getItem('activeTestRunQuery'))
+ .toBe('FastAPI migration status');
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Research started successfully! Redirecting to news page...',
+ 'success',
+ );
+});
+
+it('accepts a queued FastAPI start with a finite numeric research ID', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ status: 202,
+ json: vi.fn().mockResolvedValue({
+ status: 'queued',
+ research_id: 3299,
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+
+ await compileSubscriptionRunner(dependencies).handleTestRun();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('3299');
+ expect(sessionStorage.getItem('activeTestRunQuery'))
+ .toBe('FastAPI migration status');
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Research started successfully! Redirecting to news page...',
+ 'success',
+ );
+});
+
+it.each([
+ ['whitespace', ' '],
+ ['an object', { value: 'research-object' }],
+ ['a non-finite number', Number.POSITIVE_INFINITY],
+])('rejects %s as a research ID and releases ownership', async (
+ _label,
+ invalidResearchId,
+) => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 202,
+ json: vi.fn().mockResolvedValue({
+ status: 'queued',
+ research_id: invalidResearchId,
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 202,
+ json: vi.fn().mockResolvedValue({
+ status: 'queued',
+ research_id: 'research-valid-retry',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+
+ await runner.handleTestRun();
+
+ expect(sessionStorage.getItem('activeTestRunResearchId')).toBeNull();
+ expect(vi.getTimerCount()).toBe(0);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Unexpected response from server',
+ 'error',
+ );
+
+ await runner.handleTestRun();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-valid-retry');
+});
+
+it('executes the create-mode submit and owns its redirect window', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ id: 'subscription-submit' }),
+ })
+ .mockRejectedValue(new Error('unexpected duplicate request'));
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+ const submitEvent = () => ({ preventDefault: vi.fn() });
+
+ await runner.handleSubscriptionSubmit(submitEvent());
+ await runner.handleSubscriptionSubmit(submitEvent());
+ await vi.advanceTimersByTimeAsync(1499);
+ await runner.handleSubscriptionSubmit(submitEvent());
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscribe', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news',
+ },
+ body: expect.any(String),
+ });
+ expect(vi.getTimerCount()).toBe(1);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Subscription created successfully!',
+ 'success',
+ );
+});
+
+it('releases create-mode submit ownership after a failed response', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ json: vi.fn().mockResolvedValue({ error: 'duplicate name' }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ id: 'subscription-retry' }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+
+ await runner.handleSubscriptionSubmit({ preventDefault: vi.fn() });
+ await runner.handleSubscriptionSubmit({ preventDefault: vi.fn() });
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Error: duplicate name',
+ 'error',
+ );
+});
+
+it('allows only one test-run request while the owned start is pending', async () => {
+ const pendingStart = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => pendingStart.promise)
+ .mockRejectedValue(new Error('unexpected duplicate request'));
+ vi.stubGlobal('fetch', fetchMock);
+ const runner = compileSubscriptionRunner(createDependencies());
+
+ const firstRun = runner.handleTestRun();
+ const duplicateRun = runner.handleTestRun();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ await duplicateRun;
+
+ pendingStart.resolve({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ research_id: 'research-first',
+ }),
+ });
+ await firstRun;
+
+ expect(vi.getTimerCount()).toBe(1);
+ await runner.handleTestRun();
+ await vi.advanceTimersByTimeAsync(1499);
+ await runner.handleTestRun();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-first');
+});
+
+it('releases test-run ownership after a failed start response', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ status: 503,
+ json: vi.fn().mockResolvedValue({ error: 'queue unavailable' }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 202,
+ json: vi.fn().mockResolvedValue({
+ status: 'queued',
+ research_id: 'research-retry',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+
+ await runner.handleTestRun();
+ await runner.handleTestRun();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'queue unavailable',
+ 'error',
+ );
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-retry');
+});
+
+it('requires the dropdown-backed search engine before starting research', async () => {
+ document.getElementById('subscription-search-engine_hidden').value = '';
+ document.getElementById('subscription-search-engine').value = '';
+ const fetchMock = vi.fn();
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+
+ await compileSubscriptionRunner(dependencies).handleTestRun();
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Please select a search engine',
+ 'warning',
+ );
+});
+
+it('creates the subscription before starting its immediate research run', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ id: 'subscription-5' }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ research_id: 'research-5',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+
+ await compileSubscriptionRunner(dependencies).handleCreateAndRun();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0][0]).toBe('/news/api/subscribe');
+ expect(fetchMock.mock.calls[0][1]).toEqual({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news',
+ },
+ body: JSON.stringify({
+ user_id: 'user-7',
+ query: 'FastAPI migration status',
+ name: 'Migration watch',
+ subscription_type: 'search',
+ refresh_minutes: 45,
+ folder_id: 'folder-2',
+ is_active: true,
+ model_provider: 'openai',
+ model: 'gpt-4.1-mini',
+ custom_endpoint: null,
+ search_engine: 'searxng',
+ search_iterations: 3,
+ questions_per_iteration: 4,
+ search_strategy: 'source-based',
+ source_id: 'source-12',
+ }),
+ });
+ expect(fetchMock.mock.calls[1][0]).toBe('/api/start_research');
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-5');
+});
+
+it('allows only one create-and-run workflow while creation is pending', async () => {
+ const pendingCreate = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => pendingCreate.promise)
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({
+ status: 'success',
+ research_id: 'research-single-owner',
+ }),
+ })
+ .mockRejectedValue(new Error('unexpected duplicate request'));
+ vi.stubGlobal('fetch', fetchMock);
+ const runner = compileSubscriptionRunner(createDependencies());
+
+ const firstWorkflow = runner.handleCreateAndRun();
+ const duplicateWorkflow = runner.handleCreateAndRun();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ await duplicateWorkflow;
+
+ pendingCreate.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ id: 'subscription-single-owner' }),
+ });
+ await firstWorkflow;
+
+ expect(vi.getTimerCount()).toBe(1);
+ await runner.handleCreateAndRun();
+ await vi.advanceTimersByTimeAsync(1499);
+ await runner.handleCreateAndRun();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/subscribe',
+ '/api/start_research',
+ ]);
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-single-owner');
+});
+
+it('releases create-and-run ownership when subscription creation fails', async () => {
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({
+ ok: false,
+ json: vi.fn().mockResolvedValue({
+ error: 'duplicate subscription',
+ }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ id: 'subscription-retry' }),
+ })
+ .mockResolvedValueOnce({
+ ok: true,
+ status: 202,
+ json: vi.fn().mockResolvedValue({
+ status: 'queued',
+ research_id: 'research-after-create-retry',
+ }),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ const dependencies = createDependencies();
+ const runner = compileSubscriptionRunner(dependencies);
+
+ await runner.handleCreateAndRun();
+ await runner.handleCreateAndRun();
+
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(dependencies.showAlert).toHaveBeenCalledWith(
+ 'Error: duplicate subscription',
+ 'error',
+ );
+ expect(sessionStorage.getItem('activeTestRunResearchId'))
+ .toBe('research-after-create-retry');
+});
diff --git a/tests/js/pages/news-votes-runtime.test.js b/tests/js/pages/news-votes-runtime.test.js
new file mode 100644
index 0000000000..76e16c8ab2
--- /dev/null
+++ b/tests/js/pages/news-votes-runtime.test.js
@@ -0,0 +1,507 @@
+/** Browser endpoint contracts for the checked-in news vote consumers. */
+
+import { readFileSync } from 'node:fs';
+import { resolve as resolvePath } from 'node:path';
+
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const NEWS_SOURCE_PATH = resolvePath(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/news.js',
+);
+
+function response(payload, ok = true, status = ok ? 200 : 500) {
+ return {
+ ok,
+ status,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, reject: rejectPromise, resolve: resolvePromise };
+}
+
+function compileVotesRuntime(items, csrfToken = 'csrf-news-votes') {
+ const showAlert = vi.fn();
+ const runtime = compileTemplateHarness({
+ templatePath: NEWS_SOURCE_PATH,
+ functionNames: ['loadVotesForNewsItems', 'vote'],
+ dependencies: { items, csrfToken, showAlert },
+ preamble: `
+ let newsItems = items;
+ let voteLoadRequestId = 0;
+ const activeVoteRequests = new Map();
+ const voteRequestTails = new Map();
+ const getCSRFToken = () => csrfToken;
+ `,
+ returnExpression: `({
+ loadVotesForNewsItems,
+ vote,
+ setNewsItems: value => { newsItems = value; },
+ })`,
+ });
+ return { ...runtime, showAlert };
+}
+
+function addNewsCard(id) {
+ const card = document.createElement('article');
+ card.dataset.newsId = id;
+ card.innerHTML = `
+ <button class="ldr-vote-btn ldr-voted">old up</button>
+ <button class="ldr-vote-btn ldr-voted">old down</button>
+ `;
+ document.body.appendChild(card);
+ return card;
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+});
+
+it('posts card IDs with CSRF and renders numeric, inert vote state', async () => {
+ const firstCard = addNewsCard('news-1');
+ const secondCard = addNewsCard('news-2');
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ votes: {
+ 'news-1': { upvotes: '6', downvotes: 2, user_vote: 'up' },
+ 'news-2': {
+ upvotes: '<img src=x onerror=alert(1)>',
+ downvotes: '<script>alert(1)</script>',
+ user_vote: null,
+ },
+ },
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([
+ { id: 'news-1' },
+ { id: 'news-2' },
+ ]);
+
+ await runtime.loadVotesForNewsItems();
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/feedback/batch', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-votes',
+ },
+ body: JSON.stringify({ card_ids: ['news-1', 'news-2'] }),
+ });
+ const firstButtons = firstCard.querySelectorAll('.ldr-vote-btn');
+ expect(firstButtons[0].textContent).toContain('6');
+ expect(firstButtons[1].textContent).toContain('2');
+ expect(firstButtons[0].classList.contains('ldr-voted')).toBe(true);
+ expect(firstButtons[1].classList.contains('ldr-voted')).toBe(false);
+
+ const secondButtons = secondCard.querySelectorAll('.ldr-vote-btn');
+ expect(secondButtons[0].textContent).toContain('0');
+ expect(secondButtons[1].textContent).toContain('0');
+ expect(secondButtons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(secondButtons[1].classList.contains('ldr-voted')).toBe(false);
+ expect(secondCard.querySelector('img, script')).toBeNull();
+ expect(secondCard.innerHTML).not.toContain('onerror');
+});
+
+it('posts an individual vote with CSRF and keeps response counts inert', async () => {
+ const card = addNewsCard('news-vote');
+ const fetchMock = vi.fn().mockResolvedValue(response({
+ upvotes: '<img src=x onerror=alert(1)>',
+ downvotes: '12',
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'news-vote' }]);
+ expect(readFileSync(NEWS_SOURCE_PATH, 'utf8')).toContain('window.vote = vote;');
+
+ await runtime.vote('news-vote', 'down');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/feedback/news-vote', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-votes',
+ },
+ body: JSON.stringify({ vote: 'down' }),
+ });
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('0');
+ expect(buttons[1].textContent).toContain('12');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+ expect(card.querySelector('img, script')).toBeNull();
+ expect(card.innerHTML).not.toContain('onerror');
+});
+
+it('ignores a stale batch response after a newer vote load finishes', async () => {
+ const card = addNewsCard('shared-news');
+ const olderResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockResolvedValueOnce(response({
+ votes: {
+ 'shared-news': { upvotes: 9, downvotes: 4, user_vote: 'down' },
+ },
+ }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'shared-news' }]);
+
+ const olderLoad = runtime.loadVotesForNewsItems();
+ await runtime.loadVotesForNewsItems();
+
+ let buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('9');
+ expect(buttons[1].textContent).toContain('4');
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+
+ olderResponse.resolve(response({
+ votes: {
+ 'shared-news': { upvotes: 1, downvotes: 0, user_vote: 'up' },
+ },
+ }));
+ await olderLoad;
+
+ buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('9');
+ expect(buttons[1].textContent).toContain('4');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
+
+it('serializes same-news votes and renders only the latest intent', async () => {
+ const card = addNewsCard('rapid-news');
+ const olderResponse = deferred();
+ const newerResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => newerResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'rapid-news' }]);
+
+ const olderVote = runtime.vote('rapid-news', 'up');
+ const newerVote = runtime.vote('rapid-news', 'down');
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ vote: 'up' });
+
+ olderResponse.resolve(response({ upvotes: 6, downvotes: 7 }));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body))
+ .toEqual({ vote: 'down' });
+ expect(card.querySelectorAll('.ldr-vote-btn')[0].textContent)
+ .toBe('old up');
+
+ newerResponse.resolve(response({ upvotes: 5, downvotes: 8 }));
+ await Promise.all([olderVote, newerVote]);
+
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('5');
+ expect(buttons[1].textContent).toContain('8');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
+
+it.each([
+ [
+ 'non-OK',
+ () => response({ error: 'rejected' }, false, 503),
+ { upvotes: 6, downvotes: 7, user_vote: 'up' },
+ ],
+ [
+ 'malformed',
+ () => ({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockRejectedValue(new SyntaxError('invalid JSON')),
+ }),
+ { upvotes: 5, downvotes: 8, user_vote: 'down' },
+ ],
+])('reconciles after the latest queued vote returns %s', async (
+ _failureType,
+ failedResponse,
+ authoritativeVote,
+) => {
+ const card = addNewsCard('reconcile-news');
+ const olderResponse = deferred();
+ const latestResponse = deferred();
+ const reconciliationResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => latestResponse.promise)
+ .mockImplementationOnce(() => reconciliationResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'reconcile-news' }]);
+
+ const olderVote = runtime.vote('reconcile-news', 'up');
+ const latestVote = runtime.vote('reconcile-news', 'down');
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ vote: 'up' });
+
+ olderResponse.resolve(response({ upvotes: 6, downvotes: 7 }));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body))
+ .toEqual({ vote: 'down' });
+
+ latestResponse.resolve(failedResponse());
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+ expect(fetchMock.mock.calls[2]).toEqual([
+ '/news/api/feedback/batch',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-news-votes',
+ },
+ body: JSON.stringify({ card_ids: ['reconcile-news'] }),
+ },
+ ]);
+ expect(runtime.showAlert).toHaveBeenCalledWith(
+ 'Failed to save vote. Restoring the latest vote state.',
+ 'error',
+ );
+
+ reconciliationResponse.resolve(response({
+ votes: { 'reconcile-news': authoritativeVote },
+ }));
+ await Promise.all([olderVote, latestVote]);
+
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain(String(authoritativeVote.upvotes));
+ expect(buttons[1].textContent)
+ .toContain(String(authoritativeVote.downvotes));
+ expect(buttons[0].classList.contains('ldr-voted'))
+ .toBe(authoritativeVote.user_vote === 'up');
+ expect(buttons[1].classList.contains('ldr-voted'))
+ .toBe(authoritativeVote.user_vote === 'down');
+});
+
+it('starts a same-news retry before stale reconciliation settles', async () => {
+ const card = addNewsCard('retry-during-reconcile');
+ const olderResponse = deferred();
+ const failedResponse = deferred();
+ const reconciliationResponse = deferred();
+ const retryResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => failedResponse.promise)
+ .mockImplementationOnce(() => reconciliationResponse.promise)
+ .mockImplementationOnce(() => retryResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([
+ { id: 'retry-during-reconcile' },
+ ]);
+
+ const olderVote = runtime.vote('retry-during-reconcile', 'up');
+ const failedVote = runtime.vote('retry-during-reconcile', 'down');
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ olderResponse.resolve(response({ upvotes: 4, downvotes: 1 }));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ failedResponse.resolve(response({ error: 'temporary' }, false, 503));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ });
+ expect(fetchMock.mock.calls[2][0]).toBe('/news/api/feedback/batch');
+
+ const retryVote = runtime.vote('retry-during-reconcile', 'down');
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(4);
+ });
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feedback/retry-during-reconcile',
+ '/news/api/feedback/retry-during-reconcile',
+ '/news/api/feedback/batch',
+ '/news/api/feedback/retry-during-reconcile',
+ ]);
+ expect(JSON.parse(fetchMock.mock.calls[3][1].body))
+ .toEqual({ vote: 'down' });
+
+ reconciliationResponse.resolve(response({
+ votes: {
+ 'retry-during-reconcile': {
+ upvotes: 4,
+ downvotes: 1,
+ user_vote: 'up',
+ },
+ },
+ }));
+ await Promise.all([olderVote, failedVote]);
+ let buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toBe('old up');
+ expect(buttons[1].textContent).toBe('old down');
+
+ retryResponse.resolve(response({ upvotes: 4, downvotes: 2 }));
+ await retryVote;
+ buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('4');
+ expect(buttons[1].textContent).toContain('2');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
+
+it('continues a same-news vote queue after the older request rejects', async () => {
+ const card = addNewsCard('retry-news');
+ const olderResponse = deferred();
+ const latestResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderResponse.promise)
+ .mockImplementationOnce(() => latestResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'retry-news' }]);
+
+ const olderVote = runtime.vote('retry-news', 'up');
+ const latestVote = runtime.vote('retry-news', 'down');
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ olderResponse.reject(new Error('older vote failed'));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body))
+ .toEqual({ vote: 'down' });
+
+ latestResponse.resolve(response({ upvotes: 2, downvotes: 9 }));
+ await Promise.all([olderVote, latestVote]);
+
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('2');
+ expect(buttons[1].textContent).toContain('9');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
+
+it('starts votes for different news IDs concurrently', async () => {
+ const firstCard = addNewsCard('parallel-a');
+ const secondCard = addNewsCard('parallel-b');
+ const firstResponse = deferred();
+ const secondResponse = deferred();
+ const fetchMock = vi.fn(url => (
+ url.endsWith('/parallel-a')
+ ? firstResponse.promise
+ : secondResponse.promise
+ ));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([
+ { id: 'parallel-a' },
+ { id: 'parallel-b' },
+ ]);
+
+ const firstVote = runtime.vote('parallel-a', 'up');
+ const secondVote = runtime.vote('parallel-b', 'down');
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ });
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feedback/parallel-a',
+ '/news/api/feedback/parallel-b',
+ ]);
+
+ secondResponse.resolve(response({ upvotes: 1, downvotes: 4 }));
+ await secondVote;
+ expect(secondCard.querySelectorAll('.ldr-vote-btn')[1].textContent)
+ .toContain('4');
+ expect(firstCard.querySelectorAll('.ldr-vote-btn')[0].textContent)
+ .toBe('old up');
+
+ firstResponse.resolve(response({ upvotes: 3, downvotes: 0 }));
+ await firstVote;
+ expect(firstCard.querySelectorAll('.ldr-vote-btn')[0].textContent)
+ .toContain('3');
+});
+
+it('does not let an older batch overwrite a completed individual vote', async () => {
+ const card = addNewsCard('batch-then-vote');
+ const olderBatch = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => olderBatch.promise)
+ .mockResolvedValueOnce(response({ upvotes: 10, downvotes: 3 }));
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'batch-then-vote' }]);
+
+ const batchLoad = runtime.loadVotesForNewsItems();
+ await runtime.vote('batch-then-vote', 'down');
+
+ olderBatch.resolve(response({
+ votes: {
+ 'batch-then-vote': {
+ upvotes: 9,
+ downvotes: 2,
+ user_vote: 'up',
+ },
+ },
+ }));
+ await batchLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feedback/batch',
+ '/news/api/feedback/batch-then-vote',
+ ]);
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('10');
+ expect(buttons[1].textContent).toContain('3');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
+
+it('keeps a completed mutation authoritative over a batch started mid-write', async () => {
+ const card = addNewsCard('vote-then-batch');
+ const individualResponse = deferred();
+ const batchResponse = deferred();
+ const fetchMock = vi.fn()
+ .mockImplementationOnce(() => individualResponse.promise)
+ .mockImplementationOnce(() => batchResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+ const runtime = compileVotesRuntime([{ id: 'vote-then-batch' }]);
+
+ const individualVote = runtime.vote('vote-then-batch', 'down');
+ const batchLoad = runtime.loadVotesForNewsItems();
+
+ individualResponse.resolve(response({ upvotes: 10, downvotes: 3 }));
+ await individualVote;
+ batchResponse.resolve(response({
+ votes: {
+ 'vote-then-batch': {
+ upvotes: 9,
+ downvotes: 2,
+ user_vote: 'up',
+ },
+ },
+ }));
+ await batchLoad;
+
+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([
+ '/news/api/feedback/vote-then-batch',
+ '/news/api/feedback/batch',
+ ]);
+ const buttons = card.querySelectorAll('.ldr-vote-btn');
+ expect(buttons[0].textContent).toContain('10');
+ expect(buttons[1].textContent).toContain('3');
+ expect(buttons[0].classList.contains('ldr-voted')).toBe(false);
+ expect(buttons[1].classList.contains('ldr-voted')).toBe(true);
+});
diff --git a/tests/js/pages/note-detail-bootstrap-errors-runtime.test.js b/tests/js/pages/note-detail-bootstrap-errors-runtime.test.js
new file mode 100644
index 0000000000..418b5fdea6
--- /dev/null
+++ b/tests/js/pages/note-detail-bootstrap-errors-runtime.test.js
@@ -0,0 +1,98 @@
+/** Browser bootstrap contract for distinguishing missing notes from outages. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/note_detail.html',
+);
+const NOTE_ID = 'note-load-state-3299';
+
+class ModalStub {
+ show = vi.fn();
+ hide = vi.fn();
+
+ static getOrCreateInstance() {
+ return new ModalStub();
+ }
+
+ static getInstance() {
+ return new ModalStub();
+ }
+}
+
+class IntersectionObserverStub {
+ observe = vi.fn();
+ disconnect = vi.fn();
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.noteId;
+ delete window.api;
+ delete window.ui;
+ delete window.bootstrap;
+ delete window.__VITEST_TEST__;
+});
+
+it('shows a retryable state for HTTP 500 and not-found only for HTTP 404', async () => {
+ vi.resetModules();
+ delete window.__VITEST_TEST__;
+ // eslint-disable-next-line no-unsanitized/property -- checked-in template is the browser fixture.
+ document.body.innerHTML = readFileSync(TEMPLATE_PATH, 'utf8');
+ window.noteId = NOTE_ID;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-load-state') };
+ window.ui = { showMessage: vi.fn() };
+ window.bootstrap = { Modal: ModalStub };
+ globalThis.bootstrap = window.bootstrap;
+ vi.stubGlobal('IntersectionObserver', IntersectionObserverStub);
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+
+ let noteLoads = 0;
+ const safeFetchWithAuth = vi.fn((input) => {
+ const url = String(input);
+ if (url === `/notes/api/notes/${NOTE_ID}`) {
+ noteLoads += 1;
+ return Promise.resolve(new Response(JSON.stringify({
+ detail: noteLoads === 1
+ ? 'Temporary database outage'
+ : 'Note not found',
+ }), {
+ status: noteLoads === 1 ? 500 : 404,
+ }));
+ }
+ if (url === '/library/api/collections') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected note bootstrap request: ${url}`);
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+
+ await import('@js/pages/note-detail.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('note-load-error').style.display)
+ .toBe('block');
+ });
+ expect(document.getElementById('note-not-found').style.display).toBe('none');
+ expect(document.getElementById('note-content-wrapper').style.display)
+ .toBe('none');
+
+ document.querySelector('[data-action="retry-load-note"]').click();
+
+ await vi.waitFor(() => {
+ expect(noteLoads).toBe(2);
+ expect(document.getElementById('note-not-found').style.display)
+ .toBe('block');
+ });
+ expect(document.getElementById('note-load-error').style.display).toBe('none');
+ expect(document.getElementById('note-content-wrapper').style.display)
+ .toBe('none');
+});
diff --git a/tests/js/pages/note-detail-bootstrap-runtime.test.js b/tests/js/pages/note-detail-bootstrap-runtime.test.js
new file mode 100644
index 0000000000..5c85b6fa5f
--- /dev/null
+++ b/tests/js/pages/note-detail-bootstrap-runtime.test.js
@@ -0,0 +1,204 @@
+/** Browser-shaped bootstrap contract for the checked-in note detail page. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/note_detail.html',
+);
+const NOTE_ID = 'note-3299';
+let bootstrapFetchMock;
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), { status });
+}
+
+class ModalStub {
+ show = vi.fn();
+ hide = vi.fn();
+
+ static getOrCreateInstance() {
+ return new ModalStub();
+ }
+
+ static getInstance() {
+ return new ModalStub();
+ }
+}
+
+class IntersectionObserverStub {
+ constructor(callback, options) {
+ this.callback = callback;
+ this.options = options;
+ }
+
+ observe = vi.fn();
+ disconnect = vi.fn();
+}
+
+beforeAll(async () => {
+ delete window.__VITEST_TEST__;
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture.
+ document.body.innerHTML = readFileSync(TEMPLATE_PATH, 'utf8');
+ window.noteId = NOTE_ID;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-note-bootstrap') };
+ window.ui = { showMessage: vi.fn() };
+ window.bootstrap = { Modal: ModalStub };
+ globalThis.bootstrap = window.bootstrap;
+ vi.stubGlobal('IntersectionObserver', IntersectionObserverStub);
+ vi.stubGlobal('URLValidator', { safeAssign: vi.fn() });
+ vi.stubGlobal('escapeHtml', value => String(value ?? '').replace(
+ /[&<>"']/g,
+ character => ({
+ '&': '&amp;',
+ '<': '&lt;',
+ '>': '&gt;',
+ '"': '&quot;',
+ "'": '&#39;',
+ })[character],
+ ));
+ // The production renderer is already tested separately; this fixture
+ // keeps the bootstrap focused while still producing headings/wiki links.
+ vi.stubGlobal('renderMarkdown', vi.fn(() => (
+ '<h1>Migration heading</h1>'
+ + '<p>See [[Resolved note|the source]] for details.</p>'
+ )));
+
+ const routePayloads = new Map([
+ [`/notes/api/notes/${NOTE_ID}`, {
+ success: true,
+ note: {
+ id: NOTE_ID,
+ title: '<img src=x onerror="window.__noteBootstrapXss=true"> Migration note',
+ content: '# Migration heading\n\nSee [[Resolved note|the source]] for details.',
+ tags: ['fastapi', '<script>unsafe</script>'],
+ pinned: true,
+ is_indexed: false,
+ created_at: '2026-08-31T10:00:00Z',
+ updated_at: '2026-09-01T10:00:00Z',
+ outgoing_links: [{
+ link_text: 'Resolved note',
+ target_id: 'target-note-3299',
+ }],
+ },
+ }],
+ ['/library/api/collections', {
+ success: true,
+ collections: [{ id: 'collection-2', name: 'Available collection' }],
+ }],
+ [`/notes/api/notes/${NOTE_ID}/collections`, {
+ success: true,
+ collections: [{
+ id: 'notes-home',
+ name: 'Notes',
+ collection_type: 'notes',
+ indexed: true,
+ }],
+ }],
+ [`/notes/api/notes/${NOTE_ID}/research`, {
+ success: true,
+ research: [],
+ }],
+ [`/notes/api/notes/${NOTE_ID}/backlinks`, {
+ success: true,
+ backlinks: [{
+ id: 'backlink-1',
+ title: 'Backlink note',
+ content_preview: 'Linked this migration note',
+ }],
+ }],
+ [`/notes/api/notes/${NOTE_ID}/outgoing-links`, {
+ success: true,
+ outgoing_links: [{
+ id: 'target-note-3299',
+ title: 'Resolved note',
+ content_preview: 'Target preview',
+ }],
+ }],
+ [`/notes/api/notes/${NOTE_ID}/versions?limit=20&offset=0`, {
+ success: true,
+ versions: [],
+ total: 0,
+ }],
+ ]);
+ bootstrapFetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (!routePayloads.has(url)) {
+ throw new Error(`Unexpected note bootstrap request: ${url}`);
+ }
+ return Promise.resolve(jsonResponse(routePayloads.get(url)));
+ });
+ vi.stubGlobal('safeFetchWithAuth', bootstrapFetchMock);
+
+ await import('@js/pages/note-detail.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(document.getElementById('note-content-wrapper').style.display)
+ .toBe('block');
+ expect(document.getElementById('sidebar-backlinks').textContent)
+ .toContain('Backlink note');
+ expect(document.getElementById('sidebar-outgoing-links').textContent)
+ .toContain('Resolved note');
+ });
+
+});
+
+afterAll(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.noteId;
+ delete window.api;
+ delete window.ui;
+ delete window.bootstrap;
+ delete window.__noteBootstrapXss;
+});
+
+it('loads every dependent panel and renders the note through safe DOM ownership', () => {
+ expect(new Set(bootstrapFetchMock.mock.calls.map(([url]) => String(url)))).toEqual(
+ new Set([
+ `/notes/api/notes/${NOTE_ID}`,
+ '/library/api/collections',
+ `/notes/api/notes/${NOTE_ID}/collections`,
+ `/notes/api/notes/${NOTE_ID}/research`,
+ `/notes/api/notes/${NOTE_ID}/backlinks`,
+ `/notes/api/notes/${NOTE_ID}/outgoing-links`,
+ `/notes/api/notes/${NOTE_ID}/versions?limit=20&offset=0`,
+ ]),
+ );
+
+ const title = document.getElementById('note-title-display');
+ expect(title.textContent).toContain('<img src=x onerror=');
+ expect(title.querySelector('img')).toBeNull();
+ expect(window.__noteBootstrapXss).toBeUndefined();
+ expect(document.getElementById('ldr-note-title').value)
+ .toContain('Migration note');
+ expect(document.getElementById('pin-btn').classList).toContain('ldr-pinned');
+ expect(document.getElementById('note-indexed').style.display)
+ .toBe('inline-flex');
+ expect(document.querySelectorAll('#note-tags-display .ldr-tag'))
+ .toHaveLength(2);
+ expect(document.querySelector('#ldr-note-collections .ldr-collection-badge')
+ .textContent).toContain('Notes');
+ expect(document.querySelector('#ldr-note-collections [data-collection-id]'))
+ .toBeNull();
+ expect(document.querySelector('#toc-list [data-heading-id="heading-0"]'))
+ .not.toBeNull();
+ expect(document.getElementById('research-list').textContent)
+ .toContain('No research runs yet');
+ expect(document.getElementById('ldr-versions-list').textContent)
+ .toContain('No version history yet');
+ expect(document.title).toContain('Migration note - Deep Research System');
+
+ const wikiLink = document.querySelector(
+ '#note-content-rendered .ldr-wiki-link',
+ );
+ expect(wikiLink.textContent).toBe('the source');
+ wikiLink.click();
+ expect(URLValidator.safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ '/notes/target-note-3299',
+ );
+});
diff --git a/tests/js/pages/note-detail-compare-version.test.js b/tests/js/pages/note-detail-compare-version.test.js
index c57d59436c..b48dd84a8f 100644
--- a/tests/js/pages/note-detail-compare-version.test.js
+++ b/tests/js/pages/note-detail-compare-version.test.js
@@ -31,11 +31,40 @@ beforeEach(() => {
document.body.innerHTML = '<div id="diffModal"></div><div id="diff-modal-body"></div>';
window.ui = { showMessage: vi.fn() };
hook.setNote({ id: 'note-1', title: 'T', content: 'c', tags: [] });
+ hook.resetDiffState();
});
const body = () => document.getElementById('diff-modal-body').innerHTML;
describe('compareVersion', () => {
+ it('does not repaint or reopen a diff dismissed while the request is in flight', async () => {
+ let resolveDiff;
+ const pendingDiff = new Promise(resolve => {
+ resolveDiff = resolve;
+ });
+ globalThis.safeFetch = vi.fn(() => pendingDiff);
+ const show = vi.fn();
+ window.bootstrap.Modal.getOrCreateInstance = vi.fn(() => ({ show }));
+ const modalEl = document.getElementById('diffModal');
+
+ const comparison = hook.compareVersion('ver-dismissed-3299');
+ await vi.waitFor(() => expect(globalThis.safeFetch).toHaveBeenCalledOnce());
+ expect(show).toHaveBeenCalledOnce();
+ expect(body()).toContain('Computing semantic diff');
+
+ modalEl.dispatchEvent(new Event('hidden.bs.modal'));
+ resolveDiff({
+ json: () => Promise.resolve({
+ success: true,
+ diff: { summary: 'Late result must stay dismissed' },
+ }),
+ });
+ await comparison;
+
+ expect(show).toHaveBeenCalledOnce();
+ expect(body()).not.toContain('Late result must stay dismissed');
+ });
+
it('renders the diff sections on success', async () => {
globalThis.safeFetch = vi.fn((url) => {
expect(url).toContain('/versions/semantic-diff');
diff --git a/tests/js/pages/note-detail-research-reorder.test.js b/tests/js/pages/note-detail-research-reorder.test.js
new file mode 100644
index 0000000000..90529fe19a
--- /dev/null
+++ b/tests/js/pages/note-detail-research-reorder.test.js
@@ -0,0 +1,292 @@
+/** Research-card drag/drop ordering through the real note-detail handlers. */
+
+let hook;
+
+function jsonResponse(payload) {
+ return {
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function dragEvent(type, dataTransfer) {
+ const event = new Event(type, { bubbles: true, cancelable: true });
+ Object.defineProperty(event, 'dataTransfer', { value: dataTransfer });
+ return event;
+}
+
+function renderedOrder() {
+ return Array.from(document.querySelectorAll('.ldr-research-item'))
+ .map(item => item.dataset.researchId);
+}
+
+beforeAll(async () => {
+ window.__VITEST_TEST__ = true;
+ globalThis.safeFetch = vi.fn();
+ globalThis.escapeHtml = value => String(value ?? '');
+ await import('@js/pages/note-detail.js');
+ hook = window.__noteDetailTest;
+});
+
+afterAll(() => {
+ delete window.__VITEST_TEST__;
+});
+
+beforeEach(() => {
+ document.body.innerHTML = `
+ <span id="sidebar-research-count"></span>
+ <div id="research-list"></div>
+ `;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-reorder-3299') };
+ window.ui = { showMessage: vi.fn() };
+ hook.setNote({ id: 'note-reorder-3299', title: 'Order', content: '' });
+ hook.setNoteResearch([
+ {
+ research_id: 'research-one',
+ query_used: 'One',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:00:00Z',
+ },
+ {
+ research_id: 'research-two',
+ query_used: 'Two',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:01:00Z',
+ },
+ {
+ research_id: 'research-three',
+ query_used: 'Three',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:02:00Z',
+ },
+ ]);
+ hook.renderNoteResearch();
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.api;
+ delete window.ui;
+ document.body.replaceChildren();
+});
+
+it('serializes rapid drops and sends each captured order with CSRF', async () => {
+ let resolveFirst;
+ const firstResponse = new Promise(resolve => {
+ resolveFirst = resolve;
+ });
+ const fetchMock = vi.fn()
+ .mockReturnValueOnce(firstResponse)
+ .mockResolvedValueOnce(jsonResponse({ success: true }));
+ globalThis.safeFetch = fetchMock;
+ const transfer = {
+ effectAllowed: '',
+ dropEffect: '',
+ setData: vi.fn(),
+ };
+
+ const one = document.querySelector('[data-research-id="research-one"]');
+ const two = document.querySelector('[data-research-id="research-two"]');
+ const three = document.querySelector('[data-research-id="research-three"]');
+ one.dispatchEvent(dragEvent('dragstart', transfer));
+ two.dispatchEvent(dragEvent('drop', transfer));
+ one.dispatchEvent(dragEvent('dragend', transfer));
+ expect(renderedOrder()).toEqual([
+ 'research-two',
+ 'research-one',
+ 'research-three',
+ ]);
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+
+ three.dispatchEvent(dragEvent('dragstart', transfer));
+ two.dispatchEvent(dragEvent('drop', transfer));
+ three.dispatchEvent(dragEvent('dragend', transfer));
+ expect(renderedOrder()).toEqual([
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ]);
+ // The newer intent is queued until the older write settles.
+ expect(fetchMock).toHaveBeenCalledOnce();
+
+ resolveFirst(jsonResponse({ success: true }));
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+
+ expect(fetchMock.mock.calls.map(([url, options]) => ({
+ url,
+ method: options.method,
+ csrf: options.headers['X-CSRFToken'],
+ body: JSON.parse(options.body),
+ }))).toEqual([
+ {
+ url: '/notes/api/notes/note-reorder-3299/research/reorder',
+ method: 'POST',
+ csrf: 'csrf-reorder-3299',
+ body: {
+ research_ids: [
+ 'research-two',
+ 'research-one',
+ 'research-three',
+ ],
+ },
+ },
+ {
+ url: '/notes/api/notes/note-reorder-3299/research/reorder',
+ method: 'POST',
+ csrf: 'csrf-reorder-3299',
+ body: {
+ research_ids: [
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ],
+ },
+ },
+ ]);
+ expect(hook.getNoteResearch().map(item => item.research_id)).toEqual([
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ]);
+});
+
+it('keeps a newer reorder authoritative when the older write fails', async () => {
+ let rejectFirst;
+ const firstResponse = new Promise((_resolve, reject) => {
+ rejectFirst = reject;
+ });
+ const fetchMock = vi.fn()
+ .mockReturnValueOnce(firstResponse)
+ .mockResolvedValueOnce(jsonResponse({ success: true }));
+ globalThis.safeFetch = fetchMock;
+ const container = document.getElementById('research-list');
+ const one = container.querySelector('[data-research-id="research-one"]');
+ const two = container.querySelector('[data-research-id="research-two"]');
+ const three = container.querySelector('[data-research-id="research-three"]');
+
+ container.insertBefore(two, one);
+ const olderReorder = hook.persistResearchOrder();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+
+ container.insertBefore(three, two);
+ const latestReorder = hook.persistResearchOrder();
+ expect(renderedOrder()).toEqual([
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ]);
+
+ rejectFirst(new Error('older reorder failed'));
+ await Promise.all([olderReorder, latestReorder]);
+
+ // The stale failure must not show an error or call loadNoteResearch(),
+ // whose GET would repaint the newly dragged order with server state.
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls.map(([, options]) =>
+ JSON.parse(options.body).research_ids
+ )).toEqual([
+ ['research-two', 'research-one', 'research-three'],
+ ['research-three', 'research-two', 'research-one'],
+ ]);
+ expect(window.ui.showMessage).not.toHaveBeenCalled();
+ expect(renderedOrder()).toEqual([
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ]);
+ expect(hook.getNoteResearch().map(item => item.research_id)).toEqual([
+ 'research-three',
+ 'research-two',
+ 'research-one',
+ ]);
+});
+
+it.each(['response', 'body', 'failure'])('preserves a newer drop during recovery %s', async stage => {
+ let settleRecovery;
+ const recovery = new Promise((resolve, reject) => {
+ settleRecovery = stage === 'failure' ? reject : resolve;
+ });
+ const original = [...hook.getNoteResearch()];
+ const fetchMock = vi.fn()
+ .mockRejectedValueOnce(new Error('first write failed'))
+ .mockReturnValueOnce(stage === 'body'
+ ? { ok: true, json: () => recovery }
+ : recovery)
+ .mockResolvedValueOnce(jsonResponse({ success: true }));
+ globalThis.safeFetch = fetchMock;
+ const container = document.getElementById('research-list');
+ container.prepend(container.querySelector('[data-research-id="research-two"]'));
+ const first = hook.persistResearchOrder();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(2));
+ container.prepend(container.querySelector('[data-research-id="research-three"]'));
+ const second = hook.persistResearchOrder();
+ const newest = ['research-three', 'research-two', 'research-one'];
+ expect(renderedOrder()).toEqual(newest);
+ const data = { success: true, research: original };
+ settleRecovery(stage === 'failure' ? new Error('stale recovery failed')
+ : stage === 'body' ? data : jsonResponse(data));
+ await Promise.all([first, second]);
+ expect(fetchMock).toHaveBeenCalledTimes(3);
+ expect(renderedOrder()).toEqual(newest);
+ expect(hook.getNoteResearch().map(item => item.research_id)).toEqual(newest);
+ expect(JSON.parse(fetchMock.mock.calls[2][1].body).research_ids).toEqual(newest);
+});
+
+it('reports the latest reorder failure and restores the server order', async () => {
+ const serverOrder = [
+ {
+ research_id: 'research-one',
+ query_used: 'One restored',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:00:00Z',
+ },
+ {
+ research_id: 'research-two',
+ query_used: 'Two restored',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:01:00Z',
+ },
+ {
+ research_id: 'research-three',
+ query_used: 'Three restored',
+ research_mode: 'quick',
+ created_at: '2026-09-01T10:02:00Z',
+ },
+ ];
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(jsonResponse({
+ success: false,
+ error: 'reorder rejected',
+ }))
+ .mockResolvedValueOnce(jsonResponse({
+ success: true,
+ research: serverOrder,
+ }));
+ globalThis.safeFetch = fetchMock;
+ const container = document.getElementById('research-list');
+ const one = container.querySelector('[data-research-id="research-one"]');
+ const two = container.querySelector('[data-research-id="research-two"]');
+
+ container.insertBefore(two, one);
+ await hook.persistResearchOrder();
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(fetchMock.mock.calls[0][0]).toBe(
+ '/notes/api/notes/note-reorder-3299/research/reorder',
+ );
+ expect(fetchMock.mock.calls[1]).toEqual([
+ '/notes/api/notes/note-reorder-3299/research',
+ { credentials: 'same-origin' },
+ ]);
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Failed to save new order',
+ 'error',
+ );
+ expect(renderedOrder()).toEqual([
+ 'research-one',
+ 'research-two',
+ 'research-three',
+ ]);
+ expect(hook.getNoteResearch()).toEqual(serverOrder);
+});
diff --git a/tests/js/pages/note-detail-wikilink-render.test.js b/tests/js/pages/note-detail-wikilink-render.test.js
index bae77cc634..93893bdfbe 100644
--- a/tests/js/pages/note-detail-wikilink-render.test.js
+++ b/tests/js/pages/note-detail-wikilink-render.test.js
@@ -30,6 +30,13 @@ afterAll(() => {
});
beforeEach(() => {
+ globalThis.safeFetch = vi.fn(() =>
+ Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ success: true }),
+ })
+ );
+ window.URLValidator = { safeAssign: vi.fn() };
hook.setNote({
id: 'note-1',
outgoing_links: [{ link_text: 'Target Note', target_id: 't1' }],
@@ -60,6 +67,38 @@ describe('processWikiLinks', () => {
expect(a.getAttribute('data-note-title')).toBe(encodeURIComponent('Unknown Note'));
});
+ it('navigates an unresolved link to the exact title match, not the source note content match', async () => {
+ hook.setNote({ id: 'source-note', outgoing_links: [] });
+ globalThis.safeFetch = vi.fn().mockResolvedValue({
+ ok: true,
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ notes: [{
+ id: 'source-note',
+ title: 'Source note containing the link',
+ }, {
+ id: 'exact-target-3299',
+ title: 'Unknown Note',
+ }],
+ }),
+ });
+ const el = render('See [[Unknown Note]] here');
+
+ el.querySelector('a.ldr-wiki-link').click();
+
+ await vi.waitFor(() => {
+ expect(window.URLValidator.safeAssign).toHaveBeenCalledWith(
+ window.location,
+ 'href',
+ '/notes/exact-target-3299',
+ );
+ });
+ expect(globalThis.safeFetch).toHaveBeenCalledWith(
+ '/notes/api/notes?search=Unknown%20Note&limit=20',
+ { credentials: 'same-origin' },
+ );
+ });
+
it('supports the [[Target|Display]] alias syntax', () => {
const el = render('[[Target Note|click here]]');
const a = el.querySelector('a.ldr-wiki-link');
diff --git a/tests/js/pages/notes-bootstrap-runtime.test.js b/tests/js/pages/notes-bootstrap-runtime.test.js
new file mode 100644
index 0000000000..81b5013db1
--- /dev/null
+++ b/tests/js/pages/notes-bootstrap-runtime.test.js
@@ -0,0 +1,181 @@
+/** Browser-shaped bootstrap contract for the checked-in notes page. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/notes.html',
+);
+
+class ModalStub {
+ static instances = new Map();
+
+ constructor(element) {
+ this.element = element;
+ this.show = vi.fn();
+ this.hide = vi.fn();
+ ModalStub.instances.set(element.id, this);
+ }
+}
+
+function jsonResponse(payload, status = 200) {
+ return new Response(JSON.stringify(payload), { status });
+}
+
+let fetchMock;
+
+beforeAll(async () => {
+ delete window.__VITEST_TEST__;
+ ModalStub.instances.clear();
+ // eslint-disable-next-line no-unsanitized/property -- checked-in repository template used as the browser fixture.
+ document.body.innerHTML = readFileSync(TEMPLATE_PATH, 'utf8');
+ window.bootstrap = { Modal: ModalStub };
+ globalThis.bootstrap = window.bootstrap;
+ window.ui = { showMessage: vi.fn() };
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-notes-bootstrap') };
+
+ const notePayload = {
+ success: true,
+ total: 1,
+ notes: [{
+ id: 'note/3299',
+ title: '<img src=x onerror="window.__notesBootstrapXss=true"> Migration note',
+ content: '# FastAPI\n<script>window.__notesBootstrapXss=true</script>',
+ tags: ['migration', '<svg onload="window.__notesBootstrapXss=true">'],
+ pinned: true,
+ is_indexed: true,
+ research_count: 2,
+ updated_at: '2026-09-01T12:00:00Z',
+ }],
+ };
+ fetchMock = vi.fn((input) => {
+ const url = String(input);
+ if (url.startsWith('/notes/api/notes?')) {
+ return Promise.resolve(jsonResponse(notePayload));
+ }
+ if (url === '/library/api/collections') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ id: 'collection/3299',
+ name: '<img src=x onerror="window.__notesBootstrapXss=true"> Evidence',
+ }],
+ }));
+ }
+ throw new Error(`Unexpected notes bootstrap request: ${url}`);
+ });
+ vi.stubGlobal('safeFetchWithAuth', fetchMock);
+
+ await import('@js/security/xss-protection.js');
+ await import('@js/services/formatting.js');
+ await import('@js/pages/notes.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('#ldr-notes-grid .ldr-note-card'))
+ .toHaveLength(1);
+ expect(document.querySelectorAll('#ldr-collection-filter option'))
+ .toHaveLength(2);
+ });
+});
+
+afterAll(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ ModalStub.instances.clear();
+ document.body.replaceChildren();
+ delete window.bootstrap;
+ delete window.ui;
+ delete window.api;
+ delete window.__notesBootstrapXss;
+ delete window.__notesToolbarXss;
+});
+
+it('loads, safely renders, filters, and switches mode', async () => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/notes/api/notes?limit=100',
+ expect.objectContaining({ credentials: 'same-origin' }),
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/library/api/collections',
+ { credentials: 'same-origin' },
+ );
+
+ const card = document.querySelector('#ldr-notes-grid .ldr-note-card');
+ expect(card.getAttribute('href')).toBe('/notes/note%2F3299');
+ expect(card.textContent).toContain('<img src=x onerror=');
+ expect(card.textContent).toContain('FastAPI');
+ expect(card.classList).toContain('ldr-pinned');
+ expect(card.querySelector('img')).toBeNull();
+ expect(card.querySelector('script')).toBeNull();
+ expect(window.__notesBootstrapXss).toBeUndefined();
+
+ const collectionFilter = document.getElementById('ldr-collection-filter');
+ expect(collectionFilter.options[1].value).toBe('collection/3299');
+ expect(collectionFilter.options[1].textContent).toContain('<img src=x');
+ collectionFilter.value = 'collection/3299';
+ collectionFilter.dispatchEvent(new Event('change', { bubbles: true }));
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/notes/api/notes?collection_id=collection%2F3299&limit=100',
+ expect.objectContaining({ credentials: 'same-origin' }),
+ );
+ });
+
+ document.querySelector('[data-mode="text"]').click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('notes-search-mode-label').textContent)
+ .toBe('Text Only');
+ });
+ expect(document.getElementById('ldr-notes-search').placeholder)
+ .toBe('Search notes by keyword...');
+});
+
+it('initializes the checked-in modal toolbar and preview after opening', async () => {
+ vi.useFakeTimers();
+ try {
+ const originalBoldButton = document.querySelector(
+ '#modal-markdown-toolbar [data-format="bold"]',
+ );
+
+ document.getElementById('note-title').value = 'stale title';
+ document.getElementById('note-content').value = 'stale content';
+ document.querySelector('[data-action="create-new-note"]').click();
+ expect(document.getElementById('note-title').value).toBe('');
+ expect(document.getElementById('note-content').value).toBe('');
+ expect(ModalStub.instances.get('noteModal').show).toHaveBeenCalledOnce();
+
+ await vi.advanceTimersByTimeAsync(100);
+ const boldButton = document.querySelector(
+ '#modal-markdown-toolbar [data-format="bold"]',
+ );
+ expect(boldButton).not.toBe(originalBoldButton);
+
+ const textarea = document.getElementById('note-content');
+ textarea.value = 'migration note';
+ textarea.setSelectionRange(0, 9);
+ boldButton.querySelector('i').click();
+ expect(textarea.value).toBe('**migration** note');
+ expect(textarea.selectionStart).toBe(2);
+ expect(textarea.selectionEnd).toBe(11);
+
+ delete window.__notesToolbarXss;
+ textarea.value =
+ '<img src=x onerror="window.__notesToolbarXss=true"> **safe preview**';
+ document.querySelector('.ldr-editor-tab[data-mode="preview"] i').click();
+
+ const preview = document.getElementById('modal-note-preview');
+ expect(textarea.style.display).toBe('none');
+ expect(document.getElementById('modal-markdown-toolbar').style.display)
+ .toBe('none');
+ expect(preview.style.display).toBe('block');
+ expect(preview.querySelector('img')).toBeNull();
+ expect(preview.querySelector('strong').textContent).toBe('safe preview');
+ expect(preview.textContent).toContain('<img src=x onerror=');
+ expect(window.__notesToolbarXss).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/tests/js/pages/subscriptions-direct-runtime.test.js b/tests/js/pages/subscriptions-direct-runtime.test.js
new file mode 100644
index 0000000000..9e0b0cf9c1
--- /dev/null
+++ b/tests/js/pages/subscriptions-direct-runtime.test.js
@@ -0,0 +1,403 @@
+/** Direct browser-runtime coverage for the migrated subscriptions page. */
+
+const NOW = new Date('2026-09-01T12:00:00.000Z');
+
+function jsonResponse(payload, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status === 200 ? 'OK' : 'Request failed',
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function installDom() {
+ document.body.innerHTML = `
+ <header class="ldr-page-header"><h1>Subscriptions</h1></header>
+ <span id="total-subscriptions">0</span>
+ <span id="active-subscriptions">0</span>
+ <span id="paused-subscriptions">0</span>
+ <span id="updates-today">0</span>
+ <span id="status-indicator"></span>
+ <span id="status-text"></span>
+ <span id="scheduler-details"></span>
+ <div class="ldr-folder-list">
+ <div class="ldr-folder-item active" data-folder="all">
+ All <span class="ldr-folder-count">0</span>
+ </div>
+ <div class="ldr-folder-item" data-folder="uncategorized">
+ Uncategorized <span class="ldr-folder-count">0</span>
+ </div>
+ </div>
+ <button id="add-folder-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <input id="subscription-search">
+ <select id="status-filter">
+ <option value="all">All</option>
+ <option value="active">Active</option>
+ <option value="paused">Paused</option>
+ </select>
+ <select id="frequency-filter">
+ <option value="all">All</option>
+ <option value="hourly">Hourly</option>
+ <option value="daily">Daily</option>
+ <option value="weekly">Weekly</option>
+ </select>
+ <main id="subscriptions-grid"></main>
+ `;
+}
+
+let serverSubscriptions;
+let serverFolders;
+let fetchMock;
+let startResearchPayload;
+let modalShow;
+let registeredDocumentListeners;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ vi.setSystemTime(NOW);
+ registeredDocumentListeners = [];
+ localStorage.clear();
+ installDom();
+
+ const purify = {
+ addHook: vi.fn(),
+ sanitize: vi.fn(dirty => {
+ const template = document.createElement('template');
+ // eslint-disable-next-line no-unsanitized/property -- test-only sanitizer stand-in for repo-owned fixtures.
+ template.innerHTML = String(dirty);
+ template.content.querySelectorAll('script, iframe, object')
+ .forEach(node => node.remove());
+ template.content.querySelectorAll('*').forEach(node => {
+ for (const attr of [...node.attributes]) {
+ if (attr.name.startsWith('on')) node.removeAttribute(attr.name);
+ }
+ });
+ return template.innerHTML;
+ }),
+ };
+ globalThis.DOMPurify = purify;
+ window.DOMPurify = purify;
+ await import('@js/security/xss-protection.js');
+ await import('@js/utils/alert-helpers.js');
+
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-subscriptions-direct') };
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ modalShow = vi.fn();
+ const modalInstances = new WeakMap();
+ class Modal {
+ constructor(element) {
+ this.element = element;
+ modalInstances.set(element, this);
+ }
+
+ show() {
+ modalShow(this.element);
+ }
+
+ hide() {}
+
+ static getInstance(element) {
+ return modalInstances.get(element) || null;
+ }
+ }
+ globalThis.bootstrap = { Modal };
+ window.bootstrap = globalThis.bootstrap;
+
+ serverSubscriptions = [{
+ id: 'sub-active',
+ name: '<img src=x onerror="window.__subscriptionXss=true"> Migration watch',
+ query: 'FastAPI migration updates',
+ is_active: true,
+ folder_id: 'folder-security',
+ refresh_minutes: 60,
+ refresh_interval: 'hourly',
+ last_refreshed: NOW.toISOString(),
+ next_refresh: '2026-09-02T12:00:00.000Z',
+ created_at: '2026-08-01T10:00:00.000Z',
+ total_runs: 4,
+ source_id: 'source/3299?view=full',
+ }, {
+ id: 'sub-paused',
+ name: 'Economy daily',
+ query: 'Economy and markets',
+ is_active: false,
+ folder_id: null,
+ refresh_minutes: 1440,
+ refresh_interval: 'daily',
+ last_refreshed: '2026-08-30T10:00:00.000Z',
+ created_at: '2026-08-02T10:00:00.000Z',
+ total_runs: 0,
+ }, {
+ id: 'sub-weekly',
+ query: 'Security bulletin',
+ is_active: true,
+ folder_id: null,
+ refresh_minutes: 10080,
+ refresh_interval: 'weekly',
+ created_at: '2026-08-03T10:00:00.000Z',
+ }];
+ serverFolders = [{
+ id: 'folder-security',
+ name: '<img src=x onerror="window.__folderXss=true"> Security',
+ }];
+
+ fetchMock = vi.fn(async (input, options = {}) => {
+ const url = String(input);
+ if (url === '/news/api/subscriptions/current') {
+ return jsonResponse({
+ subscriptions: serverSubscriptions.map(item => ({ ...item })),
+ });
+ }
+ if (url === '/news/api/subscription/folders' && !options.method) {
+ return jsonResponse({
+ folders: serverFolders.map(folder => ({ ...folder })),
+ });
+ }
+ if (url === '/news/api/scheduler/status') {
+ return jsonResponse({
+ scheduler_available: true,
+ is_running: true,
+ active_users: 0,
+ scheduled_jobs: 3,
+ });
+ }
+ if (url === '/api/start_research') {
+ startResearchPayload = JSON.parse(options.body);
+ return jsonResponse({
+ status: 'queued',
+ research_id: 'research-3299<script>',
+ });
+ }
+ if (url === '/news/api/subscriptions/sub-active' && options.method === 'PUT') {
+ serverSubscriptions.find(item => item.id === 'sub-active').is_active = false;
+ return jsonResponse({ status: 'success' });
+ }
+ if (url === '/news/api/subscriptions/sub-active/history') {
+ return jsonResponse({
+ total_runs: 1,
+ history: [{
+ research_id: 'history/id?unsafe=true',
+ headline: '<img src=x onerror="window.__historyXss=true"> Result',
+ status: 'completed" onclick="window.__historyXss=true',
+ created_at: NOW.toISOString(),
+ duration_seconds: 12,
+ topics: ['<script>window.__historyXss=true</script>', 'FastAPI'],
+ }],
+ });
+ }
+ if (url === '/news/api/subscriptions/sub-paused' && options.method === 'DELETE') {
+ serverSubscriptions = serverSubscriptions.filter(item => item.id !== 'sub-paused');
+ return jsonResponse({}, 204);
+ }
+ if (url === '/news/api/subscription/folders' && options.method === 'POST') {
+ const folder = { id: 'folder-new', name: JSON.parse(options.body).name };
+ serverFolders.push(folder);
+ return jsonResponse(folder);
+ }
+ throw new Error(`Unexpected request: ${url} ${options.method || 'GET'}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ vi.stubGlobal('prompt', vi.fn(() => ' Migration Team '));
+
+ const originalDocumentAdd = document.addEventListener.bind(document);
+ const documentAddSpy = vi.spyOn(document, 'addEventListener')
+ .mockImplementation((type, listener, options) => {
+ registeredDocumentListeners.push([type, listener, options]);
+ originalDocumentAdd(type, listener, options);
+ });
+ try {
+ await import('@js/pages/subscriptions.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await vi.waitFor(() => {
+ expect(document.querySelectorAll('.ldr-subscription-card')).toHaveLength(3);
+ expect(document.querySelector('[data-folder="folder-security"]')).not.toBeNull();
+ expect(document.getElementById('status-text').textContent)
+ .toBe('Not Tracking Your Session');
+ });
+ } finally {
+ documentAddSpy.mockRestore();
+ }
+});
+
+afterEach(() => {
+ registeredDocumentListeners.forEach(([type, listener, options]) => {
+ document.removeEventListener(type, listener, options);
+ });
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ document.body.replaceChildren();
+ delete window.__subscriptionXss;
+ delete window.__folderXss;
+ delete window.__historyXss;
+ delete window.api;
+ delete window.bootstrap;
+ delete window.DOMPurify;
+ delete window.runSubscriptionNow;
+ delete window.toggleSubscription;
+ delete window.viewSubscriptionHistory;
+ delete window.deleteSubscriptionDirect;
+ delete window.showSchedulerInfo;
+ delete window.formatNextUpdate;
+});
+
+it('boots against the migrated envelopes and renders safe cards, folders, stats, and scheduler state', () => {
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscriptions/current', {
+ credentials: 'same-origin',
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscription/folders', {
+ credentials: 'same-origin',
+ });
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/scheduler/status', {
+ credentials: 'same-origin',
+ });
+ expect(document.getElementById('total-subscriptions').textContent).toBe('3');
+ expect(document.getElementById('active-subscriptions').textContent).toBe('2');
+ expect(document.getElementById('paused-subscriptions').textContent).toBe('1');
+ expect(document.getElementById('updates-today').textContent).toBe('1');
+ expect(document.querySelector('[data-folder="all"] .ldr-folder-count').textContent)
+ .toBe('3');
+ expect(document.querySelector('[data-folder="uncategorized"] .ldr-folder-count').textContent)
+ .toBe('2');
+ expect(document.querySelector('img, script')).toBeNull();
+ expect(window.__subscriptionXss).toBeUndefined();
+ expect(window.__folderXss).toBeUndefined();
+ expect(document.querySelector('[data-subscription-id="sub-active"] .ldr-source-link')
+ .getAttribute('href')).toBe('/progress/source%2F3299%3Fview%3Dfull');
+ expect(document.getElementById('scheduler-details').textContent)
+ .toContain('Log out and log back in');
+});
+
+it('combines search, status, frequency, and folder filters through real DOM listeners', () => {
+ const visibleIds = () => [...document.querySelectorAll('.ldr-subscription-card')]
+ .map(card => card.dataset.subscriptionId);
+ const status = document.getElementById('status-filter');
+ status.value = 'paused';
+ status.dispatchEvent(new Event('change'));
+ expect(visibleIds()).toEqual(['sub-paused']);
+
+ status.value = 'all';
+ status.dispatchEvent(new Event('change'));
+ const frequency = document.getElementById('frequency-filter');
+ frequency.value = 'weekly';
+ frequency.dispatchEvent(new Event('change'));
+ expect(visibleIds()).toEqual(['sub-weekly']);
+
+ frequency.value = 'all';
+ frequency.dispatchEvent(new Event('change'));
+ const search = document.getElementById('subscription-search');
+ search.value = 'markets';
+ search.dispatchEvent(new Event('input'));
+ expect(visibleIds()).toEqual(['sub-paused']);
+
+ search.value = '';
+ search.dispatchEvent(new Event('input'));
+ document.querySelector('[data-folder="folder-security"]')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(visibleIds()).toEqual(['sub-active']);
+
+ document.querySelector('[data-folder="all"]')
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }));
+ expect(visibleIds()).toEqual(['sub-active', 'sub-paused', 'sub-weekly']);
+});
+
+it('runs research through the real page handler with CSRF and a safe progress link', async () => {
+ expect(window.runSubscriptionNow).toEqual(expect.any(Function));
+
+ await window.runSubscriptionNow('sub-active');
+
+ const [, options] = fetchMock.mock.calls.find(([url]) => url === '/api/start_research');
+ expect(options).toMatchObject({
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-subscriptions-direct',
+ },
+ });
+ expect(startResearchPayload).toEqual({
+ query: 'FastAPI migration updates',
+ mode: 'quick',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ subscription_id: 'sub-active',
+ triggered_by: 'manual_run',
+ },
+ });
+ expect(JSON.parse(localStorage.getItem('active_news_research')))
+ .toMatchObject({
+ researchId: 'research-3299<script>',
+ query: 'FastAPI migration updates',
+ });
+ const successAlert = [...document.querySelectorAll('.alert-success')]
+ .find(alert => alert.textContent.includes('Research started!'));
+ expect(successAlert).toBeDefined();
+ expect(successAlert.querySelector('a').getAttribute('href'))
+ .toBe('/progress/research-3299script');
+ expect(successAlert.querySelector('script')).toBeNull();
+});
+
+it('renders subscription history as inert content with encoded report IDs', async () => {
+ await window.viewSubscriptionHistory('sub-active');
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscriptions/sub-active/history',
+ { credentials: 'same-origin' },
+ );
+ expect(modalShow).toHaveBeenCalledWith(document.getElementById('historyModal'));
+ const modal = document.getElementById('historyModal');
+ expect(modal.querySelector('img, script')).toBeNull();
+ expect(window.__historyXss).toBeUndefined();
+ expect(modal.querySelector('.ldr-history-item-header a').getAttribute('href'))
+ .toBe('/progress/history%2Fid%3Funsafe%3Dtrue');
+ expect(modal.querySelector('.ldr-status-badge').hasAttribute('onclick'))
+ .toBe(false);
+ modal.dispatchEvent(new Event('hidden.bs.modal'));
+ expect(document.getElementById('historyModal')).toBeNull();
+});
+
+it('updates and deletes cards through explicit global inline-action contracts', async () => {
+ await window.toggleSubscription('sub-active');
+ const toggleCall = fetchMock.mock.calls.find(([, options]) => options.method === 'PUT');
+ expect(toggleCall[0]).toBe('/news/api/subscriptions/sub-active');
+ expect(JSON.parse(toggleCall[1].body)).toEqual({ is_active: false });
+ expect(toggleCall[1].headers['X-CSRFToken']).toBe('csrf-subscriptions-direct');
+ expect(document.getElementById('active-subscriptions').textContent).toBe('1');
+
+ await window.deleteSubscriptionDirect('sub-paused');
+ const deleteCall = fetchMock.mock.calls.find(([, options]) => options.method === 'DELETE');
+ expect(deleteCall[0]).toBe('/news/api/subscriptions/sub-paused');
+ expect(deleteCall[1].headers['X-CSRFToken']).toBe('csrf-subscriptions-direct');
+ expect(document.querySelector('[data-subscription-id="sub-paused"]')).toBeNull();
+ expect(document.getElementById('total-subscriptions').textContent).toBe('2');
+});
+
+it('creates a trimmed folder through the bound control and safely re-renders it', async () => {
+ document.getElementById('add-folder-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelector('[data-folder="folder-new"]')).not.toBeNull();
+ });
+
+ const createCall = fetchMock.mock.calls.find(([url, options]) => (
+ url === '/news/api/subscription/folders' && options.method === 'POST'
+ ));
+ expect(createCall[0]).toBe('/news/api/subscription/folders');
+ expect(createCall[1].headers['X-CSRFToken']).toBe('csrf-subscriptions-direct');
+ expect(JSON.parse(createCall[1].body)).toEqual({ name: 'Migration Team' });
+ expect(document.querySelector('[data-folder="folder-new"]').textContent)
+ .toContain('Migration Team');
+
+ window.showSchedulerInfo();
+ const alert = [...document.querySelectorAll('.alert-info')].find(element => (
+ element.textContent.includes('About the Subscription Scheduler')
+ ));
+ expect(alert.textContent).toContain('About the Subscription Scheduler');
+});
diff --git a/tests/js/pages/subscriptions-folder-race-runtime.test.js b/tests/js/pages/subscriptions-folder-race-runtime.test.js
new file mode 100644
index 0000000000..a5acb3fd03
--- /dev/null
+++ b/tests/js/pages/subscriptions-folder-race-runtime.test.js
@@ -0,0 +1,208 @@
+/** Direct browser-runtime coverage for stale subscription-folder loads. */
+
+function deferred() {
+ let resolve;
+ let reject;
+ const promise = new Promise((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, resolve, reject };
+}
+
+function jsonResponse(payload, status = 200) {
+ return {
+ ok: status >= 200 && status < 300,
+ status,
+ statusText: status === 200 ? 'OK' : 'Request failed',
+ json: vi.fn().mockResolvedValue(payload),
+ };
+}
+
+function installDom() {
+ document.body.innerHTML = `
+ <header class="ldr-page-header"><h1>Subscriptions</h1></header>
+ <span id="total-subscriptions">0</span>
+ <span id="active-subscriptions">0</span>
+ <span id="paused-subscriptions">0</span>
+ <span id="updates-today">0</span>
+ <span id="status-indicator"></span>
+ <span id="status-text"></span>
+ <span id="scheduler-details"></span>
+ <div class="ldr-folder-list">
+ <div class="ldr-folder-item active" data-folder="all">
+ All <span class="ldr-folder-count">0</span>
+ </div>
+ <div class="ldr-folder-item" data-folder="uncategorized">
+ Uncategorized <span class="ldr-folder-count">0</span>
+ </div>
+ </div>
+ <button id="add-folder-btn"></button>
+ <button id="create-subscription-btn"></button>
+ <input id="subscription-search">
+ <select id="status-filter"><option value="all">All</option></select>
+ <select id="frequency-filter"><option value="all">All</option></select>
+ <main id="subscriptions-grid"></main>
+ `;
+}
+
+let registeredDocumentListeners;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ registeredDocumentListeners = [];
+ installDom();
+
+ const purify = {
+ addHook: vi.fn(),
+ sanitize: vi.fn(dirty => String(dirty)),
+ };
+ globalThis.DOMPurify = purify;
+ window.DOMPurify = purify;
+ await import('@js/security/xss-protection.js');
+ await import('@js/utils/alert-helpers.js');
+
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-folder-race') };
+ vi.stubGlobal('prompt', vi.fn(() => ' Created Folder '));
+});
+
+afterEach(() => {
+ registeredDocumentListeners.forEach(([type, listener, options]) => {
+ document.removeEventListener(type, listener, options);
+ });
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ delete window.api;
+ delete window.DOMPurify;
+ delete window.runSubscriptionNow;
+ delete window.toggleSubscription;
+ delete window.viewSubscriptionHistory;
+ delete window.deleteSubscriptionDirect;
+ delete window.showSchedulerInfo;
+ delete window.formatNextUpdate;
+});
+
+async function startFolderRace(staleStage) {
+ const staleGate = deferred();
+ const staleFolderPayload = {
+ folders: [{ id: 'folder-stale', name: 'Stale Folder' }],
+ };
+ const staleJson = vi.fn(() => (
+ staleStage === 'body'
+ ? staleGate.promise
+ : Promise.resolve(staleFolderPayload)
+ ));
+ const staleResponse = {
+ ok: true,
+ status: 200,
+ statusText: 'OK',
+ json: staleJson,
+ };
+ const createdFolder = { id: 'folder-created', name: 'Created Folder' };
+ let folderGetCount = 0;
+
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/news/api/subscriptions/current') {
+ return Promise.resolve(jsonResponse({ subscriptions: [] }));
+ }
+ if (url === '/news/api/scheduler/status') {
+ return Promise.resolve(jsonResponse({
+ scheduler_available: true,
+ is_running: true,
+ active_users: 1,
+ scheduled_jobs: 0,
+ }));
+ }
+ if (url === '/news/api/subscription/folders' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse(createdFolder));
+ }
+ if (url === '/news/api/subscription/folders') {
+ folderGetCount += 1;
+ if (folderGetCount === 1) {
+ if (staleStage === 'body') return Promise.resolve(staleResponse);
+ return staleGate.promise;
+ }
+ return Promise.resolve(jsonResponse({ folders: [createdFolder] }));
+ }
+ return Promise.reject(new Error(`Unexpected request: ${url}`));
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const originalDocumentAdd = document.addEventListener.bind(document);
+ const documentAddSpy = vi.spyOn(document, 'addEventListener')
+ .mockImplementation((type, listener, options) => {
+ registeredDocumentListeners.push([type, listener, options]);
+ originalDocumentAdd(type, listener, options);
+ });
+ try {
+ await import('@js/pages/subscriptions.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ } finally {
+ documentAddSpy.mockRestore();
+ }
+
+ if (staleStage === 'body') {
+ await vi.waitFor(() => expect(staleJson).toHaveBeenCalledOnce());
+ }
+
+ document.getElementById('add-folder-btn').click();
+ await vi.waitFor(() => {
+ expect(document.querySelector('[data-folder="folder-created"]')).not.toBeNull();
+ });
+
+ return {
+ fetchMock,
+ folderGetCount: () => folderGetCount,
+ staleGate,
+ staleJson,
+ staleResponse,
+ };
+}
+
+it.each([
+ { staleStage: 'response', description: 'late response' },
+ { staleStage: 'body', description: 'late response body' },
+])('keeps the created folder after an older initial GET $description', async ({ staleStage }) => {
+ const race = await startFolderRace(staleStage);
+
+ if (staleStage === 'response') race.staleGate.resolve(race.staleResponse);
+ else race.staleGate.resolve({ folders: [{ id: 'folder-stale', name: 'Stale Folder' }] });
+ await race.staleGate.promise;
+ await Promise.resolve();
+
+ expect(document.querySelector('[data-folder="folder-created"]')).not.toBeNull();
+ expect(document.querySelector('[data-folder="folder-stale"]')).toBeNull();
+ expect(race.folderGetCount()).toBe(2);
+ if (staleStage === 'response') expect(race.staleJson).not.toHaveBeenCalled();
+
+ const createCall = race.fetchMock.mock.calls.find(([url, options]) => (
+ url === '/news/api/subscription/folders' && options.method === 'POST'
+ ));
+ expect(createCall[1]).toMatchObject({
+ method: 'POST',
+ credentials: 'same-origin',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-folder-race',
+ },
+ });
+ expect(JSON.parse(createCall[1].body)).toEqual({ name: 'Created Folder' });
+});
+
+it('silences an older initial GET rejection after the created folder owns the UI', async () => {
+ const errorLog = vi.spyOn(SafeLogger, 'error');
+ const race = await startFolderRace('rejection');
+
+ race.staleGate.reject(new Error('older folder request failed'));
+ await expect(race.staleGate.promise).rejects.toThrow('older folder request failed');
+ await Promise.resolve();
+
+ expect(document.querySelector('[data-folder="folder-created"]')).not.toBeNull();
+ expect(errorLog).not.toHaveBeenCalled();
+ expect(race.folderGetCount()).toBe(2);
+});
diff --git a/tests/js/pages/subscriptions-migration-runtime.test.js b/tests/js/pages/subscriptions-migration-runtime.test.js
new file mode 100644
index 0000000000..39b7f4239f
--- /dev/null
+++ b/tests/js/pages/subscriptions-migration-runtime.test.js
@@ -0,0 +1,867 @@
+/**
+ * Runtime contracts for mutating actions in the subscriptions page.
+ * Its existing suite only exercises date formatting, while these handlers
+ * consume migrated research/news APIs.
+ */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const SOURCE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/static/js/pages/subscriptions.js',
+);
+const source = readFileSync(SOURCE_PATH, 'utf8');
+
+function sourceBlock(pattern, name) {
+ const match = source.match(pattern);
+ expect(match, `${name} source block not found`).toBeTruthy();
+ return match[1];
+}
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((fulfill, reject) => {
+ resolvePromise = fulfill;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
+function compileListMutationRuntime(initialSubscriptions = [{
+ id: 'sub-list-ownership',
+ name: 'Owned subscription',
+ is_active: true,
+}]) {
+ const loadSubscriptionsSource = sourceBlock(
+ /(async function loadSubscriptions\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Load folders/,
+ 'loadSubscriptions()',
+ );
+ const toggleSource = sourceBlock(
+ /(async function toggleSubscription\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ View subscription history/,
+ 'toggleSubscription()',
+ );
+ const deleteSource = sourceBlock(
+ /(async function deleteSubscriptionDirect\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ Update statistics/,
+ 'deleteSubscriptionDirect()',
+ );
+ const calls = {
+ renderSubscriptions: vi.fn(),
+ updateStats: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', 'initialSubscriptions', `
+ let subscriptions = initialSubscriptions.map(subscription => ({
+ ...subscription,
+ }));
+ let subscriptionsMutationGeneration = 0;
+ let subscriptionsLoadRequestId = 0;
+ const fetchOptions = { credentials: 'same-origin' };
+ const subscriptionToggleIntents = new Map();
+ const SafeLogger = { log: () => {}, error: () => {} };
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${loadSubscriptionsSource}
+ ${toggleSource}
+ ${deleteSource}
+ return {
+ loadSubscriptions,
+ toggleSubscription,
+ deleteSubscriptionDirect,
+ getSubscriptions: () => subscriptions,
+ };
+ `)(calls, initialSubscriptions);
+ return { calls, runtime };
+}
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ localStorage.clear();
+ delete window.api;
+ delete window.RESEARCH_STATUS;
+});
+
+it('loads the current subscriptions and folder-array response shapes', async () => {
+ const loadSubscriptionsSource = sourceBlock(
+ /(async function loadSubscriptions\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Load folders/,
+ 'loadSubscriptions()',
+ );
+ const loadFoldersSource = sourceBlock(
+ /(async function loadFolders\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Render subscriptions grid/,
+ 'loadFolders()',
+ );
+ const calls = {
+ renderSubscriptions: vi.fn(),
+ updateStats: vi.fn(),
+ renderFolders: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [];
+ let subscriptionsMutationGeneration = 0;
+ let subscriptionsLoadRequestId = 0;
+ let folders = [];
+ let foldersLoadRequestId = 0;
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const renderFolders = () => calls.renderFolders();
+ const showAlert = (...args) => calls.showAlert(...args);
+ ${loadSubscriptionsSource}
+ ${loadFoldersSource}
+ return {
+ loadSubscriptions,
+ loadFolders,
+ getSubscriptions: () => subscriptions,
+ getFolders: () => folders,
+ };
+ `)(calls);
+ const subscriptions = [{ id: 'sub-load', query: 'Migration' }];
+ const folders = [{ id: 'folder-load', name: 'FastAPI' }];
+ const fetchMock = vi.fn((url) => {
+ if (url === '/news/api/subscriptions/current') {
+ return Promise.resolve(new Response(JSON.stringify({
+ subscriptions,
+ }), { status: 200 }));
+ }
+ if (url === '/news/api/subscription/folders') {
+ return Promise.resolve(new Response(JSON.stringify(folders), {
+ status: 200,
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await Promise.all([
+ runtime.loadSubscriptions(),
+ runtime.loadFolders(),
+ ]);
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscriptions/current',
+ { credentials: 'same-origin' },
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscription/folders',
+ { credentials: 'same-origin' },
+ );
+ expect(runtime.getSubscriptions()).toEqual(subscriptions);
+ expect(runtime.getFolders()).toEqual(folders);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+ expect(calls.renderFolders).toHaveBeenCalledOnce();
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('renders the migrated scheduler status envelope', async () => {
+ const schedulerSource = sourceBlock(
+ /(async function checkSchedulerStatus\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Show scheduler information/,
+ 'checkSchedulerStatus()',
+ );
+ // Repository-owned production source only; no user-controlled input.
+ const checkSchedulerStatus = new Function( // eslint-disable-line no-new-func
+ `const fetchOptions = { credentials: 'same-origin' };
+ ${schedulerSource}
+ return checkSchedulerStatus;`,
+ )();
+ document.body.innerHTML = `
+ <span id="status-indicator"></span>
+ <span id="status-text"></span>
+ <span id="scheduler-details"></span>
+ `;
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ scheduler_available: true,
+ is_running: true,
+ active_users: 2,
+ scheduled_jobs: 5,
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await checkSchedulerStatus();
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/scheduler/status',
+ { credentials: 'same-origin' },
+ );
+ expect(document.getElementById('status-indicator').className)
+ .toBe('ldr-status-indicator active');
+ expect(document.getElementById('status-text').textContent).toBe('Active');
+ expect(document.getElementById('scheduler-details').textContent)
+ .toBe('2 active users, 5 scheduled jobs');
+});
+
+it('starts a queued subscription research with the migrated payload and CSRF', async () => {
+ vi.useFakeTimers();
+ const runSource = sourceBlock(
+ /(async function runSubscriptionNow\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ Toggle subscription/,
+ 'runSubscriptionNow()',
+ );
+ const calls = {
+ showAlert: vi.fn(),
+ renderSubscriptions: vi.fn(),
+ loadSubscriptions: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{
+ id: 'sub-1',
+ query: 'FastAPI migration news',
+ is_active: true,
+ }];
+ const fetchOptions = { credentials: 'same-origin' };
+ const runningSubscriptionIds = new Set();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const renderSubscriptions = (...args) => calls.renderSubscriptions(...args);
+ const loadSubscriptions = (...args) => calls.loadSubscriptions(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${runSource}
+ return { runSubscriptionNow, getSubscriptions: () => subscriptions };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-subscriptions') };
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ status: 'queued',
+ research_id: 'research-1<script>',
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await runtime.runSubscriptionNow('sub-1');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/start_research');
+ expect(options.method).toBe('POST');
+ expect(options.credentials).toBe('same-origin');
+ expect(options.headers).toEqual({
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-subscriptions',
+ });
+ expect(JSON.parse(options.body)).toEqual({
+ query: 'FastAPI migration news',
+ mode: 'quick',
+ metadata: {
+ is_news_search: true,
+ search_type: 'news_analysis',
+ display_in: 'news_feed',
+ subscription_id: 'sub-1',
+ triggered_by: 'manual_run',
+ },
+ });
+ expect(calls.showAlert).toHaveBeenLastCalledWith(
+ expect.stringContaining('/progress/research-1script'),
+ 'success',
+ );
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(runtime.getSubscriptions()[0].last_run).toBeTruthy();
+ expect(JSON.parse(localStorage.getItem('active_news_research'))).toEqual(
+ expect.objectContaining({
+ researchId: 'research-1<script>',
+ query: 'FastAPI migration news',
+ }),
+ );
+});
+
+it('updates active state through the migrated PUT contract', async () => {
+ const toggleSource = sourceBlock(
+ /(async function toggleSubscription\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ View subscription history/,
+ 'toggleSubscription()',
+ );
+ const calls = { renderSubscriptions: vi.fn(), updateStats: vi.fn() };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{ id: 'sub-2', is_active: true }];
+ let subscriptionsMutationGeneration = 0;
+ const fetchOptions = { credentials: 'same-origin' };
+ const subscriptionToggleIntents = new Map();
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const showAlert = () => {};
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${toggleSource}
+ return { toggleSubscription, getSubscriptions: () => subscriptions };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-subscriptions') };
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ status: 'success',
+ subscription: { id: 'sub-2', is_active: false },
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await runtime.toggleSubscription('sub-2');
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscriptions/sub-2', {
+ credentials: 'same-origin',
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-subscriptions',
+ },
+ body: JSON.stringify({ is_active: false }),
+ });
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+});
+
+it('coalesces repeated Run clicks until the owned research start settles', async () => {
+ vi.useFakeTimers();
+ const runSource = sourceBlock(
+ /(async function runSubscriptionNow\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ Toggle subscription/,
+ 'runSubscriptionNow()',
+ );
+ const calls = {
+ showAlert: vi.fn(),
+ renderSubscriptions: vi.fn(),
+ loadSubscriptions: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{
+ id: 'sub-run-guard',
+ query: 'One research only',
+ is_active: true,
+ }];
+ const fetchOptions = { credentials: 'same-origin' };
+ const runningSubscriptionIds = new Set();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const renderSubscriptions = (...args) => calls.renderSubscriptions(...args);
+ const loadSubscriptions = (...args) => calls.loadSubscriptions(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${runSource}
+ return { runSubscriptionNow };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-run-guard') };
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ const firstResponse = deferred();
+ const fetchMock = vi.fn(() => firstResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const firstRun = runtime.runSubscriptionNow('sub-run-guard');
+ const duplicateRun = runtime.runSubscriptionNow('sub-run-guard');
+ await duplicateRun;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(calls.showAlert.mock.calls.filter(([, type]) => type === 'info'))
+ .toHaveLength(1);
+
+ firstResponse.resolve(new Response(JSON.stringify({
+ status: 'queued',
+ research_id: 'run-guard-1',
+ }), { status: 200 }));
+ await firstRun;
+
+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({
+ status: 'queued',
+ research_id: 'run-guard-2',
+ }), { status: 200 }));
+ await runtime.runSubscriptionNow('sub-run-guard');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+});
+
+it('shows a FastAPI detail error and releases Run ownership so retry can recover', async () => {
+ vi.useFakeTimers();
+ const runSource = sourceBlock(
+ /(async function runSubscriptionNow\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ Toggle subscription/,
+ 'runSubscriptionNow()',
+ );
+ const calls = {
+ showAlert: vi.fn(),
+ renderSubscriptions: vi.fn(),
+ loadSubscriptions: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runSubscriptionNow = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ const subscriptions = [{
+ id: 'sub-run-retry',
+ query: 'Recover the failed run',
+ is_active: true,
+ }];
+ const fetchOptions = { credentials: 'same-origin' };
+ const runningSubscriptionIds = new Set();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const renderSubscriptions = (...args) => calls.renderSubscriptions(...args);
+ const loadSubscriptions = (...args) => calls.loadSubscriptions(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${runSource}
+ return runSubscriptionNow;
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-run-retry') };
+ window.RESEARCH_STATUS = { QUEUED: 'queued' };
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ detail: 'Research service is temporarily unavailable',
+ }), {
+ status: 503,
+ statusText: 'Service Unavailable',
+ }))
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ status: 'queued',
+ research_id: 'run-recovered',
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await runSubscriptionNow('sub-run-retry');
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(calls.showAlert).toHaveBeenLastCalledWith(
+ 'Research service is temporarily unavailable',
+ 'error',
+ );
+ expect(calls.renderSubscriptions).not.toHaveBeenCalled();
+
+ await runSubscriptionNow('sub-run-retry');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(calls.showAlert).toHaveBeenLastCalledWith(
+ expect.stringContaining('/progress/run-recovered'),
+ 'success',
+ );
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(vi.getTimerCount()).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(2000);
+
+ expect(calls.loadSubscriptions).toHaveBeenCalledOnce();
+});
+
+it('guards rapid toggles, applies the captured intent once, and then unlocks', async () => {
+ const toggleSource = sourceBlock(
+ /(async function toggleSubscription\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ View subscription history/,
+ 'toggleSubscription()',
+ );
+ const calls = {
+ renderSubscriptions: vi.fn(),
+ updateStats: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{ id: 'sub-toggle-guard', is_active: true }];
+ let subscriptionsMutationGeneration = 0;
+ const fetchOptions = { credentials: 'same-origin' };
+ const subscriptionToggleIntents = new Map();
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${toggleSource}
+ return { toggleSubscription, getSubscriptions: () => subscriptions };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-toggle-guard') };
+ const firstResponse = deferred();
+ const fetchMock = vi.fn(() => firstResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const firstToggle = runtime.toggleSubscription('sub-toggle-guard');
+ const duplicateToggle = runtime.toggleSubscription('sub-toggle-guard');
+ await duplicateToggle;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(runtime.getSubscriptions()[0].is_active).toBe(true);
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body))
+ .toEqual({ is_active: false });
+ expect(calls.renderSubscriptions).not.toHaveBeenCalled();
+
+ firstResponse.resolve({ ok: true, status: 200 });
+ await firstToggle;
+
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+
+ fetchMock.mockResolvedValueOnce({ ok: true, status: 200 });
+ await runtime.toggleSubscription('sub-toggle-guard');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(fetchMock.mock.calls[1][1].body))
+ .toEqual({ is_active: true });
+ expect(runtime.getSubscriptions()[0].is_active).toBe(true);
+ expect(calls.renderSubscriptions).toHaveBeenCalledTimes(2);
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('applies a pending toggle intent to the subscription object from a newer list load', async () => {
+ const toggleSource = sourceBlock(
+ /(async function toggleSubscription\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ View subscription history/,
+ 'toggleSubscription()',
+ );
+ const calls = {
+ renderSubscriptions: vi.fn(),
+ updateStats: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{ id: 'sub-toggle-reload', is_active: true }];
+ let subscriptionsMutationGeneration = 0;
+ const fetchOptions = { credentials: 'same-origin' };
+ const subscriptionToggleIntents = new Map();
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${toggleSource}
+ return {
+ toggleSubscription,
+ getSubscriptions: () => subscriptions,
+ replaceSubscriptions: value => { subscriptions = value; },
+ };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-toggle-reload') };
+ const response = deferred();
+ vi.stubGlobal('fetch', vi.fn(() => response.promise));
+ const staleSubscription = runtime.getSubscriptions()[0];
+
+ const toggle = runtime.toggleSubscription('sub-toggle-reload');
+ const refreshedSubscription = {
+ id: 'sub-toggle-reload',
+ is_active: true,
+ marker: 'fresh-list-object',
+ };
+ runtime.replaceSubscriptions([refreshedSubscription]);
+ response.resolve({ ok: true, status: 200 });
+ await toggle;
+
+ expect(staleSubscription.is_active).toBe(true);
+ expect(runtime.getSubscriptions()[0]).toBe(refreshedSubscription);
+ expect(refreshedSubscription.is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('does not let a stale list response overwrite a completed toggle', async () => {
+ const { calls, runtime } = compileListMutationRuntime();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-stale-load') };
+ const staleLoad = deferred();
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/news/api/subscriptions/current') {
+ return staleLoad.promise;
+ }
+ if (
+ url === '/news/api/subscriptions/sub-list-ownership'
+ && options.method === 'PUT'
+ ) {
+ return Promise.resolve({ ok: true, status: 200 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const load = runtime.loadSubscriptions();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+
+ await runtime.toggleSubscription('sub-list-ownership');
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+
+ staleLoad.resolve(new Response(JSON.stringify({
+ subscriptions: [{ id: 'sub-list-ownership', is_active: true }],
+ }), { status: 200 }));
+ await load;
+
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('does not let a stale list body overwrite a completed toggle', async () => {
+ const { calls, runtime } = compileListMutationRuntime();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-stale-body') };
+ const staleBody = deferred();
+ const staleJson = vi.fn(() => staleBody.promise);
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/news/api/subscriptions/current') {
+ return Promise.resolve({ ok: true, json: staleJson });
+ }
+ if (
+ url === '/news/api/subscriptions/sub-list-ownership'
+ && options.method === 'PUT'
+ ) {
+ return Promise.resolve({ ok: true, status: 200 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const load = runtime.loadSubscriptions();
+ await vi.waitFor(() => expect(staleJson).toHaveBeenCalledOnce());
+
+ await runtime.toggleSubscription('sub-list-ownership');
+ staleBody.resolve({
+ subscriptions: [{ id: 'sub-list-ownership', is_active: true }],
+ });
+ await load;
+
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('lets only the newest same-generation list request render', async () => {
+ const { calls, runtime } = compileListMutationRuntime();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-latest-list') };
+ const olderBody = deferred();
+ const olderJson = vi.fn(() => olderBody.promise);
+ const fetchMock = vi.fn()
+ .mockResolvedValueOnce({ ok: true, json: olderJson })
+ .mockResolvedValueOnce(new Response(JSON.stringify({
+ subscriptions: [{
+ id: 'sub-list-ownership',
+ is_active: false,
+ marker: 'newest-list',
+ }],
+ }), { status: 200 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = runtime.loadSubscriptions();
+ await vi.waitFor(() => expect(olderJson).toHaveBeenCalledOnce());
+ await runtime.loadSubscriptions();
+
+ olderBody.resolve({
+ subscriptions: [{
+ id: 'sub-list-ownership',
+ is_active: true,
+ marker: 'older-list',
+ }],
+ });
+ await olderLoad;
+
+ expect(runtime.getSubscriptions()).toEqual([{
+ id: 'sub-list-ownership',
+ is_active: false,
+ marker: 'newest-list',
+ }]);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+ expect(calls.showAlert).not.toHaveBeenCalled();
+});
+
+it('does not let a pre-delete list response resurrect a deleted subscription', async () => {
+ const { calls, runtime } = compileListMutationRuntime();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-delete-owned') };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const staleLoad = deferred();
+ let listCalls = 0;
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/news/api/subscriptions/current') {
+ listCalls += 1;
+ if (listCalls === 1) return staleLoad.promise;
+ return Promise.resolve(new Response(JSON.stringify({
+ subscriptions: [],
+ }), { status: 200 }));
+ }
+ if (
+ url === '/news/api/subscriptions/sub-list-ownership'
+ && options.method === 'DELETE'
+ ) {
+ return Promise.resolve({ ok: true, status: 204 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const olderLoad = runtime.loadSubscriptions();
+ await vi.waitFor(() => expect(fetchMock).toHaveBeenCalledOnce());
+ await runtime.deleteSubscriptionDirect('sub-list-ownership');
+
+ expect(runtime.getSubscriptions()).toEqual([]);
+ staleLoad.resolve(new Response(JSON.stringify({
+ subscriptions: [{ id: 'sub-list-ownership', is_active: true }],
+ }), { status: 200 }));
+ await olderLoad;
+
+ expect(runtime.getSubscriptions()).toEqual([]);
+ expect(calls.renderSubscriptions).toHaveBeenCalledTimes(2);
+ expect(calls.updateStats).toHaveBeenCalledTimes(2);
+ expect(calls.showAlert).toHaveBeenCalledWith(
+ 'Subscription deleted successfully',
+ 'success',
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/news/api/subscriptions/sub-list-ownership',
+ expect.objectContaining({
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': 'csrf-delete-owned' },
+ }),
+ );
+});
+
+it('keeps a deleted subscription absent when a later toggle retires its reload', async () => {
+ const { calls, runtime } = compileListMutationRuntime([
+ { id: 'delete-a', name: 'Delete A', is_active: true },
+ { id: 'toggle-b', name: 'Toggle B', is_active: true },
+ ]);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-delete-toggle') };
+ vi.stubGlobal('confirm', vi.fn(() => true));
+ const deleteReloadBody = deferred();
+ const deleteReloadJson = vi.fn(() => deleteReloadBody.promise);
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (
+ url === '/news/api/subscriptions/delete-a'
+ && options.method === 'DELETE'
+ ) {
+ return Promise.resolve({ ok: true, status: 204 });
+ }
+ if (url === '/news/api/subscriptions/current') {
+ return Promise.resolve({ ok: true, json: deleteReloadJson });
+ }
+ if (
+ url === '/news/api/subscriptions/toggle-b'
+ && options.method === 'PUT'
+ ) {
+ return Promise.resolve({ ok: true, status: 200 });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ const deleting = runtime.deleteSubscriptionDirect('delete-a');
+ await vi.waitFor(() => expect(deleteReloadJson).toHaveBeenCalledOnce());
+ await runtime.toggleSubscription('toggle-b');
+
+ deleteReloadBody.resolve({
+ subscriptions: [
+ { id: 'delete-a', name: 'Delete A', is_active: true },
+ { id: 'toggle-b', name: 'Toggle B', is_active: true },
+ ],
+ });
+ await deleting;
+
+ expect(runtime.getSubscriptions()).toEqual([
+ { id: 'toggle-b', name: 'Toggle B', is_active: false },
+ ]);
+ expect(calls.renderSubscriptions).toHaveBeenCalledTimes(2);
+ expect(calls.updateStats).toHaveBeenCalledTimes(2);
+ expect(calls.showAlert).toHaveBeenCalledWith(
+ 'Subscription deleted successfully',
+ 'success',
+ );
+});
+
+it('surfaces a non-ok toggle and unlocks the subscription for recovery', async () => {
+ const toggleSource = sourceBlock(
+ /(async function toggleSubscription\(subscriptionId\)\s*\{[\s\S]*?\n\})\n\n\/\/ View subscription history/,
+ 'toggleSubscription()',
+ );
+ const calls = {
+ renderSubscriptions: vi.fn(),
+ updateStats: vi.fn(),
+ showAlert: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const runtime = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ let subscriptions = [{ id: 'sub-toggle-retry', is_active: true }];
+ let subscriptionsMutationGeneration = 0;
+ const fetchOptions = { credentials: 'same-origin' };
+ const subscriptionToggleIntents = new Map();
+ const renderSubscriptions = () => calls.renderSubscriptions();
+ const updateStats = () => calls.updateStats();
+ const showAlert = (...args) => calls.showAlert(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${toggleSource}
+ return { toggleSubscription, getSubscriptions: () => subscriptions };
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-toggle-retry') };
+ const failedResponse = deferred();
+ const fetchMock = vi.fn(() => failedResponse.promise);
+ vi.stubGlobal('fetch', fetchMock);
+
+ const failedToggle = runtime.toggleSubscription('sub-toggle-retry');
+ const duplicateToggle = runtime.toggleSubscription('sub-toggle-retry');
+ await duplicateToggle;
+ failedResponse.resolve({
+ ok: false,
+ status: 503,
+ statusText: 'Service Unavailable',
+ });
+ await failedToggle;
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(runtime.getSubscriptions()[0].is_active).toBe(true);
+ expect(calls.renderSubscriptions).not.toHaveBeenCalled();
+ expect(calls.updateStats).not.toHaveBeenCalled();
+ expect(calls.showAlert).toHaveBeenCalledWith(
+ 'Failed to update subscription',
+ 'error',
+ );
+
+ fetchMock.mockResolvedValueOnce({ ok: true, status: 200 });
+ await runtime.toggleSubscription('sub-toggle-retry');
+
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(runtime.getSubscriptions()[0].is_active).toBe(false);
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+ expect(calls.updateStats).toHaveBeenCalledOnce();
+});
+
+it('creates a folder with CSRF and consumes the created folder envelope', async () => {
+ const createSource = sourceBlock(
+ /(async function createNewFolder\(\)\s*\{[\s\S]*?\n\})\n\n\/\/ Utility functions/,
+ 'createNewFolder()',
+ );
+ const calls = {
+ showAlert: vi.fn(),
+ loadFolders: vi.fn().mockResolvedValue(undefined),
+ renderSubscriptions: vi.fn(),
+ };
+ // Repository-owned production source only; no user-controlled input.
+ const createNewFolder = new Function( // eslint-disable-line no-new-func
+ 'calls', `
+ const fetchOptions = { credentials: 'same-origin' };
+ const showAlert = (...args) => calls.showAlert(...args);
+ const loadFolders = (...args) => calls.loadFolders(...args);
+ const renderSubscriptions = (...args) => calls.renderSubscriptions(...args);
+ const getCSRFToken = () => window.api.getCsrfToken();
+ ${createSource}
+ return createNewFolder;
+ `)(calls);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-subscriptions') };
+ vi.stubGlobal('prompt', vi.fn(() => ' Migration Sources '));
+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({
+ id: 'folder-1',
+ name: 'Migration Sources',
+ }), { status: 201 }));
+ vi.stubGlobal('fetch', fetchMock);
+
+ await createNewFolder();
+
+ expect(fetchMock).toHaveBeenCalledWith('/news/api/subscription/folders', {
+ credentials: 'same-origin',
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-subscriptions',
+ },
+ body: JSON.stringify({ name: 'Migration Sources' }),
+ });
+ expect(calls.showAlert).toHaveBeenCalledWith(
+ 'Folder "Migration Sources" created successfully!',
+ 'success',
+ );
+ expect(calls.loadFolders).toHaveBeenCalledOnce();
+ expect(calls.renderSubscriptions).toHaveBeenCalledOnce();
+});
diff --git a/tests/js/pages/unified-search-bootstrap-runtime.test.js b/tests/js/pages/unified-search-bootstrap-runtime.test.js
new file mode 100644
index 0000000000..1d9b0aca68
--- /dev/null
+++ b/tests/js/pages/unified-search-bootstrap-runtime.test.js
@@ -0,0 +1,98 @@
+/** Direct bootstrap coverage for the migrated unified-search page. */
+
+let documentListeners;
+
+function installDom() {
+ document.body.innerHTML = `
+ <input id="ldr-unified-search-input">
+ <section id="ldr-unified-search-results"></section>
+ <section id="ldr-unified-search-empty"></section>
+ <p id="ldr-unified-search-notice"></p>
+ <button id="unified-search-mode-btn"><i></i></button>
+ <span id="unified-search-mode-label"></span>
+ <ul id="unified-search-mode-menu"></ul>
+ `;
+}
+
+beforeEach(() => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ installDom();
+ documentListeners = [];
+ const addDocumentListener = document.addEventListener.bind(document);
+ vi.spyOn(document, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ documentListeners.push([type, listener, options]);
+ addDocumentListener(type, listener, options);
+ },
+ );
+ delete window.__VITEST_TEST__;
+ window.SemanticSearch = {
+ MIN_QUERY_LENGTH: 2,
+ MIN_SIMILARITY: 0.35,
+ buildTieredResults: vi.fn(),
+ flattenTieredResults: vi.fn(),
+ };
+ window.formatting = { similarityBadge: vi.fn(() => '') };
+ vi.stubGlobal('escapeHtml', value => String(value ?? '')
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;'));
+});
+
+afterEach(() => {
+ for (const [type, listener, options] of documentListeners) {
+ document.removeEventListener(type, listener, options);
+ }
+ documentListeners = [];
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.SemanticSearch;
+ delete window.formatting;
+ document.body.replaceChildren();
+});
+
+it('wires the real page controls and renders a debounced text result', async () => {
+ const safeFetchWithAuth = vi.fn().mockResolvedValue({
+ json: vi.fn().mockResolvedValue({
+ success: true,
+ results: [{
+ id: 'bootstrap-result',
+ title: 'Unified migration result',
+ content_preview: 'Found through the wired page input',
+ url: '/results/bootstrap-result',
+ source_type: 'research_report',
+ }],
+ }),
+ });
+ vi.stubGlobal('safeFetchWithAuth', safeFetchWithAuth);
+
+ await import('@js/pages/unified_search.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ expect(document.querySelectorAll('#unified-search-mode-menu [data-mode]'))
+ .toHaveLength(3);
+ expect(document.getElementById('unified-search-mode-label').textContent)
+ .toBe('AI Hybrid');
+ expect(document.getElementById('ldr-unified-search-input').placeholder)
+ .toContain('AI Hybrid');
+
+ document.querySelector('[data-mode="text"]').click();
+ const input = document.getElementById('ldr-unified-search-input');
+ input.value = 'migration coverage';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ await vi.advanceTimersByTimeAsync(300);
+
+ await vi.waitFor(() => expect(safeFetchWithAuth).toHaveBeenCalledOnce());
+ expect(safeFetchWithAuth.mock.calls[0][0])
+ .toBe('/library/search/api/keyword?q=migration+coverage&limit=20');
+ await vi.waitFor(() => {
+ expect(document.getElementById('ldr-unified-search-results').textContent)
+ .toContain('Unified migration result');
+ });
+ expect(document.querySelector('.ldr-unified-result-card').getAttribute('href'))
+ .toBe('/results/bootstrap-result');
+});
diff --git a/tests/js/pages/unified-search.test.js b/tests/js/pages/unified-search.test.js
index 0e9f99c068..8735bcdd33 100644
--- a/tests/js/pages/unified-search.test.js
+++ b/tests/js/pages/unified-search.test.js
@@ -195,6 +195,124 @@ describe('input invalidation', () => {
expect(dom.empty.textContent).toContain('Search everything');
expect(globalThis.safeFetch).toHaveBeenCalledTimes(1);
});
+
+ it('does not let an older rejected request replace newer results', async () => {
+ const dom = makeDom();
+ hook.setDomRefs(dom);
+ hook.setUnifiedSearchMode('text');
+
+ let rejectOld;
+ const oldRequest = new Promise((_resolve, reject) => {
+ rejectOld = reject;
+ });
+ globalThis.safeFetch = vi.fn()
+ .mockImplementationOnce(() => oldRequest)
+ .mockResolvedValueOnce({
+ json: () => Promise.resolve({
+ success: true,
+ results: [{
+ id: 'new',
+ title: 'Current result',
+ content_preview: 'fresh',
+ url: '/notes/new',
+ source_type: 'note',
+ }],
+ }),
+ });
+
+ dom.input.value = 'older query';
+ const olderRun = hook.runUnifiedSearch();
+ await Promise.resolve();
+ dom.input.value = 'newer query';
+ await hook.runUnifiedSearch();
+ expect(dom.results.textContent).toContain('Current result');
+
+ rejectOld(new Error('late network failure'));
+ await olderRun;
+
+ expect(dom.results.textContent).toContain('Current result');
+ expect(dom.empty.textContent).not.toContain("Couldn't search");
+ });
+
+ it('cancels the pending debounce when a mode switch runs immediately', async () => {
+ vi.useFakeTimers();
+ try {
+ const dom = makeDom();
+ hook.setDomRefs(dom);
+ hook.setUnifiedSearchMode('hybrid');
+ hook.setupUnifiedSearchListeners();
+ globalThis.safeFetch = vi.fn().mockResolvedValue({
+ json: () => Promise.resolve({ success: true, results: [] }),
+ });
+
+ dom.input.value = 'mode switch query';
+ dom.input.dispatchEvent(new Event('input'));
+ hook.setUnifiedSearchMode('text');
+ await vi.waitFor(() => expect(globalThis.safeFetch).toHaveBeenCalledOnce());
+
+ await vi.advanceTimersByTimeAsync(500);
+ expect(globalThis.safeFetch).toHaveBeenCalledTimes(1);
+ expect(globalThis.safeFetch.mock.calls[0][0]).toContain('/api/keyword');
+ } finally {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe('failure recovery', () => {
+ it('shows a server-reported mode error instead of a misleading network error', async () => {
+ const dom = makeDom();
+ hook.setDomRefs(dom);
+ hook.setUnifiedSearchMode('text');
+ dom.input.value = 'bad request';
+ globalThis.safeFetch = vi.fn().mockResolvedValue({
+ json: () => Promise.resolve({
+ success: false,
+ error: 'Search filter is invalid',
+ }),
+ });
+
+ await hook.runUnifiedSearch();
+
+ expect(dom.empty.textContent).toContain('Search filter is invalid');
+ expect(dom.empty.textContent).not.toContain('check your connection');
+ expect(dom.empty.querySelector('[data-action="retry-unified-search"]'))
+ .not.toBeNull();
+ });
+
+ it('retries the current query through the registered recovery action', async () => {
+ const dom = makeDom();
+ hook.setDomRefs(dom);
+ hook.setUnifiedSearchMode('text');
+ dom.input.value = 'retry query';
+ globalThis.safeFetch = vi.fn()
+ .mockResolvedValueOnce({
+ json: () => Promise.resolve({ success: false, error: 'Temporary failure' }),
+ })
+ .mockResolvedValueOnce({
+ json: () => Promise.resolve({
+ success: true,
+ results: [{
+ id: 'recovered',
+ title: 'Recovered result',
+ content_preview: 'available again',
+ url: '/notes/recovered',
+ source_type: 'note',
+ }],
+ }),
+ });
+
+ await hook.runUnifiedSearch();
+ expect(dom.empty.querySelector('[data-action="retry-unified-search"]'))
+ .not.toBeNull();
+ hook.UNIFIED_SEARCH_ACTIONS['retry-unified-search']();
+
+ await vi.waitFor(() => {
+ expect(dom.results.textContent).toContain('Recovered result');
+ });
+ expect(globalThis.safeFetch).toHaveBeenCalledTimes(2);
+ });
});
describe('hybrid mode — leg degradation', () => {
diff --git a/tests/js/pages/zotero-runtime.test.js b/tests/js/pages/zotero-runtime.test.js
new file mode 100644
index 0000000000..f88c46c9cd
--- /dev/null
+++ b/tests/js/pages/zotero-runtime.test.js
@@ -0,0 +1,472 @@
+/** Runtime coverage for the Zotero page's FastAPI consumers and polling. */
+
+import { readFileSync } from 'node:fs';
+import { resolve } from 'node:path';
+
+const TEMPLATE_PATH = resolve(
+ __dirname,
+ '../../../src/local_deep_research/web/templates/pages/zotero.html',
+);
+const template = readFileSync(TEMPLATE_PATH, 'utf8');
+const scriptMatch = template.match(
+ /<script>\s*(\(function \(\) \{[\s\S]*?\}\)\(\);)\s*<\/script>/,
+);
+
+function config(overrides = {}) {
+ return {
+ success: true,
+ configured: false,
+ enabled: true,
+ use_local_api: false,
+ library_type: 'user',
+ library_id: '1234',
+ collection_keys: [],
+ has_api_key: true,
+ import_items_without_pdf: false,
+ import_annotations: false,
+ import_tags: [],
+ pdf_storage_mode: 'none',
+ auto_sync_enabled: false,
+ sync_interval_minutes: 360,
+ ...overrides,
+ };
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(settle => {
+ resolvePromise = settle;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+function jsonResponse(payload) {
+ return new Response(JSON.stringify(payload), { status: 200 });
+}
+
+function loadPage(fetchMock) {
+ expect(scriptMatch, 'Zotero inline runtime not found').toBeTruthy();
+ document.head.innerHTML = '<meta name="csrf-token" content="csrf-zotero">';
+ // eslint-disable-next-line no-unsanitized/property -- checked-in template is the browser fixture
+ document.body.innerHTML = template;
+ window.ui = { showMessage: vi.fn() };
+ vi.stubGlobal('fetch', fetchMock);
+ // Repository-owned production source only; no user-controlled input.
+ new Function(scriptMatch[1])(); // eslint-disable-line no-new-func
+}
+
+afterEach(() => {
+ if (vi.isFakeTimers()) {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.ui;
+ document.head.replaceChildren();
+ document.body.replaceChildren();
+});
+
+it('hydrates config then autosaves the full non-secret settings payload', async () => {
+ const currentConfig = config();
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(new Response(JSON.stringify(currentConfig), {
+ status: 200,
+ }));
+ }
+ if (url === '/library/api/zotero/status') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [],
+ progress: null,
+ }), { status: 200 }));
+ }
+ if (
+ url === '/settings/save_all_settings'
+ && options.method === 'POST'
+ ) {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ loadPage(fetchMock);
+ await vi.waitFor(() => {
+ expect(document.getElementById('zotero-config-form').dataset.configLoaded)
+ .toBe('1');
+ });
+
+ expect(document.getElementById('zt-library-id').value).toBe('1234');
+ expect(document.getElementById('zt-api-key').value).toBe('');
+ expect(document.getElementById('zt-api-key').placeholder)
+ .toContain('saved');
+
+ const storage = document.getElementById('zt-pdf-storage');
+ storage.value = 'database';
+ storage.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/save_all_settings',
+ expect.objectContaining({ method: 'POST' }),
+ );
+ });
+ const [, options] = fetchMock.mock.calls.find(
+ ([url]) => url === '/settings/save_all_settings',
+ );
+ expect(options.headers).toEqual({
+ 'Content-Type': 'application/json',
+ 'Accept': 'application/json',
+ 'X-CSRFToken': 'csrf-zotero',
+ });
+ expect(JSON.parse(options.body)).toEqual({
+ 'zotero.enabled': true,
+ 'zotero.use_local_api': false,
+ 'zotero.library_type': 'user',
+ 'zotero.library_id': '1234',
+ 'zotero.collection_keys': '',
+ 'zotero.import_items_without_pdf': false,
+ 'zotero.import_annotations': false,
+ 'zotero.import_tags': '',
+ 'zotero.pdf_storage_mode': 'database',
+ 'zotero.auto_sync_enabled': false,
+ 'zotero.sync_interval_minutes': 360,
+ });
+ expect(JSON.parse(options.body)).not.toHaveProperty('zotero.api_key');
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Zotero settings saved.',
+ 'success',
+ 4000,
+ );
+ });
+});
+
+it('uses CSRF-protected POSTs for connection test and background sync', async () => {
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(new Response(JSON.stringify(config({
+ configured: true,
+ })), { status: 200 }));
+ }
+ if (url === '/library/api/zotero/status') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [],
+ progress: null,
+ }), { status: 200 }));
+ }
+ if (url === '/library/api/zotero/collections') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ collections: [],
+ }), { status: 200 }));
+ }
+ if (url === '/library/api/zotero/groups') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ groups: [],
+ }), { status: 200 }));
+ }
+ if (url === '/library/api/zotero/test' && options.method === 'POST') {
+ return Promise.resolve(new Response(JSON.stringify({
+ success: true,
+ library_version: 42,
+ collection_count: 3,
+ }), { status: 200 }));
+ }
+ if (url === '/library/api/zotero/sync' && options.method === 'POST') {
+ // A rejected envelope restores the button immediately, avoiding a
+ // long-lived polling interval while still exercising the contract.
+ return Promise.resolve(new Response(JSON.stringify({
+ success: false,
+ error: 'Sync already running',
+ }), { status: 409 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ loadPage(fetchMock);
+ await vi.waitFor(() => {
+ expect(document.getElementById('zotero-sync').disabled).toBe(false);
+ });
+
+ document.getElementById('zotero-test').click();
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Connected. Library version 42, 3 collections.',
+ 'success',
+ 4000,
+ );
+ });
+ document.getElementById('zotero-sync').click();
+ await vi.waitFor(() => {
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Sync already running',
+ 'error',
+ 6000,
+ );
+ });
+
+ for (const url of [
+ '/library/api/zotero/test',
+ '/library/api/zotero/sync',
+ ]) {
+ expect(fetchMock).toHaveBeenCalledWith(url, {
+ method: 'POST',
+ headers: {
+ 'Accept': 'application/json',
+ 'X-CSRFToken': 'csrf-zotero',
+ },
+ });
+ }
+ expect(document.getElementById('zotero-test').disabled).toBe(false);
+ expect(document.getElementById('zotero-sync').disabled).toBe(false);
+ expect(document.getElementById('zotero-sync').textContent)
+ .toBe('Sync now');
+});
+
+it('keeps polling through a transient failure and serializes a deferred status request', async () => {
+ vi.useFakeTimers();
+ const completedStatus = deferred();
+ let statusCalls = 0;
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(jsonResponse(config({ configured: true })));
+ }
+ if (url === '/library/api/zotero/status') {
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [],
+ progress: null,
+ }));
+ }
+ if (statusCalls === 2) {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ collection_key: 'owned-sync',
+ last_status: 'syncing',
+ item_count: 3,
+ last_synced_at: null,
+ }],
+ progress: { phase: 'importing', done: 1, total: 3 },
+ }));
+ }
+ if (statusCalls === 3) {
+ return Promise.reject(new Error('transient status failure'));
+ }
+ if (statusCalls === 4) return completedStatus.promise;
+ throw new Error(`Unexpected status request ${statusCalls}`);
+ }
+ if (url === '/library/api/zotero/collections') {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [],
+ }));
+ }
+ if (url === '/library/api/zotero/groups') {
+ return Promise.resolve(jsonResponse({ success: true, groups: [] }));
+ }
+ if (url === '/library/api/zotero/sync' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({ success: true }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ loadPage(fetchMock);
+ await vi.advanceTimersByTimeAsync(0);
+ const syncButton = document.getElementById('zotero-sync');
+ expect(syncButton.disabled).toBe(false);
+
+ syncButton.click();
+ await vi.advanceTimersByTimeAsync(0);
+ expect(syncButton.disabled).toBe(true);
+ expect(syncButton.textContent).toBe('Syncing…');
+
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(statusCalls).toBe(2);
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('syncing');
+
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(statusCalls).toBe(3);
+ expect(syncButton.disabled).toBe(true);
+ expect(window.ui.showMessage).not.toHaveBeenCalledWith(
+ 'Sync finished.',
+ 'success',
+ 4000,
+ );
+
+ await vi.advanceTimersByTimeAsync(1500);
+ expect(statusCalls).toBe(4);
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusCalls).toBe(4);
+ expect(syncButton.disabled).toBe(true);
+
+ completedStatus.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ collection_key: 'owned-sync',
+ last_status: 'completed',
+ item_count: 3,
+ last_synced_at: '2026-09-01T10:00:00Z',
+ }],
+ progress: null,
+ }));
+ await vi.advanceTimersByTimeAsync(0);
+
+ expect(syncButton.disabled).toBe(false);
+ expect(syncButton.textContent).toBe('Sync now');
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('completed');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Sync finished.',
+ 'success',
+ 4000,
+ );
+
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(statusCalls).toBe(4);
+});
+
+it('does not let an older deferred refresh replace a newer status snapshot', async () => {
+ const olderStatus = deferred();
+ let statusCalls = 0;
+ const fetchMock = vi.fn(url => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(jsonResponse(config()));
+ }
+ if (url === '/library/api/zotero/status') {
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [],
+ progress: null,
+ }));
+ }
+ if (statusCalls === 2) return olderStatus.promise;
+ if (statusCalls === 3) {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ collection_key: 'newer-terminal',
+ last_status: 'completed',
+ item_count: 8,
+ last_synced_at: '2026-09-01T10:00:00Z',
+ }],
+ progress: null,
+ }));
+ }
+ throw new Error(`Unexpected status request ${statusCalls}`);
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ loadPage(fetchMock);
+ await vi.waitFor(() => expect(statusCalls).toBe(1));
+
+ const refreshButton = document.getElementById('zotero-refresh');
+ refreshButton.click();
+ refreshButton.click();
+ await vi.waitFor(() => {
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('newer-terminal');
+ });
+
+ olderStatus.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ collection_key: 'older-running',
+ last_status: 'syncing',
+ item_count: 1,
+ last_synced_at: null,
+ }],
+ progress: { phase: 'importing', done: 1, total: 8 },
+ }));
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(statusCalls).toBe(3);
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('newer-terminal');
+ expect(document.getElementById('zotero-status').textContent)
+ .not.toContain('older-running');
+ expect(document.getElementById('zotero-progress').hidden).toBe(true);
+});
+
+it('preserves the last good status when refresh returns an invalid envelope', async () => {
+ let statusCalls = 0;
+ const invalidSuccess = vi.fn(() => false);
+ const invalidEnvelope = {
+ get success() {
+ return invalidSuccess();
+ },
+ error: 'status store temporarily unavailable',
+ };
+ const invalidJson = vi.fn(() => Promise.resolve(invalidEnvelope));
+ const fetchMock = vi.fn(url => {
+ if (url === '/library/api/zotero/config') {
+ return Promise.resolve(jsonResponse(config()));
+ }
+ if (url === '/library/api/zotero/status') {
+ statusCalls += 1;
+ if (statusCalls === 1) {
+ return Promise.resolve(jsonResponse({
+ success: true,
+ collections: [{
+ collection_key: 'last-good-library',
+ last_status: 'syncing',
+ item_count: 4,
+ last_synced_at: null,
+ }],
+ progress: {
+ phase: 'importing',
+ done: 2,
+ total: 4,
+ current: 'paper-2.pdf',
+ },
+ }));
+ }
+ return Promise.resolve({
+ ok: true,
+ status: 200,
+ json: invalidJson,
+ });
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ loadPage(fetchMock);
+ await vi.waitFor(() => {
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('last-good-library');
+ });
+ const progress = document.getElementById('zotero-progress');
+ expect(progress.hidden).toBe(false);
+ expect(progress.textContent).toContain('Importing 2/4');
+ expect(progress.querySelector('.ldr-zotero-progress-fill').style.width)
+ .toBe('50%');
+
+ document.getElementById('zotero-refresh').click();
+ await vi.waitFor(() => {
+ expect(statusCalls).toBe(2);
+ expect(invalidJson).toHaveBeenCalledOnce();
+ expect(invalidSuccess).toHaveBeenCalledOnce();
+ });
+
+ expect(document.getElementById('zotero-status').textContent)
+ .toContain('last-good-library');
+ expect(document.getElementById('zotero-status').textContent)
+ .not.toContain('No syncs yet');
+ expect(progress.hidden).toBe(false);
+ expect(progress.textContent).toContain('Importing 2/4');
+ expect(progress.querySelector('.ldr-zotero-progress-fill').style.width)
+ .toBe('50%');
+});
diff --git a/tests/js/pdf-upload-handler-migration-contract.test.js b/tests/js/pdf-upload-handler-migration-contract.test.js
new file mode 100644
index 0000000000..664562ef70
--- /dev/null
+++ b/tests/js/pdf-upload-handler-migration-contract.test.js
@@ -0,0 +1,341 @@
+/**
+ * Browser contract for the unchanged research-page PDF consumer after the
+ * FastAPI migration. The collection uploader is a separate component; this
+ * handler owns /api/config/limits and /api/upload/pdf.
+ */
+
+function jsonResponse(body, status = 200) {
+ return new Response(JSON.stringify(body), { status });
+}
+
+function deferred() {
+ let resolvePromise;
+ const promise = new Promise(resolve => {
+ resolvePromise = resolve;
+ });
+ return { promise, resolve: resolvePromise };
+}
+
+let bodyListeners = [];
+
+async function loadHandler(fetchMock, { waitForLimits = true } = {}) {
+ vi.resetModules();
+ bodyListeners = [];
+ const addBodyListener = document.body.addEventListener.bind(document.body);
+ vi.spyOn(document.body, 'addEventListener').mockImplementation(
+ (type, listener, options) => {
+ bodyListeners.push([type, listener, options]);
+ addBodyListener(type, listener, options);
+ },
+ );
+ document.body.innerHTML = `
+ <div>
+ <textarea id="query"></textarea>
+ <div class="ldr-search-hints"><div class="ldr-hint-row"></div></div>
+ </div>
+ `;
+ delete window.pdfUploadHandler;
+ vi.stubGlobal('URLS', {
+ API: {
+ CONFIG_LIMITS: '/api/config/limits',
+ UPLOAD_PDF: '/api/upload/pdf',
+ },
+ });
+ vi.stubGlobal('URLValidator', {
+ isSafeUrl: vi.fn(() => true),
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-pdf') };
+ window.formatBytes = bytes => `${bytes} bytes`;
+
+ await import('@js/pdf_upload_handler.js');
+ await vi.waitFor(() => expect(window.pdfUploadHandler).toBeTruthy());
+ if (waitForLimits) {
+ await vi.waitFor(() => {
+ expect(window.pdfUploadHandler.limitsLoaded).toBe(true);
+ });
+ }
+ return window.pdfUploadHandler;
+}
+
+afterEach(() => {
+ if (vi.isFakeTimers()) {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ }
+ for (const [type, listener, options] of bodyListeners) {
+ document.body.removeEventListener(type, listener, options);
+ }
+ bodyListeners = [];
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.pdfUploadHandler;
+ delete window.api;
+ delete window.formatBytes;
+ delete window.__pdfUploadXss;
+ document.body.replaceChildren();
+});
+
+it('hydrates validation limits from the migrated config response', async () => {
+ const fetchMock = vi.fn((url) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({
+ max_file_size: 12_345_678,
+ max_files: 17,
+ allowed_mime_types: ['application/pdf'],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+
+ const handler = await loadHandler(fetchMock);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledWith('/api/config/limits');
+ expect(handler.maxFileSize).toBe(12_345_678);
+ expect(handler.maxFiles).toBe(17);
+});
+
+it('uploads multipart PDFs with CSRF and consumes the extraction envelope', async () => {
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({
+ max_file_size: 50 * 1024 * 1024,
+ max_files: 200,
+ }));
+ }
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ processed_files: 1,
+ total_files: 1,
+ extracted_texts: [{
+ filename: 'migration.pdf',
+ text: 'FastAPI contract text',
+ size: 4,
+ pages: 2,
+ }],
+ combined_text: '--- From migration.pdf ---\nFastAPI contract text',
+ errors: [],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ fetchMock.mockClear();
+ vi.spyOn(handler, 'showProcessing').mockImplementation(() => {});
+ vi.spyOn(handler, 'hideProcessing').mockImplementation(() => {});
+ const success = vi.spyOn(handler, 'showSuccess')
+ .mockImplementation(() => {});
+
+ const pdf = new File(['%PDF'], 'migration.pdf', {
+ type: 'application/pdf',
+ });
+ await handler.uploadAndExtractPDFs([pdf]);
+
+ expect(fetchMock).toHaveBeenCalledOnce();
+ const [url, options] = fetchMock.mock.calls[0];
+ expect(url).toBe('/api/upload/pdf');
+ expect(options.method).toBe('POST');
+ expect(options.headers).toEqual({ 'X-CSRFToken': 'csrf-pdf' });
+ expect(options.body).toBeInstanceOf(FormData);
+ expect(options.body.getAll('files')).toHaveLength(1);
+ expect(options.body.get('files').name).toBe('migration.pdf');
+ expect(document.getElementById('query').value).toContain(
+ 'FastAPI contract text',
+ );
+ expect(handler.getUploadedPDFs()).toEqual([{
+ filename: 'migration.pdf',
+ size: 4,
+ text: 'FastAPI contract text',
+ pages: 2,
+ }]);
+ expect(success).toHaveBeenCalledWith(1, []);
+});
+
+it('accepts a dropped PDF while the migrated limits request is still pending', async () => {
+ const limits = deferred();
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') return limits.promise;
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ processed_files: 1,
+ extracted_texts: [{
+ filename: 'early-drop.pdf',
+ text: 'Dropped before limits hydration',
+ pages: 1,
+ }],
+ combined_text: 'Dropped before limits hydration',
+ errors: [],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock, { waitForLimits: false });
+ const pdf = new File(['%PDF'], 'early-drop.pdf', {
+ type: 'application/pdf',
+ });
+ const drop = new Event('drop', { bubbles: true, cancelable: true });
+ Object.defineProperty(drop, 'dataTransfer', {
+ value: { files: [pdf] },
+ });
+
+ document.getElementById('query').dispatchEvent(drop);
+
+ await vi.waitFor(() => {
+ expect(handler.getUploadedPDFs()).toEqual([{
+ filename: 'early-drop.pdf',
+ size: 4,
+ text: 'Dropped before limits hydration',
+ pages: 1,
+ }]);
+ });
+ expect(drop.defaultPrevented).toBe(true);
+ expect(document.getElementById('query').value)
+ .toContain('Dropped before limits hydration');
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/api/upload/pdf',
+ expect.objectContaining({ method: 'POST' }),
+ );
+
+ limits.resolve(jsonResponse({
+ max_file_size: 12_345,
+ max_files: 7,
+ }));
+ await vi.waitFor(() => expect(handler.limitsLoaded).toBe(true));
+ expect(handler.maxFiles).toBe(7);
+});
+
+it('rejects invalid count and size selections before starting an upload', async () => {
+ const fetchMock = vi.fn((url) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({
+ max_file_size: 4,
+ max_files: 1,
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ vi.useFakeTimers();
+ fetchMock.mockClear();
+ const upload = vi.spyOn(handler, 'uploadAndExtractPDFs');
+
+ await handler.handleFiles([
+ new File(['plain'], 'notes.txt', { type: 'text/plain' }),
+ ]);
+ expect(document.getElementById('pdf-upload-status').textContent)
+ .toContain('Please select PDF files only');
+
+ await handler.handleFiles([
+ new File(['a'], 'one.pdf', { type: 'application/pdf' }),
+ new File(['b'], 'two.pdf', { type: 'application/pdf' }),
+ ]);
+ expect(document.getElementById('pdf-upload-status').textContent)
+ .toContain('Maximum 1 PDF files allowed at once');
+
+ await handler.handleFiles([
+ new File(['12345'], 'large.pdf', { type: 'application/pdf' }),
+ ]);
+ const status = document.getElementById('pdf-upload-status');
+ expect(status.textContent).toContain('smaller than 4 bytes');
+ expect(status.style.display).toBe('block');
+ expect(upload).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(handler.statusTimers).toHaveLength(1);
+
+ await vi.advanceTimersByTimeAsync(5000);
+ expect(status.style.display).toBe('none');
+});
+
+it('keeps terminal upload feedback visible and escapes an API error message', async () => {
+ const hostileMessage = '<img src=x onerror="window.__pdfUploadXss=true">';
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({
+ max_file_size: 100,
+ max_files: 2,
+ }));
+ }
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ status: 'error',
+ message: hostileMessage,
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ vi.useFakeTimers();
+ delete window.__pdfUploadXss;
+
+ await handler.uploadAndExtractPDFs([
+ new File(['%PDF'], 'rejected.pdf', { type: 'application/pdf' }),
+ ]);
+
+ const status = document.getElementById('pdf-upload-status');
+ expect(status.style.display).toBe('block');
+ expect(status.textContent).toContain(hostileMessage);
+ expect(status.querySelector('img')).toBeNull();
+ expect(window.__pdfUploadXss).toBeUndefined();
+ expect(status.querySelector('.fa-spinner')).toBeNull();
+ expect(status.querySelector('.fa-exclamation-triangle')).not.toBeNull();
+
+ await vi.advanceTimersByTimeAsync(4999);
+ expect(status.style.display).toBe('block');
+ await vi.advanceTimersByTimeAsync(1);
+ expect(status.style.display).toBe('none');
+});
+
+it('keeps successful upload feedback visible while updating existing query text', async () => {
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (url === '/api/config/limits') {
+ return Promise.resolve(jsonResponse({
+ max_file_size: 100,
+ max_files: 2,
+ }));
+ }
+ if (url === '/api/upload/pdf' && options.method === 'POST') {
+ return Promise.resolve(jsonResponse({
+ status: 'success',
+ processed_files: 2,
+ extracted_texts: [
+ { text: 'First paper', pages: 2 },
+ { text: 'Second paper', pages: 3 },
+ ],
+ combined_text: 'First paper\nSecond paper',
+ errors: ['one metadata warning'],
+ }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ const handler = await loadHandler(fetchMock);
+ vi.useFakeTimers();
+ const query = document.getElementById('query');
+ query.value = 'Compare these sources';
+ const inputListener = vi.fn();
+ query.addEventListener('input', inputListener);
+
+ await handler.uploadAndExtractPDFs([
+ new File(['a'], 'one.pdf', { type: 'application/pdf' }),
+ new File(['b'], 'two.pdf', { type: 'application/pdf' }),
+ ]);
+
+ const status = document.getElementById('pdf-upload-status');
+ expect(status.style.display).toBe('block');
+ expect(status.textContent).toContain('Successfully processed 2 PDFs');
+ expect(status.textContent).toContain('one metadata warning');
+ expect(query.value).toBe(
+ 'Compare these sources\n\n--- PDF Content ---\n' +
+ 'First paper\nSecond paper',
+ );
+ expect(query.placeholder).toContain('2 PDFs loaded, 5 pages total');
+ expect(inputListener).toHaveBeenCalledOnce();
+ expect(query.selectionStart).toBe(query.value.length);
+ expect(handler.getUploadedPDFs()).toHaveLength(2);
+
+ handler.clearUploadedPDFs();
+ expect(handler.getUploadedPDFs()).toEqual([]);
+ expect(query.placeholder).toContain('drop a PDF paper here');
+});
diff --git a/tests/js/research-form-migration-contract.test.js b/tests/js/research-form-migration-contract.test.js
new file mode 100644
index 0000000000..7cb60aedfc
--- /dev/null
+++ b/tests/js/research-form-migration-contract.test.js
@@ -0,0 +1,226 @@
+/**
+ * Browser contract for the settings APIs and socket event consumed by
+ * research_form.js after the FastAPI migration.
+ */
+
+import '@js/config/urls.js';
+
+const flushPromises = async (turns = 8) => {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+};
+
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return { promise, resolve: resolvePromise, reject: rejectPromise };
+}
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ vi.useRealTimers();
+ delete window.socket;
+ delete window.api;
+ delete window.refetchSettingsAndUpdateWarnings;
+ delete window.displayWarnings;
+ delete window.clearAllWarnings;
+ delete window.checkAndDisplayWarnings;
+ delete window.saveProviderSetting;
+ document.body.replaceChildren();
+});
+
+it('loads, saves, and refreshes settings through the migrated contracts', async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ document.body.innerHTML = `
+ <form id="research-form">
+ <input id="iterations" value="1">
+ <input id="questions_per_iteration" value="1">
+ <select id="model_provider"><option value="openai">OpenAI</option></select>
+ <select id="search_engine"><option value="searxng">SearXNG</option></select>
+ <select id="strategy"><option value="source-based">Source based</option></select>
+ </form>
+ <div id="research-alert"></div>
+ `;
+
+ const socketHandlers = {};
+ const rawSocket = {
+ on: vi.fn((event, callback) => {
+ socketHandlers[event] = callback;
+ }),
+ };
+ window.socket = {
+ getSocketInstance: vi.fn(() => null),
+ init: vi.fn(() => rawSocket),
+ };
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-migration') };
+ const providerSaveResult = { saved: true };
+ const originalSaveProviderSetting = vi.fn(() => providerSaveResult);
+ window.saveProviderSetting = originalSaveProviderSetting;
+ vi.stubGlobal('URLS', window.URLS);
+
+ const fetchMock = vi.fn((input, options = {}) => {
+ const url = String(input);
+ if (url === '/settings/api') {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ settings: {
+ 'search.iterations': { value: 4 },
+ 'search.questions_per_iteration': { value: 2 },
+ },
+ }), { status: 200 }));
+ }
+ if (url === '/settings/api/warnings') {
+ return Promise.resolve(new Response(JSON.stringify({
+ warnings: [],
+ }), { status: 200 }));
+ }
+ if (
+ url === '/settings/save_all_settings'
+ && options.method === 'POST'
+ ) {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ await import('@js/research_form.js');
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+ await flushPromises();
+
+ expect(document.getElementById('iterations').value).toBe('4');
+ expect(document.getElementById('questions_per_iteration').value).toBe('2');
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api');
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/warnings');
+ expect(window.socket.init).toHaveBeenCalledOnce();
+ expect(rawSocket.on).toHaveBeenCalledWith(
+ 'settings_changed',
+ expect.any(Function),
+ );
+ expect(window.saveProviderSetting).not.toBe(originalSaveProviderSetting);
+
+ document.getElementById('research-form').dispatchEvent(
+ new Event('submit', { bubbles: true, cancelable: true }),
+ );
+ await flushPromises();
+
+ const saveCall = fetchMock.mock.calls.find(
+ ([url]) => String(url) === '/settings/save_all_settings',
+ );
+ expect(saveCall).toBeDefined();
+ expect(saveCall[1]).toEqual({
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-migration',
+ },
+ body: JSON.stringify({
+ 'search.iterations': 4,
+ 'search.questions_per_iteration': 2,
+ }),
+ });
+
+ vi.advanceTimersByTime(100);
+ await flushPromises();
+ const warningsBeforeEvent = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api/warnings',
+ ).length;
+
+ socketHandlers.settings_changed({
+ settings: { 'search.iterations': { value: 5 } },
+ });
+ vi.advanceTimersByTime(100);
+ await flushPromises();
+
+ const warningsAfterEvent = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api/warnings',
+ ).length;
+ expect(warningsAfterEvent).toBe(warningsBeforeEvent + 1);
+
+ const settingsBeforeListeners = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api',
+ ).length;
+ const warningsBeforeListeners = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api/warnings',
+ ).length;
+
+ expect(window.saveProviderSetting('openrouter')).toBe(providerSaveResult);
+ expect(originalSaveProviderSetting).toHaveBeenCalledWith('openrouter');
+ await vi.advanceTimersByTimeAsync(300);
+ await flushPromises();
+
+ document.getElementById('model_provider').dispatchEvent(new Event('change'));
+ await vi.advanceTimersByTimeAsync(600);
+ await flushPromises();
+
+ document.getElementById('search_engine').dispatchEvent(new Event('change'));
+ document.getElementById('strategy').dispatchEvent(new Event('change'));
+ await vi.advanceTimersByTimeAsync(100);
+ await flushPromises();
+
+ const settingsAfterListeners = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api',
+ ).length;
+ const warningsAfterListeners = fetchMock.mock.calls.filter(
+ ([url]) => String(url) === '/settings/api/warnings',
+ ).length;
+ expect(settingsAfterListeners).toBe(settingsBeforeListeners + 2);
+ expect(warningsAfterListeners).toBe(warningsBeforeListeners + 4);
+
+ const olderWarnings = deferred();
+ const newerWarnings = deferred();
+ fetchMock.mockImplementationOnce(() => olderWarnings.promise);
+ fetchMock.mockImplementationOnce(() => newerWarnings.promise);
+ const olderWarningRequest = window.checkAndDisplayWarnings();
+ const newerWarningRequest = window.checkAndDisplayWarnings();
+ newerWarnings.resolve(new Response(JSON.stringify({
+ warnings: [{
+ type: 'configuration',
+ title: 'Current warning',
+ message: 'Keep this warning visible',
+ }],
+ }), { status: 200 }));
+ await newerWarningRequest;
+ olderWarnings.resolve(new Response(JSON.stringify({
+ warnings: [{
+ type: 'configuration',
+ title: 'Stale warning',
+ message: 'Do not render this warning',
+ }],
+ }), { status: 200 }));
+ await olderWarningRequest;
+
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Keep this warning visible');
+ expect(document.getElementById('research-alert').textContent)
+ .not.toContain('Do not render this warning');
+
+ const staleFailure = deferred();
+ const finalWarnings = deferred();
+ fetchMock.mockImplementationOnce(() => staleFailure.promise);
+ fetchMock.mockImplementationOnce(() => finalWarnings.promise);
+ const staleFailureRequest = window.checkAndDisplayWarnings();
+ const finalWarningRequest = window.checkAndDisplayWarnings();
+ finalWarnings.resolve(new Response(JSON.stringify({
+ warnings: [{
+ type: 'configuration',
+ title: 'Final warning',
+ message: 'Still visible after stale failure',
+ }],
+ }), { status: 200 }));
+ await finalWarningRequest;
+ staleFailure.reject(new Error('stale warning request failed'));
+ await staleFailureRequest;
+
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Still visible after stale failure');
+});
diff --git a/tests/js/research-form-warning-coverage.test.js b/tests/js/research-form-warning-coverage.test.js
new file mode 100644
index 0000000000..93a12fdfeb
--- /dev/null
+++ b/tests/js/research-form-warning-coverage.test.js
@@ -0,0 +1,240 @@
+/** Direct-import coverage for research_form.js warning rendering and refresh recovery. */
+
+import '@js/config/urls.js';
+import '@js/security/xss-protection.js';
+
+async function flushPromises(turns = 8) {
+ for (let turn = 0; turn < turns; turn += 1) {
+ await Promise.resolve();
+ }
+}
+
+async function loadWarningRuntime() {
+ vi.resetModules();
+ vi.stubGlobal('URLS', window.URLS);
+ await import('@js/research_form.js');
+}
+
+beforeEach(() => {
+ document.body.innerHTML = '<div id="research-alert"></div>';
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.refetchSettingsAndUpdateWarnings;
+ delete window.displayWarnings;
+ delete window.clearAllWarnings;
+ delete window.checkAndDisplayWarnings;
+ delete window.dismissWarning;
+ document.body.replaceChildren();
+});
+
+it('renders only safe warning actions, escapes fields, and clears the surface', async () => {
+ await loadWarningRuntime();
+ const hostile = '<img src=x onerror="window.__warningXss=true">';
+
+ window.displayWarnings([
+ {
+ type: 'searxng_recommendation',
+ icon: hostile,
+ title: `Use ${hostile}`,
+ message: `Configure ${hostile}`,
+ actionUrl: '/settings/?tab=search&engine=<local>',
+ actionLabel: `Open ${hostile}`,
+ dismissKey: 'app.warnings.dismiss_search_hint',
+ },
+ {
+ type: 'configuration',
+ icon: '!',
+ title: 'External action rejected',
+ message: 'Keep navigation inside the application',
+ actionUrl: '//attacker.example/leave',
+ actionLabel: 'Leave',
+ dismissKey: null,
+ },
+ ]);
+
+ const alert = document.getElementById('research-alert');
+ const banners = alert.querySelectorAll('.warning-banner');
+ expect(banners).toHaveLength(2);
+ expect(banners[0].classList.contains('ldr-alert-info')).toBe(true);
+ expect(banners[1].classList.contains('ldr-alert-warning')).toBe(true);
+ expect(alert.querySelector('img')).toBeNull();
+ expect(window.__warningXss).toBeUndefined();
+
+ const actions = alert.querySelectorAll('.ldr-alert-action');
+ expect(actions).toHaveLength(1);
+ expect(actions[0].getAttribute('href'))
+ .toBe('/settings/?tab=search&engine=<local>');
+ expect(actions[0].textContent).toContain(`Open ${hostile}`);
+
+ const dismissButtons = alert.querySelectorAll('button');
+ expect(dismissButtons).toHaveLength(1);
+ expect(dismissButtons[0].getAttribute('onclick')).toBeNull();
+ expect(dismissButtons[0].dataset.dismissKey)
+ .toBe('app.warnings.dismiss_search_hint');
+ expect(alert.style.display).toBe('block');
+
+ window.clearAllWarnings();
+
+ expect(alert.style.display).toBe('none');
+ expect(alert.childElementCount).toBe(0);
+});
+
+it('dismisses through the migrated settings contract and refreshes warnings', async () => {
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-warning-3299') };
+ const fetchMock = vi.fn((url, options = {}) => {
+ if (
+ url === '/settings/save_all_settings'
+ && options.method === 'POST'
+ ) {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ }), { status: 200 }));
+ }
+ if (url === '/settings/api/warnings') {
+ return Promise.resolve(new Response(JSON.stringify({
+ warnings: [],
+ }), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+ await loadWarningRuntime();
+ window.displayWarnings([{
+ type: 'configuration',
+ icon: '!',
+ title: 'Dismiss me',
+ message: 'Persist this choice',
+ dismissKey: 'app.warnings.dismiss_research_hint',
+ }]);
+
+ document.querySelector('.ldr-warning-dismiss').click();
+
+ await vi.waitFor(() => {
+ expect(fetchMock).toHaveBeenCalledWith('/settings/api/warnings');
+ });
+ expect(fetchMock).toHaveBeenCalledWith(
+ '/settings/save_all_settings',
+ {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-warning-3299',
+ },
+ body: JSON.stringify({
+ 'app.warnings.dismiss_research_hint': true,
+ }),
+ },
+ );
+ expect(document.getElementById('research-alert').style.display)
+ .toBe('none');
+});
+
+it('keeps the warning and skips refresh when dismissal is rejected', async () => {
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-warning-3299') };
+ const fetchMock = vi.fn(() => Promise.resolve(new Response(JSON.stringify({
+ status: 'error',
+ detail: 'Dismissal was rejected',
+ }), { status: 409 })));
+ vi.stubGlobal('fetch', fetchMock);
+ await loadWarningRuntime();
+ window.displayWarnings([{
+ type: 'configuration',
+ icon: '!',
+ title: 'Still relevant',
+ message: 'Do not hide this warning',
+ dismissKey: 'app.warnings.dismiss_research_hint',
+ }]);
+
+ const logger = vi.spyOn(SafeLogger, 'error');
+ document.querySelector('.ldr-warning-dismiss').click();
+
+ await vi.waitFor(() => {
+ expect(logger).toHaveBeenCalledWith(
+ 'Failed to dismiss warning:',
+ expect.objectContaining({ message: 'Dismissal was rejected' }),
+ );
+ });
+ expect(fetchMock).toHaveBeenCalledOnce();
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Still relevant');
+});
+
+it('rechecks warnings after both successful and failed settings refreshes', async () => {
+ vi.useFakeTimers();
+ await loadWarningRuntime();
+ let settingsCalls = 0;
+ let warningCalls = 0;
+ const fetchMock = vi.fn(url => {
+ if (url === '/settings/api') {
+ settingsCalls += 1;
+ if (settingsCalls === 1) {
+ return Promise.resolve(new Response(JSON.stringify({
+ status: 'success',
+ settings: {
+ 'search.iterations': { value: 3 },
+ },
+ }), { status: 200 }));
+ }
+ return Promise.reject(new Error('settings temporarily offline'));
+ }
+ if (url === '/settings/api/warnings') {
+ warningCalls += 1;
+ return Promise.resolve(new Response(JSON.stringify(
+ warningCalls === 1
+ ? {
+ warnings: [{
+ type: 'configuration',
+ icon: '!',
+ title: 'Current warning',
+ message: 'Rendered after settings refresh',
+ }],
+ }
+ : {},
+ ), { status: 200 }));
+ }
+ throw new Error(`Unexpected request: ${url}`);
+ });
+ vi.stubGlobal('fetch', fetchMock);
+
+ window.refetchSettingsAndUpdateWarnings();
+ await flushPromises();
+ expect(settingsCalls).toBe(1);
+ expect(vi.getTimerCount()).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(100);
+ await flushPromises();
+ expect(warningCalls).toBe(1);
+ expect(document.getElementById('research-alert').textContent)
+ .toContain('Rendered after settings refresh');
+
+ window.refetchSettingsAndUpdateWarnings();
+ await flushPromises();
+ expect(settingsCalls).toBe(2);
+ expect(vi.getTimerCount()).toBe(1);
+
+ await vi.advanceTimersByTimeAsync(100);
+ await flushPromises();
+ expect(warningCalls).toBe(2);
+ expect(document.getElementById('research-alert').style.display)
+ .toBe('none');
+
+ window.displayWarnings([{
+ type: 'configuration',
+ icon: '!',
+ title: 'Temporary warning',
+ message: 'Must clear on a current request failure',
+ }]);
+ fetchMock.mockResolvedValueOnce(new Response('', { status: 503 }));
+
+ await window.checkAndDisplayWarnings();
+
+ expect(document.getElementById('research-alert').style.display)
+ .toBe('none');
+ expect(document.getElementById('research-alert').textContent).toBe('');
+});
diff --git a/tests/js/security/safe-fetch.test.js b/tests/js/security/safe-fetch.test.js
index 5b424cfa58..ea4e9637f5 100644
--- a/tests/js/security/safe-fetch.test.js
+++ b/tests/js/security/safe-fetch.test.js
@@ -149,3 +149,119 @@ describe('safeFetchWithAuth', () => {
).rejects.toThrow('Blocked unsafe URL');
});
});
+
+describe('safeFetchJson', () => {
+ const originalFetch = globalThis.fetch;
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ vi.useRealTimers();
+ });
+
+ it('returns a successful JSON envelope and preserves request options', async () => {
+ const options = {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ query: 'migration coverage' }),
+ };
+ globalThis.fetch = vi.fn().mockResolvedValue(new Response(
+ JSON.stringify({ status: 'success', research_id: 'safe-json-3299' }),
+ {
+ status: 201,
+ headers: { 'Content-Type': 'application/json' },
+ },
+ ));
+
+ await expect(window.safeFetchJson('/api/start', options)).resolves.toEqual({
+ status: 'success',
+ research_id: 'safe-json-3299',
+ });
+ expect(globalThis.fetch).toHaveBeenCalledWith('/api/start', options);
+ });
+
+ it('throws structured metadata for a FastAPI JSON error and numeric retry delay', async () => {
+ const body = {
+ detail: 'Rate limit reached; retry this research later',
+ error_code: 'rate_limited',
+ };
+ globalThis.fetch = vi.fn().mockResolvedValue(new Response(
+ JSON.stringify(body),
+ {
+ status: 429,
+ statusText: 'Too Many Requests',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Retry-After': '30',
+ },
+ },
+ ));
+
+ let error;
+ try {
+ await window.safeFetchJson('/api/research/rate-limited');
+ } catch (caught) {
+ error = caught;
+ }
+
+ expect(error).toBeInstanceOf(window.HTTPError);
+ expect(error).toMatchObject({
+ name: 'HTTPError',
+ message: body.detail,
+ status: 429,
+ statusText: 'Too Many Requests',
+ retryAfter: 30,
+ body,
+ url: '/api/research/rate-limited',
+ });
+ });
+
+ it('parses an HTTP-date retry delay while ignoring a non-JSON error page', async () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-09-01T12:00:00Z'));
+ globalThis.fetch = vi.fn().mockResolvedValue(new Response(
+ '<h1>Temporarily unavailable</h1>',
+ {
+ status: 503,
+ statusText: 'Service Unavailable',
+ headers: {
+ 'Content-Type': 'text/html',
+ 'Retry-After': 'Tue, 01 Sep 2026 12:00:45 GMT',
+ },
+ },
+ ));
+
+ await expect(window.safeFetchJson('/api/report/research-1'))
+ .rejects.toMatchObject({
+ message: 'Service Unavailable',
+ status: 503,
+ retryAfter: 45,
+ body: null,
+ });
+ });
+
+ it('contains malformed JSON errors and rejects an invalid retry header', async () => {
+ const response = {
+ ok: false,
+ status: 502,
+ statusText: '',
+ headers: {
+ get: vi.fn(name => (
+ name.toLowerCase() === 'content-type'
+ ? 'application/json'
+ : 'not-a-delay'
+ )),
+ },
+ json: vi.fn().mockRejectedValue(new SyntaxError('invalid JSON')),
+ };
+ globalThis.fetch = vi.fn().mockResolvedValue(response);
+
+ await expect(window.safeFetchJson('/api/report/research-2'))
+ .rejects.toMatchObject({
+ message: 'HTTP 502',
+ status: 502,
+ retryAfter: null,
+ body: null,
+ });
+ expect(response.json).toHaveBeenCalledOnce();
+ });
+});
diff --git a/tests/js/security/safe-logger.test.js b/tests/js/security/safe-logger.test.js
index 79c27c95cf..43b23ebff0 100644
--- a/tests/js/security/safe-logger.test.js
+++ b/tests/js/security/safe-logger.test.js
@@ -16,12 +16,63 @@ describe('SafeLogger', () => {
});
describe('environment detection', () => {
+ const originalLocation = window.location;
+
+ function setLocation({ hostname, protocol }) {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: { hostname, protocol },
+ });
+ SL.resetProductionMode();
+ }
+
+ afterEach(() => {
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: originalLocation,
+ });
+ vi.restoreAllMocks();
+ });
+
it('detects localhost as development', () => {
// happy-dom defaults to localhost
SL.resetProductionMode();
expect(SL.isProduction()).toBe(false);
});
+ it.each([
+ ['research.example.com', 'https:'],
+ ['staging.example.com', 'https:'],
+ ['localhost.example.com', 'https:'],
+ ])('defaults %s to production and redacts dynamic data', (
+ hostname,
+ protocol,
+ ) => {
+ setLocation({ hostname, protocol });
+ const log = vi.spyOn(console, 'log').mockImplementation(() => {});
+
+ expect(SL.isProduction()).toBe(true);
+ SL.log('Research query:', 'private migration details');
+
+ expect(log).toHaveBeenCalledWith(
+ 'Research query:',
+ '[redacted]',
+ );
+ });
+
+ it.each([
+ ['127.0.0.1', 'http:'],
+ ['research-box.local', 'https:'],
+ ['', 'file:'],
+ ])('recognizes the explicit local context %s (%s)', (
+ hostname,
+ protocol,
+ ) => {
+ setLocation({ hostname, protocol });
+
+ expect(SL.isProduction()).toBe(false);
+ });
+
it('can be forced to production mode', () => {
SL.setProductionMode(true);
expect(SL.isProduction()).toBe(true);
diff --git a/tests/js/security/url-validator.test.js b/tests/js/security/url-validator.test.js
index e088d91db7..56033a1b03 100644
--- a/tests/js/security/url-validator.test.js
+++ b/tests/js/security/url-validator.test.js
@@ -87,23 +87,97 @@ describe('URLValidator', () => {
});
describe('safeAssign', () => {
+ it.each([
+ ['empty string', ''],
+ ['whitespace-only string', ' '],
+ ['null', null],
+ ['number', 3299],
+ ])('blocks a %s URL value', (_case, value) => {
+ const el = {};
+ expect(URLValidator.safeAssign(el, 'href', value)).toBe(false);
+ expect(el.href).toBeUndefined();
+ });
+
it('allows internal paths starting with /', () => {
const el = {};
expect(URLValidator.safeAssign(el, 'href', '/settings')).toBe(true);
expect(el.href).toBe('/settings');
});
+ it.each([
+ ['protocol-relative URL', '//evil.example/path'],
+ ['triple-slash URL', '///evil.example/path'],
+ ['backslash-normalized URL', '/\\evil.example/path'],
+ ['backslash-and-slash URL', '/\\/evil.example/path'],
+ ['tab-normalized URL', `/${String.fromCharCode(9)}/evil.example/path`],
+ ['newline-normalized URL', `/${String.fromCharCode(10)}/evil.example/path`],
+ ['carriage-return-normalized URL', `/${String.fromCharCode(13)}/evil.example/path`],
+ ['whitespace-prefixed protocol-relative URL', ` ${String.fromCharCode(9)}//evil.example/path`],
+ ['NUL-prefixed protocol-relative URL', `${String.fromCharCode(0)}//evil.example/path`],
+ ['SOH-prefixed protocol-relative URL', `${String.fromCharCode(1)}//evil.example/path`],
+ ['unit-separator-prefixed protocol-relative URL', `${String.fromCharCode(31)}//evil.example/path`],
+ ['control-obscured HTTP scheme', `h${String.fromCharCode(9)}ttp://evil.example/path`],
+ ])('blocks an ambiguous internal-looking %s', (_case, url) => {
+ const el = {};
+ expect(URLValidator.safeAssign(el, 'href', url)).toBe(false);
+ expect(el.href).toBeUndefined();
+ });
+
it('allows fragment URLs', () => {
const el = {};
expect(URLValidator.safeAssign(el, 'href', '#top')).toBe(true);
expect(el.href).toBe('#top');
});
- it('allows blob URLs for downloads', () => {
+ it('honors an explicit fragment ban', () => {
const el = {};
+ expect(URLValidator.safeAssign(
+ el,
+ 'href',
+ '#top',
+ { allowFragments: false },
+ )).toBe(false);
+ expect(el.href).toBeUndefined();
+ });
+
+ it('allows blob URLs for downloads', () => {
+ const el = document.createElement('a');
const blobUrl = 'blob:http://localhost/abc-123';
expect(URLValidator.safeAssign(el, 'href', blobUrl)).toBe(true);
- expect(el.href).toBe(blobUrl);
+ expect(el.getAttribute('href')).toBe(blobUrl);
+ });
+
+ it('blocks blob URLs as page-navigation destinations', () => {
+ const locationLike = {};
+ const blobUrl = 'blob:http://localhost/attacker-controlled';
+ expect(URLValidator.safeAssign(locationLike, 'href', blobUrl)).toBe(false);
+ expect(locationLike.href).toBeUndefined();
+ });
+
+ it('allows raster data URLs only on image rendering targets', () => {
+ const dataUrl = 'data:image/png;base64,aGVsbG8=';
+ const image = document.createElement('img');
+ const favicon = document.createElement('link');
+ favicon.rel = 'shortcut icon';
+
+ expect(URLValidator.safeAssign(image, 'src', dataUrl)).toBe(true);
+ expect(image.getAttribute('src')).toBe(dataUrl);
+ expect(URLValidator.safeAssign(favicon, 'href', dataUrl)).toBe(true);
+ expect(favicon.getAttribute('href')).toBe(dataUrl);
+ });
+
+ it.each([
+ ['active HTML navigation', document.createElement('a'), 'href', 'data:text/html,<script>alert(1)</script>'],
+ ['raster navigation', document.createElement('a'), 'href', 'data:image/png;base64,aGVsbG8='],
+ ['SVG data image outside the raster allowlist', document.createElement('img'), 'src', 'data:image/svg+xml,<svg onload="alert(1)"></svg>'],
+ ])('blocks %s through the data URL exception', (
+ _case,
+ element,
+ property,
+ dataUrl,
+ ) => {
+ expect(URLValidator.safeAssign(element, property, dataUrl)).toBe(false);
+ expect(element.getAttribute(property)).toBeNull();
});
it('blocks unsafe external URLs', () => {
diff --git a/tests/js/security/xss-protection-dompurify-runtime.test.js b/tests/js/security/xss-protection-dompurify-runtime.test.js
new file mode 100644
index 0000000000..4937950179
--- /dev/null
+++ b/tests/js/security/xss-protection-dompurify-runtime.test.js
@@ -0,0 +1,186 @@
+/**
+ * Runtime contracts for the DOMPurify-backed XSS helpers.
+ *
+ * The general unit suite deliberately exercises the no-library fallbacks.
+ * Production loads DOMPurify through app.js before this classic script, so
+ * these cases mirror that load order and pin the sanitizer boundary, config,
+ * and hook wiring. DOMPurify's DOM traversal is not supported by happy-dom
+ * (its cached Node.nodeName getter returns an empty name; see happy-dom #2182),
+ * so a strict boundary spy drives production helpers below. The real
+ * DOMPurify policy is asserted separately through isValidAttribute(), which
+ * does not depend on the incompatible traversal path.
+ */
+
+import createDOMPurify from 'dompurify';
+import '@js/utils/alert-helpers.js';
+
+let realDOMPurify;
+let purifierBoundary;
+let afterSanitizeAttributes;
+
+beforeAll(async () => {
+ realDOMPurify = createDOMPurify(window);
+ purifierBoundary = {
+ addHook: vi.fn((name, callback) => {
+ if (name === 'afterSanitizeAttributes') {
+ afterSanitizeAttributes = callback;
+ }
+ }),
+ sanitize: vi.fn(),
+ };
+ globalThis.DOMPurify = purifierBoundary;
+
+ vi.resetModules();
+ await import('@js/security/xss-protection.js');
+});
+
+afterAll(() => {
+ delete globalThis.DOMPurify;
+ delete window.XSSProtection;
+ delete window.escapeHtml;
+ delete window.escapeHtmlAttribute;
+ delete window.safeSetInnerHTML;
+ delete window.safeCreateElement;
+ delete window.safeSetTextContent;
+ delete window.createSafeAlertElement;
+ delete window.sanitizeUserInput;
+ delete window.sanitizeHtml;
+ delete window.safeUpdateButton;
+ delete window.createSafeLoadingOverlay;
+ delete window.safeSetStyles;
+ delete window.showSafeAlert;
+});
+
+beforeEach(() => {
+ document.body.replaceChildren();
+ delete window.__xssExecuted;
+ purifierBoundary.sanitize.mockReset();
+});
+
+afterEach(() => {
+ document.body.replaceChildren();
+ delete window.__xssExecuted;
+});
+
+it('installs and enforces the target-blank tabnabbing hook', () => {
+ expect(purifierBoundary.addHook).toHaveBeenCalledWith(
+ 'afterSanitizeAttributes',
+ expect.any(Function),
+ );
+
+ const link = document.createElement('a');
+ link.target = '_blank';
+ afterSanitizeAttributes(link);
+
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
+});
+
+it('the installed DOMPurify policy rejects executable attributes and URLs', () => {
+ expect(realDOMPurify.isValidAttribute(
+ 'a',
+ 'href',
+ 'javascript:alert(1)',
+ )).toBe(false);
+ expect(realDOMPurify.isValidAttribute(
+ 'img',
+ 'onerror',
+ 'window.__xssExecuted=true',
+ )).toBe(false);
+ expect(realDOMPurify.isValidAttribute(
+ 'a',
+ 'href',
+ 'https://example.test/source',
+ )).toBe(true);
+});
+
+it('safeSetInnerHTML inserts only the sanitizer result with the strict config', () => {
+ const host = document.createElement('div');
+ const dirty = `
+ <strong id="kept">Safe report</strong>
+ <img src="x" onerror="window.__xssExecuted = true">
+ <script>window.__xssExecuted = true</script>
+ <a href="javascript:alert(1)">bad link</a>
+ `;
+ purifierBoundary.sanitize.mockReturnValue(
+ '<strong id="kept">Safe report</strong>',
+ );
+
+ window.safeSetInnerHTML(host, dirty, true);
+
+ expect(purifierBoundary.sanitize).toHaveBeenCalledWith(
+ dirty,
+ expect.objectContaining({
+ ALLOWED_TAGS: expect.arrayContaining(['strong', 'a']),
+ FORBID_TAGS: expect.arrayContaining(['script', 'iframe', 'form']),
+ FORBID_ATTR: expect.arrayContaining(['onerror', 'onclick', 'on*']),
+ ALLOW_DATA_ATTR: false,
+ SAFE_FOR_TEMPLATES: true,
+ }),
+ );
+ expect(host.querySelector('#kept')?.textContent).toBe('Safe report');
+ expect(host.querySelector('img')).toBeNull();
+ expect(host.querySelector('script')).toBeNull();
+ expect(window.__xssExecuted).toBeUndefined();
+});
+
+it('safeCreateElement rejects unsafe tags and sanitizes unsafe attributes', () => {
+ expect(() => window.safeCreateElement('script', 'alert(1)'))
+ .toThrow('safeCreateElement: disallowed tag "script"');
+
+ purifierBoundary.sanitize.mockImplementation((dirty, config) => {
+ expect(dirty).toContain('href="javascript:alert(1)"');
+ expect(dirty).toContain('onclick="window.__xssExecuted = true"');
+ expect(config).toEqual({
+ ALLOWED_TAGS: ['a'],
+ RETURN_DOM_FRAGMENT: true,
+ });
+
+ const fragment = document.createDocumentFragment();
+ const sanitizedLink = document.createElement('a');
+ sanitizedLink.textContent = 'Safe label';
+ sanitizedLink.className = 'trusted-link';
+ sanitizedLink.target = '_blank';
+ sanitizedLink.rel = 'noopener noreferrer';
+ fragment.appendChild(sanitizedLink);
+ return fragment;
+ });
+
+ const link = window.safeCreateElement(
+ 'a',
+ 'Safe label',
+ {
+ href: 'javascript:alert(1)',
+ onclick: 'window.__xssExecuted = true',
+ target: '_blank',
+ },
+ ['trusted-link'],
+ );
+
+ expect(link.tagName).toBe('A');
+ expect(link.textContent).toBe('Safe label');
+ expect(link.classList.contains('trusted-link')).toBe(true);
+ expect(link.hasAttribute('href')).toBe(false);
+ expect(link.hasAttribute('onclick')).toBe(false);
+ expect(link.getAttribute('rel')).toBe('noopener noreferrer');
+});
+
+it('sanitizeUserInput allowHtml uses DOMPurify instead of HTML escaping', () => {
+ const dirty = ' <strong>kept</strong><img src=x onerror="window.__xssExecuted=true"> ';
+ purifierBoundary.sanitize.mockReturnValue('<strong>kept</strong>');
+
+ const clean = window.sanitizeUserInput(
+ dirty,
+ { allowHtml: true },
+ );
+
+ expect(clean).toBe('<strong>kept</strong>');
+ expect(clean).not.toContain('onerror');
+ expect(window.__xssExecuted).toBeUndefined();
+ expect(purifierBoundary.sanitize).toHaveBeenCalledWith(
+ dirty.trim(),
+ expect.objectContaining({
+ ALLOWED_TAGS: expect.arrayContaining(['strong']),
+ FORBID_TAGS: expect.arrayContaining(['script']),
+ }),
+ );
+});
diff --git a/tests/js/services/api.test.js b/tests/js/services/api.test.js
index 0476b245f3..3ee7491c89 100644
--- a/tests/js/services/api.test.js
+++ b/tests/js/services/api.test.js
@@ -10,6 +10,7 @@
* untouched to avoid redirect loops and false positives.
*/
+import '@js/config/urls.js';
import '@js/services/api.js';
const { fetchWithErrorHandling, shouldRedirectToLoginOn401 } = window.api;
@@ -71,6 +72,8 @@ describe('fetchWithErrorHandling — 401 handling', () => {
afterEach(() => {
globalThis.fetch = originalFetch;
window.location = originalLocation;
+ vi.useRealTimers();
+ vi.restoreAllMocks();
});
it('returns parsed JSON on 200 without redirecting', async () => {
@@ -201,4 +204,281 @@ describe('fetchWithErrorHandling — 401 handling', () => {
'API Error: 502 Bad Gateway'
);
});
+
+ it('aborts a stalled request at the caller-supplied timeout', async () => {
+ vi.useFakeTimers();
+ let requestSignal;
+ globalThis.fetch = vi.fn((_url, options) => {
+ requestSignal = options.signal;
+ return new Promise((_resolve, reject) => {
+ requestSignal.addEventListener('abort', () => {
+ const error = new Error('aborted by controller');
+ error.name = 'AbortError';
+ reject(error);
+ });
+ });
+ });
+
+ const request = fetchWithErrorHandling('/api/history', { timeout: 25 });
+ const rejection = expect(request).rejects.toThrow('Request timed out');
+
+ expect(requestSignal.aborted).toBe(false);
+ await vi.advanceTimersByTimeAsync(25);
+ await rejection;
+ expect(requestSignal.aborted).toBe(true);
+ });
+
+ it('retires the timeout after a successful response', async () => {
+ vi.useFakeTimers();
+ let requestSignal;
+ globalThis.fetch = vi.fn((_url, options) => {
+ requestSignal = options.signal;
+ return Promise.resolve(new Response('{"ok":true}', { status: 200 }));
+ });
+
+ await expect(
+ fetchWithErrorHandling('/api/history', { timeout: 25 })
+ ).resolves.toEqual({ ok: true });
+ await vi.advanceTimersByTimeAsync(25);
+
+ expect(requestSignal.aborted).toBe(false);
+ });
+
+ it('preserves caller cancellation instead of replacing its signal', async () => {
+ vi.useFakeTimers();
+ const callerController = new AbortController();
+ let requestSignal;
+ globalThis.fetch = vi.fn((_url, options) => {
+ requestSignal = options.signal;
+ return new Promise((_resolve, reject) => {
+ requestSignal.addEventListener('abort', () => {
+ const error = new Error('cancelled by caller');
+ error.name = 'AbortError';
+ reject(error);
+ });
+ });
+ });
+
+ const request = fetchWithErrorHandling('/api/history', {
+ signal: callerController.signal,
+ timeout: 30_000,
+ });
+ const rejection = expect(request).rejects.toMatchObject({
+ name: 'AbortError',
+ message: 'cancelled by caller',
+ });
+
+ expect(requestSignal).not.toBe(callerController.signal);
+ expect(requestSignal.aborted).toBe(false);
+ callerController.abort();
+ await rejection;
+
+ expect(requestSignal.aborted).toBe(true);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+
+ it('does not log caller cancellation as an API failure', async () => {
+ const callerController = new AbortController();
+ const cancellation = new globalThis.DOMException(
+ 'superseded API request',
+ 'AbortError',
+ );
+ const errorSpy = vi.spyOn(globalThis.SafeLogger, 'error');
+ globalThis.fetch = vi.fn((_url, options) =>
+ new Promise((_resolve, reject) => {
+ options.signal.addEventListener('abort', () => {
+ reject(options.signal.reason);
+ }, { once: true });
+ })
+ );
+
+ const request = fetchWithErrorHandling('/api/history', {
+ signal: callerController.signal,
+ });
+ const rejection = expect(request).rejects.toBe(cancellation);
+
+ callerController.abort(cancellation);
+ await rejection;
+
+ expect(errorSpy).not.toHaveBeenCalled();
+ });
+
+ it('preserves a caller signal that was already aborted before dispatch', async () => {
+ vi.useFakeTimers();
+ const callerController = new AbortController();
+ const cancellation = new globalThis.DOMException(
+ 'superseded status request',
+ 'AbortError',
+ );
+ callerController.abort(cancellation);
+ let requestSignal;
+ globalThis.fetch = vi.fn((_url, options) => {
+ requestSignal = options.signal;
+ return Promise.reject(requestSignal.reason);
+ });
+
+ await expect(fetchWithErrorHandling('/api/history', {
+ signal: callerController.signal,
+ timeout: 30_000,
+ })).rejects.toMatchObject({
+ name: 'AbortError',
+ message: 'superseded status request',
+ });
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ expect(requestSignal).not.toBe(callerController.signal);
+ expect(requestSignal.aborted).toBe(true);
+ expect(requestSignal.reason).toBe(cancellation);
+ expect(vi.getTimerCount()).toBe(0);
+ });
+});
+
+describe('FastAPI migration route contracts', () => {
+ const originalFetch = globalThis.fetch;
+
+ beforeEach(() => {
+ document.head.innerHTML =
+ '<meta name="csrf-token" content="csrf-migration-test">';
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve(new Response('{"ok":true}', { status: 200 }))
+ );
+ });
+
+ afterEach(() => {
+ globalThis.fetch = originalFetch;
+ document.head.innerHTML = '';
+ });
+
+ it('POSTs open-file requests to the settings router with CSRF', async () => {
+ await window.api.openFileLocation('/tmp/research-report.md');
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ const [url, options] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe('/settings/open_file_location');
+ expect(options.method).toBe('POST');
+ expect(options.headers['X-CSRFToken']).toBe('csrf-migration-test');
+ expect(JSON.parse(options.body)).toEqual({
+ path: '/tmp/research-report.md',
+ });
+ });
+
+ it('preserves a caller-supplied CSRF token instead of replacing it with stale page metadata', async () => {
+ await fetchWithErrorHandling('/settings/save_all_settings', {
+ method: 'POST',
+ headers: {
+ 'X-CSRFToken': 'csrf-refreshed-by-caller',
+ 'X-Request-Source': 'settings-form',
+ },
+ body: '{}',
+ });
+
+ const [, options] = globalThis.fetch.mock.calls[0];
+ expect(options.headers).toMatchObject({
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-refreshed-by-caller',
+ 'X-Request-Source': 'settings-form',
+ });
+ });
+
+ it.each([
+ 'saveMainConfig',
+ 'saveSearchEnginesConfig',
+ 'saveCollectionsConfig',
+ 'saveApiKeysConfig',
+ 'saveLlmConfig',
+ ])('%s uses the canonical bulk-settings route', async (methodName) => {
+ await window.api[methodName]({ enabled: true });
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ const [url, options] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe('/settings/save_all_settings');
+ expect(options.method).toBe('POST');
+ expect(options.headers['X-CSRFToken']).toBe('csrf-migration-test');
+ expect(JSON.parse(options.body)).toEqual({ enabled: true });
+ });
+
+ it('loads history from the router that returns the items envelope', async () => {
+ await window.api.getResearchHistory();
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ expect(globalThis.fetch.mock.calls[0][0]).toBe('/history/api');
+ });
+
+ it('downloads markdown from the migrated history route', async () => {
+ await window.api.getMarkdownExport('research-42');
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);
+ expect(globalThis.fetch.mock.calls[0][0]).toBe(
+ '/history/markdown/research-42'
+ );
+ });
+
+ it.each([
+ ['getResearchStatus', '/api/research/research-42/status'],
+ ['getResearchDetails', '/api/research/research-42'],
+ ['getResearchLogs', '/api/research/research-42/logs'],
+ ['getReport', '/api/report/research-42'],
+ ])('%s keeps string research IDs on the canonical GET route', async (
+ methodName,
+ expectedUrl,
+ ) => {
+ await window.api[methodName]('research-42');
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ const [url, options] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe(expectedUrl);
+ expect(options.method).toBeUndefined();
+ });
+
+ it.each([
+ [
+ 'startResearch',
+ ['Migration contract', 'detailed'],
+ '/api/start_research',
+ { query: 'Migration contract', mode: 'detailed' },
+ ],
+ [
+ 'terminateResearch',
+ ['research-42'],
+ '/api/terminate/research-42',
+ {},
+ ],
+ [
+ 'clearResearchHistory',
+ [],
+ '/api/clear_history',
+ {},
+ ],
+ [
+ 'saveRawConfig',
+ ['llm:\n provider: ollama'],
+ '/api/save_raw_config',
+ { raw_config: 'llm:\n provider: ollama' },
+ ],
+ ])('%s POSTs its migrated payload with CSRF', async (
+ methodName,
+ args,
+ expectedUrl,
+ expectedBody,
+ ) => {
+ await window.api[methodName](...args);
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ const [url, options] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe(expectedUrl);
+ expect(options.method).toBe('POST');
+ expect(options.headers['X-CSRFToken']).toBe('csrf-migration-test');
+ expect(JSON.parse(options.body)).toEqual(expectedBody);
+ });
+
+ it('DELETEs a migrated research ID with CSRF and no synthetic body', async () => {
+ await window.api.deleteResearch('research-42');
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ const [url, options] = globalThis.fetch.mock.calls[0];
+ expect(url).toBe('/api/delete/research-42');
+ expect(options.method).toBe('DELETE');
+ expect(options.headers['X-CSRFToken']).toBe('csrf-migration-test');
+ expect(options.body).toBeUndefined();
+ });
});
diff --git a/tests/js/services/audio-runtime.test.js b/tests/js/services/audio-runtime.test.js
new file mode 100644
index 0000000000..677893a664
--- /dev/null
+++ b/tests/js/services/audio-runtime.test.js
@@ -0,0 +1,25 @@
+/** Contract for the deliberately disabled audio service used by progress pages. */
+
+beforeAll(async () => {
+ await import('@js/services/audio.js');
+});
+
+afterAll(() => {
+ delete window.audio;
+});
+
+it('publishes the complete no-op API and never attempts playback', () => {
+ expect(window.audio).toMatchObject({
+ initialize: expect.any(Function),
+ playSuccess: expect.any(Function),
+ playError: expect.any(Function),
+ play: expect.any(Function),
+ test: expect.any(Function),
+ });
+
+ expect(window.audio.initialize()).toBe(false);
+ expect(window.audio.playSuccess()).toBe(false);
+ expect(window.audio.playError()).toBe(false);
+ expect(window.audio.play()).toBe(false);
+ expect(window.audio.test()).toBe(false);
+});
diff --git a/tests/js/services/help-runtime.test.js b/tests/js/services/help-runtime.test.js
new file mode 100644
index 0000000000..00bc27dd69
--- /dev/null
+++ b/tests/js/services/help-runtime.test.js
@@ -0,0 +1,146 @@
+/**
+ * Direct initialization and failure contracts for the browser help service.
+ * The older unit suite covers successful public actions; these cases bind the
+ * FastAPI bulk-state envelope and the recovery paths used during page startup.
+ */
+
+let HelpService;
+let bulkFetch;
+let originalFetch;
+
+function panel(id, { collapsed = false } = {}) {
+ const element = document.createElement('section');
+ element.id = `help-panel-${id}`;
+ element.className = `ldr-help-panel${collapsed ? ' collapsed' : ''}`;
+ element.dataset.panelId = id;
+ const header = document.createElement('button');
+ header.className = 'ldr-help-panel-header';
+ header.setAttribute('aria-expanded', String(!collapsed));
+ element.appendChild(header);
+ document.body.appendChild(element);
+ return element;
+}
+
+beforeAll(async () => {
+ originalFetch = globalThis.fetch;
+ document.body.replaceChildren();
+ localStorage.clear();
+ const restored = panel('alpha /');
+ const dismissed = panel('beta');
+ const tooltip = document.createElement('button');
+ tooltip.className = 'ldr-help-tooltip';
+ tooltip.setAttribute('aria-expanded', 'false');
+ document.body.appendChild(tooltip);
+ localStorage.setItem('ldr_panel_collapsed_alpha /', 'true');
+
+ let resolveBulk;
+ bulkFetch = vi.fn(() => new Promise(resolve => {
+ resolveBulk = resolve;
+ }));
+ globalThis.fetch = bulkFetch;
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-help') };
+ window.ui = { showMessage: vi.fn() };
+
+ await import('@js/services/help.js');
+ HelpService = window.HelpService;
+
+ const keyboardEvent = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ cancelable: true,
+ });
+ tooltip.dispatchEvent(keyboardEvent);
+ expect(keyboardEvent.defaultPrevented).toBe(true);
+ expect(tooltip.getAttribute('aria-expanded')).toBe('true');
+
+ await HelpService.init();
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ resolveBulk({
+ ok: true,
+ json: () => Promise.resolve({
+ success: true,
+ settings: {
+ 'app.ui.help_dismissed_beta': { value: 'True' },
+ },
+ }),
+ });
+
+ await vi.waitFor(() => {
+ expect(dismissed.style.display).toBe('none');
+ });
+ expect(restored.classList.contains('collapsed')).toBe(true);
+ expect(restored.querySelector('.ldr-help-panel-header')
+ .getAttribute('aria-expanded')).toBe('false');
+});
+
+afterAll(() => {
+ document.body.replaceChildren();
+ localStorage.clear();
+ delete window.HelpService;
+ delete window.api;
+ delete window.ui;
+ globalThis.fetch = originalFetch;
+});
+
+beforeEach(() => {
+ // Failure-path cases replace fetch; restore the bootstrap spy so shuffled
+ // test order cannot change which request the bulk-load contract observes.
+ globalThis.fetch = bulkFetch;
+ window.ui.showMessage.mockClear();
+});
+
+it('loads encoded panel keys once and recognizes the backend truth value', () => {
+ expect(bulkFetch).toHaveBeenCalledWith(
+ '/settings/api/bulk?keys[]=app.ui.help_dismissed_alpha%20%2F'
+ + '&keys[]=app.ui.help_dismissed_beta',
+ );
+ expect(HelpService.isPanelDismissed('beta')).toBe(true);
+ expect(HelpService.isPanelDismissed('alpha /')).toBe(false);
+});
+
+it('keeps a panel visible when FastAPI rejects its dismissal', async () => {
+ const retained = panel('retained');
+ globalThis.fetch = vi.fn().mockResolvedValue({ ok: false, status: 503 });
+
+ await HelpService.dismissPanel('retained');
+
+ expect(retained.style.display).toBe('');
+ expect(HelpService.isPanelDismissed('retained')).toBe(false);
+ expect(window.ui.showMessage)
+ .toHaveBeenCalledWith('Failed to save preference', 'error');
+});
+
+it('contains a network failure while dismissing a panel', async () => {
+ const retained = panel('offline');
+ globalThis.fetch = vi.fn().mockRejectedValue(new Error('offline'));
+ const error = vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+
+ await expect(HelpService.dismissPanel('offline')).resolves.toBeUndefined();
+
+ expect(retained.style.display).toBe('');
+ expect(error).toHaveBeenCalledWith(
+ 'Error dismissing panel:',
+ expect.objectContaining({ message: 'offline' }),
+ );
+ expect(window.ui.showMessage)
+ .toHaveBeenCalledWith('Failed to save preference', 'error');
+ error.mockRestore();
+});
+
+it('persists collapsed state even when storage is unavailable', () => {
+ const retained = panel('storage-failure');
+ const warn = vi.spyOn(SafeLogger, 'warn').mockImplementation(() => {});
+ const storage = vi.spyOn(window.localStorage, 'setItem')
+ .mockImplementation(() => {
+ throw new Error('blocked');
+ });
+
+ expect(() => HelpService.togglePanel('storage-failure')).not.toThrow();
+
+ expect(retained.classList.contains('collapsed')).toBe(true);
+ expect(warn).toHaveBeenCalledWith(
+ 'Failed to save panel state:',
+ expect.objectContaining({ message: 'blocked' }),
+ );
+ storage.mockRestore();
+ warn.mockRestore();
+});
diff --git a/tests/js/services/help.test.js b/tests/js/services/help.test.js
index c3de8feda6..70da9945aa 100644
--- a/tests/js/services/help.test.js
+++ b/tests/js/services/help.test.js
@@ -143,8 +143,85 @@ describe('HelpService', () => {
);
await HelpService.dismissPanel('dismiss1');
+
+ expect(globalThis.fetch).toHaveBeenCalledWith(
+ '/settings/api/app.ui.help_dismissed_dismiss1',
+ {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'test-token',
+ },
+ body: JSON.stringify({ value: true }),
+ },
+ );
expect(panel.style.display).toBe('none');
expect(HelpService.isPanelDismissed('dismiss1')).toBe(true);
});
});
+
+ describe('resetDismissedPanels', () => {
+ it('DELETEs every panel setting with CSRF and makes panels visible', async () => {
+ const first = createPanel('reset-one');
+ const second = createPanel('reset/two');
+ first.style.display = 'none';
+ second.style.display = 'none';
+ globalThis.fetch = vi.fn(() =>
+ Promise.resolve({ ok: true, status: 200 })
+ );
+
+ await HelpService.resetDismissedPanels();
+
+ expect(globalThis.fetch.mock.calls).toEqual([
+ [
+ '/settings/api/app.ui.help_dismissed_reset-one',
+ {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': 'test-token' },
+ },
+ ],
+ [
+ '/settings/api/app.ui.help_dismissed_reset%2Ftwo',
+ {
+ method: 'DELETE',
+ headers: { 'X-CSRFToken': 'test-token' },
+ },
+ ],
+ ]);
+ expect(first.style.display).toBe('');
+ expect(second.style.display).toBe('');
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Help panels reset',
+ 'success',
+ );
+ });
+
+ it('keeps a panel dismissed when its DELETE is rejected', async () => {
+ const reset = createPanel('reset-success');
+ const retained = createPanel('reset-failed');
+ globalThis.fetch = vi.fn(() => Promise.resolve({ ok: true, status: 200 }));
+ await HelpService.dismissPanel('reset-success');
+ await HelpService.dismissPanel('reset-failed');
+ expect(reset.style.display).toBe('none');
+ expect(retained.style.display).toBe('none');
+
+ window.ui.showMessage.mockClear();
+ globalThis.fetch = vi.fn(url => Promise.resolve({
+ ok: !url.endsWith('reset-failed'),
+ status: url.endsWith('reset-failed') ? 503 : 200,
+ }));
+
+ await HelpService.resetDismissedPanels();
+
+ expect(reset.style.display).toBe('');
+ expect(HelpService.isPanelDismissed('reset-success')).toBe(false);
+ expect(retained.style.display).toBe('none');
+ expect(HelpService.isPanelDismissed('reset-failed')).toBe(true);
+ expect(window.ui.showMessage).toHaveBeenCalledOnce();
+ expect(window.ui.showMessage).toHaveBeenCalledWith(
+ 'Could not reset 1 help panel',
+ 'error',
+ );
+ });
+ });
});
diff --git a/tests/js/services/keyboard.test.js b/tests/js/services/keyboard.test.js
index 7db75a852b..1c5d6d822a 100644
--- a/tests/js/services/keyboard.test.js
+++ b/tests/js/services/keyboard.test.js
@@ -63,9 +63,6 @@ describe('KeyboardService', () => {
describe('keyboard event handling', () => {
it('Escape key triggers newSearch shortcut', () => {
- // The shortcut sets window.location.href, which we can spy on
- const originalHref = window.location.href;
-
// Create a keydown event for Escape
const event = new KeyboardEvent('keydown', {
key: 'Escape',
@@ -112,6 +109,87 @@ describe('KeyboardService', () => {
expect(() => input.dispatchEvent(event)).not.toThrow();
input.remove();
});
+
+ it('does not navigate when Escape closes a settings select', () => {
+ window.history.replaceState({}, '', '/settings/');
+ const select = document.createElement('select');
+ const option = document.createElement('option');
+ option.value = 'openai';
+ option.textContent = 'OpenAI';
+ select.appendChild(option);
+ document.body.appendChild(select);
+ select.focus();
+ const event = new KeyboardEvent('keydown', {
+ key: 'Escape',
+ code: 'Escape',
+ bubbles: true,
+ cancelable: true,
+ });
+
+ select.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(false);
+ expect(window.location.pathname).toBe('/settings/');
+ select.remove();
+ });
+
+ it('opens a visible same-origin result with Enter on progress pages', () => {
+ window.history.replaceState({}, '', '/progress/research-3299');
+ const viewButton = document.createElement('a');
+ viewButton.id = 'view-results-btn';
+ viewButton.href = '/results/research-3299';
+ viewButton.style.display = 'block';
+ document.body.appendChild(viewButton);
+ const event = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ code: 'Enter',
+ bubbles: true,
+ cancelable: true,
+ });
+
+ document.dispatchEvent(event);
+
+ expect(event.defaultPrevented).toBe(true);
+ expect(window.location.pathname).toBe('/results/research-3299');
+ viewButton.remove();
+ });
+
+ it('does not consume Enter for hidden or external result links', () => {
+ window.history.replaceState({}, '', '/progress/research-3299');
+ const viewButton = document.createElement('a');
+ viewButton.id = 'view-results-btn';
+ viewButton.href = '/results/research-3299';
+ viewButton.style.display = 'none';
+ document.body.appendChild(viewButton);
+
+ const hiddenEvent = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ code: 'Enter',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(hiddenEvent);
+ expect(hiddenEvent.defaultPrevented).toBe(false);
+ expect(window.location.pathname).toBe('/progress/research-3299');
+
+ viewButton.style.display = 'block';
+ viewButton.href = 'https://example.test/results/research-3299';
+ const logger = vi.spyOn(SafeLogger, 'error');
+ const externalEvent = new KeyboardEvent('keydown', {
+ key: 'Enter',
+ code: 'Enter',
+ bubbles: true,
+ cancelable: true,
+ });
+ document.dispatchEvent(externalEvent);
+
+ expect(externalEvent.defaultPrevented).toBe(false);
+ expect(window.location.pathname).toBe('/progress/research-3299');
+ expect(logger).toHaveBeenCalledWith(
+ 'Blocked non-same-origin redirect in keyboard shortcut',
+ );
+ viewButton.remove();
+ });
});
});
diff --git a/tests/js/services/pdf-runtime.test.js b/tests/js/services/pdf-runtime.test.js
new file mode 100644
index 0000000000..0321bead21
--- /dev/null
+++ b/tests/js/services/pdf-runtime.test.js
@@ -0,0 +1,391 @@
+/**
+ * Direct runtime contracts for PDF generation and browser downloads.
+ * jsPDF and html2canvas are boundary fakes; all branching, DOM walking,
+ * sanitization requirements, download ownership, and cleanup are production
+ * code from services/pdf.js.
+ */
+
+import '@js/services/pdf.js';
+
+const { downloadPdf, generatePdf } = window.pdfService;
+
+let pdfInstances;
+let createdBlob;
+let pageWidth;
+let pageHeight;
+
+class FakePdf {
+ constructor() {
+ this.internal = {
+ pageSize: {
+ getWidth: () => pageWidth,
+ getHeight: () => pageHeight,
+ },
+ };
+ this.setFontSize = vi.fn();
+ this.setTextColor = vi.fn();
+ this.text = vi.fn();
+ this.setFont = vi.fn();
+ this.splitTextToSize = vi.fn((text) => String(text).split('\n'));
+ this.getTextWidth = vi.fn((text) => String(text).length * 5);
+ this.addPage = vi.fn();
+ this.setFillColor = vi.fn();
+ this.rect = vi.fn();
+ this.textWithLink = vi.fn();
+ this.setDrawColor = vi.fn();
+ this.setLineWidth = vi.fn();
+ this.line = vi.fn();
+ this.addImage = vi.fn();
+ this.output = vi.fn(() => createdBlob);
+ pdfInstances.push(this);
+ }
+}
+
+function canvas(width = 200, height = 100) {
+ return {
+ width,
+ height,
+ toDataURL: vi.fn(() => 'data:image/png;base64,rendered'),
+ };
+}
+
+beforeEach(() => {
+ document.body.replaceChildren();
+ pdfInstances = [];
+ createdBlob = new Blob(['pdf'], { type: 'application/pdf' });
+ pageWidth = 612;
+ pageHeight = 792;
+ globalThis.jsPDF = FakePdf;
+ globalThis.html2canvas = vi.fn().mockResolvedValue(canvas());
+ window.marked = { parse: vi.fn((markdown) => String(markdown)) };
+ window.DOMPurify = { sanitize: vi.fn((html) => html) };
+ globalThis.URLValidator = {
+ safeAssign: vi.fn((element, property, value) => {
+ element[property] = value;
+ }),
+ };
+ Object.defineProperty(URL, 'createObjectURL', {
+ configurable: true,
+ value: vi.fn(() => 'blob:pdf-download'),
+ });
+ Object.defineProperty(URL, 'revokeObjectURL', {
+ configurable: true,
+ value: vi.fn(),
+ });
+ window.alert = vi.fn();
+ vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ document.body.replaceChildren();
+ delete globalThis.jsPDF;
+ delete globalThis.html2canvas;
+ delete globalThis.URLValidator;
+ delete window.marked;
+ delete window.DOMPurify;
+ delete window.alert;
+});
+
+it('fails before rendering when jsPDF is unavailable', async () => {
+ delete globalThis.jsPDF;
+ await expect(generatePdf('Title', 'Report')).rejects.toThrow(
+ 'PDF generation libraries not loaded (jsPDF missing)',
+ );
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
+
+it('fails before rendering when html2canvas is unavailable', async () => {
+ delete globalThis.html2canvas;
+ await expect(generatePdf('Title', 'Report')).rejects.toThrow(
+ 'PDF generation libraries not loaded (html2canvas missing)',
+ );
+
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
+
+it('requires the markdown parser and cleans its temporary DOM', async () => {
+ delete window.marked;
+ await expect(generatePdf('Title', '# Report')).rejects.toThrow(
+ 'Markdown parser (marked.js) not loaded. Cannot generate PDF.',
+ );
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
+
+it('requires the sanitizer and cleans its temporary DOM', async () => {
+ window.marked.parse.mockReturnValue('<p>Report</p>');
+ delete window.DOMPurify;
+ await expect(generatePdf('Title', '# Report')).rejects.toThrow(
+ 'DOMPurify not loaded. Cannot generate PDF safely.',
+ );
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
+
+it('sanitizes and walks structured report content into selectable PDF operations', async () => {
+ const html = `
+ <h1>Migration report</h1>
+ <h2>FastAPI contracts</h2>
+ <h3>Details</h3>
+ <p>Read <a href="https://example.test/source">the source</a> now</p>
+ <p>Legacy citation [[7]](https://example.test/citation)</p>
+ <ul><li>Bullet <a href="https://example.test/list">link</a></li></ul>
+ <ol><li>Numbered item</li></ol>
+ <table>
+ <tr><th>Route</th><th>Status</th></tr>
+ <tr><td>/api/report</td><td>migrated</td></tr>
+ </table>
+ <pre>const route = '/api/report';</pre>
+ <img src="data:image/jpeg;base64,image">
+ <section>Fallback text remains selectable</section>
+ <section><svg></svg></section>
+ `;
+ window.marked.parse.mockReturnValue(html);
+
+ const result = await generatePdf('Migration', '# ignored');
+
+ expect(result).toBe(createdBlob);
+ expect(window.DOMPurify.sanitize).toHaveBeenCalledWith(html, {
+ ADD_TAGS: ['semantics', 'annotation'],
+ });
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+ expect(pdfInstances).toHaveLength(1);
+ const pdf = pdfInstances[0];
+ expect(pdf.textWithLink).toHaveBeenCalledWith(
+ 'the source ',
+ expect.any(Number),
+ expect.any(Number),
+ { url: 'https://example.test/source' },
+ );
+ expect(pdf.textWithLink).toHaveBeenCalledWith(
+ '[7]',
+ expect.any(Number),
+ expect.any(Number),
+ { url: 'https://example.test/citation' },
+ );
+ expect(pdf.rect).toHaveBeenCalled();
+ expect(pdf.addImage).toHaveBeenCalledWith(
+ 'data:image/png;base64,rendered',
+ 'PNG',
+ expect.any(Number),
+ expect.any(Number),
+ expect.any(Number),
+ expect.any(Number),
+ );
+ expect(pdf.output).toHaveBeenCalledWith('blob');
+ expect(globalThis.html2canvas).toHaveBeenCalledWith(
+ expect.any(Element),
+ {
+ scale: 2,
+ useCORS: true,
+ logging: false,
+ backgroundColor: '#FFFFFF',
+ },
+ );
+});
+
+it('contains one malformed element and keeps producing the remaining PDF', async () => {
+ window.marked.parse.mockReturnValue('<p>Broken</p><p>Still rendered</p>');
+ class PartiallyFailingPdf extends FakePdf {
+ constructor() {
+ super();
+ this.splitTextToSize
+ .mockImplementationOnce(() => {
+ throw new Error('cannot measure first paragraph');
+ })
+ .mockImplementation((text) => [String(text)]);
+ }
+ }
+ globalThis.jsPDF = PartiallyFailingPdf;
+
+ await expect(generatePdf('Title', 'Report')).resolves.toBe(createdBlob);
+
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error processing element:',
+ expect.objectContaining({ message: 'cannot measure first paragraph' }),
+ );
+ expect(pdfInstances[0].text).toHaveBeenCalledWith(
+ '[Error rendering content]',
+ 40,
+ expect.any(Number),
+ );
+ expect(pdfInstances[0].text).toHaveBeenCalledWith(
+ ['Still rendered'],
+ 40,
+ expect.any(Number),
+ );
+});
+
+it('paginates long structured reports and redraws table ownership headers', async () => {
+ pageHeight = 115;
+ window.marked.parse.mockReturnValue(`
+ <h1>Long migration report</h1>
+ <h2>Next section</h2>
+ <p>Paragraph crossing the remaining page</p>
+ <ul><li>First item</li><li>Second item</li></ul>
+ <table>
+ <tr><th>Route</th><th>Owner</th><th>Method</th><th>Status</th><th>Notes</th></tr>
+ <tr><td>/api/report</td><td>results</td><td>GET</td><td>ready</td><td>one</td></tr>
+ <tr><td>/api/start</td><td>research</td><td>POST</td><td>ready</td><td>two</td></tr>
+ </table>
+ <pre>line one\nline two\nline three</pre>
+ <section>Fallback text</section>
+ <section><svg></svg></section>
+ `);
+
+ await expect(generatePdf('Long report', 'ignored'))
+ .resolves.toBe(createdBlob);
+
+ const pdf = pdfInstances[0];
+ expect(pdf.addPage.mock.calls.length).toBeGreaterThanOrEqual(6);
+ const headerDraws = pdf.text.mock.calls.filter(([text]) =>
+ Array.isArray(text) && text[0] === 'Route');
+ expect(headerDraws.length).toBeGreaterThanOrEqual(2);
+ expect(pdf.output).toHaveBeenCalledWith('blob');
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
+
+it('wraps long links and citations across pages without losing their targets', async () => {
+ pageWidth = 140;
+ pageHeight = 90;
+ window.marked.parse.mockReturnValue(`
+ <p>alpha beta gamma <a href="https://example.test/report-source">report source</a> omega psi</p>
+ <p>alpha beta [[99]](https://example.test/citation) omega psi</p>
+ <ul>
+ <li>alpha beta <a href="https://example.test/list-source">list source</a> omega</li>
+ </ul>
+ `);
+
+ await expect(generatePdf('Linked report', 'ignored'))
+ .resolves.toBe(createdBlob);
+
+ const pdf = pdfInstances[0];
+ expect(pdf.addPage.mock.calls.length).toBeGreaterThanOrEqual(4);
+ expect(pdf.textWithLink).toHaveBeenCalledWith(
+ 'report source ',
+ expect.any(Number),
+ expect.any(Number),
+ { url: 'https://example.test/report-source' },
+ );
+ expect(pdf.textWithLink).toHaveBeenCalledWith(
+ '[99]',
+ expect.any(Number),
+ expect.any(Number),
+ { url: 'https://example.test/citation' },
+ );
+ expect(pdf.textWithLink).toHaveBeenCalledWith(
+ 'list source ',
+ expect.any(Number),
+ expect.any(Number),
+ { url: 'https://example.test/list-source' },
+ );
+});
+
+it('falls back to a readable placeholder when an image URL is rejected', async () => {
+ window.marked.parse.mockReturnValue(
+ '<img src="https://untrusted.example/image.jpg">',
+ );
+ globalThis.URLValidator.safeAssign.mockImplementation(() => {
+ throw new Error('unsafe image URL');
+ });
+
+ await expect(generatePdf('Report', 'ignored')).resolves.toBe(createdBlob);
+
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error adding image:',
+ expect.objectContaining({ message: 'unsafe image URL' }),
+ );
+ expect(pdfInstances[0].text).toHaveBeenCalledWith(
+ '[Image could not be rendered]',
+ 40,
+ expect.any(Number),
+ );
+});
+
+it('contains an html2canvas failure to the unsupported element', async () => {
+ window.marked.parse.mockReturnValue('<section><svg></svg></section>');
+ globalThis.html2canvas.mockRejectedValue(new Error('canvas tainted'));
+
+ await expect(generatePdf('Report', 'ignored')).resolves.toBe(createdBlob);
+
+ expect(pdfInstances[0].text).toHaveBeenCalledWith(
+ '[Content could not be rendered]',
+ 40,
+ expect.any(Number),
+ );
+ expect(pdfInstances[0].output).toHaveBeenCalledWith('blob');
+});
+
+it('keeps the loading state until rendering completes and revokes the download URL', async () => {
+ window.marked.parse.mockReturnValue('<section><svg></svg></section>');
+ let finishCanvas;
+ globalThis.html2canvas.mockImplementation(() => new Promise((resolve) => {
+ finishCanvas = resolve;
+ }));
+ let clickedDownload;
+ let clickedHref;
+ vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(function click() {
+ clickedDownload = this.download;
+ clickedHref = this.href;
+ });
+
+ const pending = downloadPdf('Migration: #3299', 'Report');
+ await vi.waitFor(() => {
+ expect(document.querySelector('.ldr-loading-indicator')).not.toBeNull();
+ });
+ finishCanvas(canvas());
+
+ await expect(pending).resolves.toBe(true);
+
+ expect(clickedDownload).toBe('migration___3299_research.pdf');
+ expect(clickedHref).toBe('blob:pdf-download');
+ expect(URL.createObjectURL).toHaveBeenCalledWith(createdBlob);
+ expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:pdf-download');
+ expect(globalThis.URLValidator.safeAssign).toHaveBeenCalledWith(
+ expect.any(window.HTMLAnchorElement),
+ 'href',
+ 'blob:pdf-download',
+ );
+ expect(document.querySelector('.ldr-loading-indicator')).toBeNull();
+ expect(document.querySelector('a[download]')).toBeNull();
+});
+
+it('safely reduces legacy HTML research data to text before PDF rendering', async () => {
+ const clickSpy = vi.spyOn(window.HTMLAnchorElement.prototype, 'click')
+ .mockImplementation(() => {});
+ window.pwned = undefined;
+
+ await downloadPdf({
+ query: 'Legacy report',
+ html: '<h1>Hello</h1><p><img src=x onerror="window.pwned=true">Safe &amp; sound</p>',
+ created_at: '2026-09-01T10:00:00Z',
+ }, 'research-3299');
+
+ const markdownInput = window.marked.parse.mock.calls[0][0];
+ expect(markdownInput).toContain('# Hello');
+ expect(markdownInput).toContain('Safe & sound');
+ expect(markdownInput).not.toContain('<img');
+ expect(markdownInput).not.toContain('onerror');
+ expect(window.pwned).toBeUndefined();
+ expect(clickSpy).toHaveBeenCalledOnce();
+});
+
+it('reports generation failures and always removes transient browser state', async () => {
+ globalThis.jsPDF = class BrokenPdf {
+ constructor() {
+ throw new Error('printer unavailable');
+ }
+ };
+
+ await expect(downloadPdf('Report', 'Body'))
+ .rejects.toThrow('printer unavailable');
+
+ expect(window.alert)
+ .toHaveBeenCalledWith('Error generating PDF: printer unavailable');
+ expect(SafeLogger.error).toHaveBeenCalledWith(
+ 'Error generating PDF:',
+ expect.objectContaining({ message: 'printer unavailable' }),
+ );
+ expect(document.querySelector('.ldr-loading-indicator')).toBeNull();
+ expect(document.querySelector('.ldr-pdf-content')).toBeNull();
+});
diff --git a/tests/js/services/socket-page-polling-ownership.test.js b/tests/js/services/socket-page-polling-ownership.test.js
new file mode 100644
index 0000000000..1d488b890d
--- /dev/null
+++ b/tests/js/services/socket-page-polling-ownership.test.js
@@ -0,0 +1,172 @@
+/** Couple the real socket fallback to its shipped page polling consumers. */
+import { resolve } from 'node:path';
+import { compileTemplateHarness } from '../helpers/template-harness.js';
+
+const source = name => resolve(__dirname, '../../../src/local_deep_research/web', name);
+let transport;
+let service;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.useFakeTimers();
+ vi.spyOn(window, 'location', 'get').mockReturnValue({
+ pathname: '/progress/owner-run', protocol: 'http:', host: 'localhost',
+ });
+ const handlers = {};
+ transport = {
+ connected: false,
+ on: vi.fn((name, callback) => { (handlers[name] ||= []).push(callback); }),
+ off: vi.fn(), emit: vi.fn(), disconnect: vi.fn(),
+ fire(name) { (handlers[name] || []).forEach(callback => callback(new Error('offline'))); },
+ };
+ vi.stubGlobal('io', () => transport);
+ vi.stubGlobal('fetch', vi.fn().mockImplementation(async () => ({
+ ok: true, json: async () => ({ status: 'in_progress', progress: 25 }),
+ })));
+ window.api = {
+ getResearchStatus: vi.fn().mockResolvedValue({ status: 'in_progress', progress: 25 }),
+ };
+ window.ResearchStates = { isTerminal: () => false, logLevel: () => 'info' };
+ window.pollIntervals = {};
+ delete window.pollResearchStatus;
+ delete window.addConsoleLog;
+ delete window._socketAddLogEntry;
+ delete window.logPanel;
+ document.body.innerHTML = '<section id="performance-charts-section"></section>';
+ await import('@js/services/socket.js');
+ service = window.socket;
+ service.init();
+});
+
+afterEach(() => {
+ service.disconnect();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.socket;
+ delete window.ResearchStates;
+ delete window.pollIntervals;
+ delete window.pollResearchStatus;
+ delete window.addConsoleLog;
+ delete window._socketAddLogEntry;
+ delete window.logPanel;
+ document.body.replaceChildren();
+});
+
+function failInitialConnection() {
+ for (let attempt = 0; attempt < 3; attempt++) transport.fire('connect_error');
+}
+
+it('does not recurse or change log counts when the log panel is unavailable', () => {
+ document.body.innerHTML = '<div id="console-log-container"></div><span id="log-indicator">7</span>';
+ expect(() => window.addConsoleLog('fallback event')).not.toThrow();
+ expect(() => window._socketAddLogEntry({ message: 'socket event', type: 'info' })).not.toThrow();
+ expect(document.getElementById('console-log-container').children).toHaveLength(0);
+ expect(document.getElementById('log-indicator').textContent).toBe('7');
+});
+
+it('still routes logs to a replacement connector and prefers the real log panel', () => {
+ const connector = vi.fn();
+ window._socketAddLogEntry = connector;
+ window.addConsoleLog('connector event', 'warning', { phase: 'search' });
+ expect(connector).toHaveBeenCalledOnce();
+ expect(connector).toHaveBeenCalledWith(expect.objectContaining({
+ message: 'connector event', type: 'warning', metadata: { phase: 'search' },
+ }));
+ const addLog = vi.fn();
+ window.logPanel = { addLog };
+ window.addConsoleLog('panel event', 'info', { phase: 'done' });
+ expect(addLog).toHaveBeenCalledExactlyOnceWith('panel event', 'info', { phase: 'done' });
+ expect(connector).toHaveBeenCalledOnce();
+});
+
+it('keeps chat on its single one-second completion poll', async () => {
+ const page = compileTemplateHarness({
+ templatePath: source('static/js/components/chat.js'),
+ functionNames: ['subscribeToResearch', 'attachResearchListeners', 'pollForCompletion'],
+ dependencies: {
+ _log: { warn: vi.fn(), error: vi.fn() },
+ getCsrfToken: () => 'csrf-chat',
+ handleProgressUpdate: vi.fn(), handleResponseChunk: vi.fn(),
+ handleResearchComplete: vi.fn(), handleResearchSuspended: vi.fn(), handleResearchError: vi.fn(),
+ },
+ preamble: `
+ let currentResearchId = 'owner-run';
+ let streamingMessageEl = null, streamedContent = '', streamTruncated = false;
+ let streamingComplete = false, lastStepPhase = null, _stableProgressCb = null;
+ let subscribeRetryTimerId = null, pollTimerId = null, chatMessages = null;
+ `,
+ returnExpression: '({ subscribeToResearch })',
+ });
+ page.subscribeToResearch('owner-run', null);
+ failInitialConnection();
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(fetch).toHaveBeenCalledTimes(6);
+ expect(fetch).toHaveBeenCalledWith('/api/research/owner-run/status', expect.any(Object));
+ expect(window.api.getResearchStatus).not.toHaveBeenCalled();
+ expect(Object.keys(window.pollIntervals)).toEqual([]);
+});
+
+it('starts only the progress page poll when the initial connection fails', async () => {
+ const page = compileTemplateHarness({
+ templatePath: source('static/js/components/progress.js'),
+ functionNames: ['initializeSocket', 'fallbackToPolling', 'checkProgress', 'claimProgressSnapshot'],
+ dependencies: {
+ handleProgressUpdate: vi.fn(), updateProgressUI: vi.fn(), handleResearchCompletion: vi.fn(),
+ },
+ preamble: `
+ let currentResearchId = 'owner-run', pollInterval = null;
+ let isCompleted = false, researchCompleted = false, socketErrorShown = false;
+ let nextProgressUpdateGeneration = 0, latestAppliedProgressUpdateGeneration = 0;
+ let reconnectAttempts = 0, statusText = null;
+ `,
+ returnExpression: '({ initializeSocket })',
+ });
+ page.initializeSocket();
+ failInitialConnection();
+ await vi.advanceTimersByTimeAsync(6000);
+ // The page's initial 2 s check plus its sole 3 s interval (3 s and 6 s).
+ expect(window.api.getResearchStatus).toHaveBeenCalledTimes(3);
+ expect(Object.keys(window.pollIntervals)).toEqual([]);
+});
+
+it('never polls benchmark run IDs through the research API', async () => {
+ const pagePoll = vi.fn();
+ const page = compileTemplateHarness({
+ templatePath: source('templates/pages/benchmark.html'),
+ functionNames: ['startProgressTracking'],
+ dependencies: {
+ initializeCharts: vi.fn(), loadHistoricalChartData: vi.fn(),
+ updateBenchmarkProgress: pagePoll, handleDetailedProgress: vi.fn(),
+ },
+ preamble: `
+ let currentBenchmarkId = 42, progressInterval = null, progressRunGeneration = 0;
+ let progressStatusRequestId = 0, terminalBenchmarkRunGeneration = 0;
+ let hydratedTerminalBenchmarkRunGeneration = 0, recentResultsRequestId = 0;
+ let historicalChartRequestId = 0, searchQualityRequestId = 0;
+ let lastResultsUpdate = 0, lastChartsUpdate = 0, lastResultsData = null;
+ `,
+ returnExpression: '({ startProgressTracking })',
+ });
+ page.startProgressTracking();
+ await vi.advanceTimersByTimeAsync(500);
+ failInitialConnection();
+ await vi.advanceTimersByTimeAsync(5500);
+ expect(pagePoll).toHaveBeenCalledTimes(2);
+ expect(window.api.getResearchStatus).not.toHaveBeenCalled();
+ expect(Object.keys(window.pollIntervals)).toEqual([]);
+});
+
+it('retains generic fallback for a caller without a page poller', async () => {
+ window.api.getResearchStatus.mockResolvedValue(null);
+ service.subscribeToResearch('owner-run', () => {});
+ failInitialConnection();
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(window.api.getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(window.api.getResearchStatus).toHaveBeenCalledWith('owner-run');
+ service.unsubscribeFromResearch('owner-run');
+ await vi.advanceTimersByTimeAsync(6000);
+ expect(window.api.getResearchStatus).toHaveBeenCalledTimes(2);
+});
diff --git a/tests/js/services/socket-progress-frames.test.js b/tests/js/services/socket-progress-frames.test.js
new file mode 100644
index 0000000000..9a39965bf7
--- /dev/null
+++ b/tests/js/services/socket-progress-frames.test.js
@@ -0,0 +1,303 @@
+/**
+ * Runtime contracts for FastAPI progress frames consumed by socket.js.
+ *
+ * These tests enter through the real Socket.IO listener registered by the
+ * shared service. They cover error metadata, batched logs, deduplication,
+ * and safe fallback filtering without copying the production parser.
+ */
+
+function createMockSocket() {
+ const handlers = new Map();
+ return {
+ connected: true,
+ emit: vi.fn(),
+ disconnect: vi.fn(),
+ on: vi.fn((event, callback) => {
+ const callbacks = handlers.get(event) || [];
+ callbacks.push(callback);
+ handlers.set(event, callbacks);
+ }),
+ off: vi.fn(event => handlers.delete(event)),
+ fire(event, ...args) {
+ for (const callback of handlers.get(event) || []) callback(...args);
+ },
+ };
+}
+
+const synthesisCases = [
+ ['timeout', 'LLM Timeout Error'],
+ ['token_limit', 'Token Limit Exceeded'],
+ ['connection', 'LLM Connection Error'],
+ ['rate_limit', 'API Rate Limit Reached'],
+ ['unexpected_provider_error', 'LLM Synthesis Error'],
+];
+
+let service;
+let mockSocket;
+
+beforeAll(async () => {
+ vi.useFakeTimers();
+ vi.resetModules();
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: {
+ pathname: '/progress/socket-frame-contract',
+ protocol: 'http:',
+ host: 'localhost',
+ },
+ });
+
+ mockSocket = createMockSocket();
+ vi.stubGlobal('io', vi.fn(() => mockSocket));
+ window.api = {
+ getResearchStatus: vi.fn(),
+ getCsrfToken: () => '',
+ };
+ window.ResearchStates = {
+ isTerminal: status => ['completed', 'failed', 'cancelled'].includes(status),
+ logLevel: status => (status === 'failed' ? 'error' : 'info'),
+ };
+ window.addConsoleLog = vi.fn();
+ window.showNotification = vi.fn();
+ window.escapeHtml = value => String(value)
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#39;');
+
+ await import('@js/services/socket.js');
+ await vi.advanceTimersByTimeAsync(100);
+ service = window.socket;
+});
+
+beforeEach(() => {
+ vi.setSystemTime(new Date('2026-09-01T00:00:00Z'));
+ mockSocket.connected = true;
+ mockSocket.emit.mockClear();
+ mockSocket.off.mockClear();
+ window.addConsoleLog.mockClear();
+ window.showNotification.mockClear();
+ window._processedSocketMessages = new Map();
+ window.pollIntervals = {};
+ document.body.replaceChildren();
+});
+
+afterAll(() => {
+ service.disconnect();
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ delete window.api;
+ delete window.ResearchStates;
+ delete window.addConsoleLog;
+ delete window.showNotification;
+ delete window.escapeHtml;
+ delete window._processedSocketMessages;
+ delete window.pollIntervals;
+ document.body.replaceChildren();
+});
+
+it.each(synthesisCases)(
+ 'maps synthesis error type %s to its user-facing notification',
+ (errorType, expectedTitle) => {
+ const researchId = `synthesis-${errorType}`;
+ const consumer = vi.fn();
+ service.subscribeToResearch(researchId, consumer);
+
+ mockSocket.fire(`research_progress_${researchId}`, {
+ status: 'in_progress',
+ metadata: {
+ phase: 'synthesis_error',
+ error_type: errorType,
+ },
+ });
+
+ expect(window.showNotification).toHaveBeenCalledOnce();
+ expect(window.showNotification).toHaveBeenCalledWith(
+ expectedTitle,
+ expect.any(String),
+ 'error',
+ 10000,
+ );
+ expect(window.addConsoleLog).toHaveBeenNthCalledWith(
+ 1,
+ expect.stringContaining(expectedTitle),
+ 'error',
+ {
+ phase: 'synthesis_error',
+ error_type: errorType,
+ },
+ );
+ expect(window.addConsoleLog).toHaveBeenNthCalledWith(
+ 2,
+ expect.stringContaining('fallback mode'),
+ 'milestone',
+ { phase: 'synthesis_fallback' },
+ );
+ expect(consumer).toHaveBeenCalledOnce();
+
+ service.unsubscribeFromResearch(researchId);
+ },
+);
+
+it('normalizes, deduplicates, and expires logs before delivering the frame', () => {
+ vi.setSystemTime(new Date('2026-09-01T12:00:00Z'));
+ const researchId = 'batched-progress-logs';
+ const consumer = vi.fn();
+ const deliveredAt = vi.fn(() => window.addConsoleLog.mock.calls.length);
+ service.subscribeToResearch(researchId, data => {
+ deliveredAt();
+ consumer(data);
+ });
+ window._processedSocketMessages.set('expired-log', Date.now() - 301_000);
+ window._processedSocketMessages.set('t4-Duplicate log', Date.now());
+
+ const payload = {
+ status: 'in_progress',
+ progress_log: JSON.stringify([
+ {
+ time: 't1',
+ message: 'Iteration complete',
+ metadata: { phase: 'iteration_complete' },
+ },
+ {
+ time: 't2',
+ message: 'Provider failed',
+ metadata: { type: 'error' },
+ },
+ { time: 't3', message: 'Ordinary update' },
+ { time: 't4', message: 'Duplicate log' },
+ { time: 't5' },
+ ]),
+ };
+ mockSocket.fire(`research_progress_${researchId}`, payload);
+
+ expect(window.addConsoleLog.mock.calls.map(([message, type]) => (
+ [message, type]
+ ))).toEqual([
+ ['Iteration complete', 'milestone'],
+ ['Provider failed', 'error'],
+ ['Ordinary update', 'info'],
+ ]);
+ expect(deliveredAt).toHaveReturnedWith(3);
+ expect(consumer).toHaveBeenCalledWith(payload);
+ expect(window._processedSocketMessages.has('expired-log')).toBe(false);
+ expect(window._processedSocketMessages.has('t4-Duplicate log')).toBe(true);
+
+ service.unsubscribeFromResearch(researchId);
+});
+
+it('deduplicates direct log entries without suppressing progress consumers', () => {
+ const researchId = 'direct-progress-log';
+ const consumer = vi.fn();
+ const payload = {
+ log_entry: {
+ time: '2026-09-01T12:00:00Z',
+ message: 'Queued by FastAPI',
+ metadata: { type: 'milestone' },
+ },
+ };
+ service.subscribeToResearch(researchId, consumer);
+
+ mockSocket.fire(`research_progress_${researchId}`, payload);
+ mockSocket.fire(`research_progress_${researchId}`, payload);
+
+ expect(window.addConsoleLog).toHaveBeenCalledOnce();
+ expect(window.addConsoleLog).toHaveBeenCalledWith(
+ 'Queued by FastAPI',
+ 'milestone',
+ { type: 'milestone' },
+ );
+ expect(consumer).toHaveBeenCalledTimes(2);
+
+ service.unsubscribeFromResearch(researchId);
+});
+
+it('contains a malformed progress_log and still delivers the status frame', () => {
+ const researchId = 'malformed-progress-log';
+ const consumer = vi.fn();
+ const errorLog = vi.spyOn(SafeLogger, 'error');
+ service.subscribeToResearch(researchId, consumer);
+
+ const payload = {
+ status: 'in_progress',
+ progress: 38,
+ progress_log: '{not-json',
+ };
+ expect(() => {
+ mockSocket.fire(`research_progress_${researchId}`, payload);
+ }).not.toThrow();
+
+ expect(errorLog).toHaveBeenCalledWith(
+ 'Error processing progress_log:',
+ expect.any(SyntaxError),
+ );
+ expect(consumer).toHaveBeenCalledWith(payload);
+
+ service.unsubscribeFromResearch(researchId);
+ errorLog.mockRestore();
+});
+
+it('adapts the standalone FastAPI engine-selection event for the log panel', () => {
+ mockSocket.fire('search_engine_selected', {
+ engine: 'serper',
+ result_count: 9,
+ });
+
+ expect(window.addConsoleLog).toHaveBeenCalledOnce();
+ expect(window.addConsoleLog).toHaveBeenCalledWith(
+ 'Search engine selected: Serper (found 9 results)',
+ 'info',
+ {
+ type: 'info',
+ phase: 'engine_selected',
+ engine: 'serper',
+ result_count: 9,
+ is_engine_selection: true,
+ },
+ );
+});
+
+it('delegates filtering to a later log-panel override without recursing', () => {
+ const serviceFilter = window.filterLogsByType;
+ const logPanelFilter = vi.fn();
+ window.filterLogsByType = logPanelFilter;
+
+ try {
+ serviceFilter('error');
+ expect(logPanelFilter).toHaveBeenCalledOnce();
+ expect(logPanelFilter).toHaveBeenCalledWith('error');
+ } finally {
+ window.filterLogsByType = serviceFilter;
+ }
+});
+
+it('renders an empty filter message without interpreting an untrusted type', () => {
+ const hostileType = '<img src=x onerror="window.__socketXss=true">';
+ document.body.innerHTML = `
+ <div class="ldr-filter-buttons">
+ <button class="ldr-small-btn">All</button>
+ </div>
+ <section id="console-log-container">
+ <article class="ldr-console-log-entry" data-log-type="info">
+ <span class="ldr-log-badge">Info</span>
+ </article>
+ </section>
+ `;
+
+ window.filterLogsByType(hostileType);
+
+ const container = document.getElementById('console-log-container');
+ expect(container.querySelector('.ldr-console-log-entry').style.display)
+ .toBe('none');
+ expect(container.querySelector('.ldr-empty-log-message').textContent)
+ .toContain(hostileType);
+ expect(container.querySelector('img')).toBeNull();
+ expect(window.__socketXss).toBeUndefined();
+
+ window.filterLogsByType('all');
+ expect(container.querySelector('.ldr-console-log-entry').style.display)
+ .toBe('');
+ expect(container.querySelector('.ldr-empty-log-message')).toBeNull();
+});
diff --git a/tests/js/services/socket.test.js b/tests/js/services/socket.test.js
index 0f5c824c41..c9c9af81af 100644
--- a/tests/js/services/socket.test.js
+++ b/tests/js/services/socket.test.js
@@ -21,7 +21,9 @@ function createMockSocket() {
handlers[event] ||= [];
handlers[event].push(cb);
}),
- off: vi.fn(),
+ off: vi.fn((event) => {
+ delete handlers[event];
+ }),
// Test helper — simulate an event from the server.
_fire(event, ...args) {
(handlers[event] || []).forEach((cb) => cb(...args));
@@ -50,6 +52,11 @@ beforeAll(async () => {
await import('@js/services/socket.js');
socketModule = window.socket;
+
+ // socket.js schedules its eager progress-page bootstrap 100 ms after
+ // import. Wait for it here so the real timer cannot outlive this test
+ // environment and fire after jsdom has torn down `window`.
+ await vi.waitFor(() => expect(globalThis.io).toHaveBeenCalledOnce());
});
beforeEach(() => {
@@ -62,6 +69,16 @@ beforeEach(() => {
});
describe('subscribeToResearch — page-load race', () => {
+ it('exports the lifecycle API consumed by the benchmark page', () => {
+ expect(socketModule.init).toEqual(expect.any(Function));
+ expect(socketModule.getSocketInstance).toEqual(expect.any(Function));
+
+ // Exercise the checked-in service rather than a benchmark-page mock:
+ // init is idempotent and the getter returns that same live instance.
+ expect(socketModule.init()).toBe(mockSocket);
+ expect(socketModule.getSocketInstance()).toBe(mockSocket);
+ });
+
it('does not fall back to polling when socket exists but is mid-connect', () => {
// Simulate the page-load state: io() has been called (so socket
// exists) but the websocket handshake hasn't completed yet.
@@ -84,6 +101,137 @@ describe('subscribeToResearch — page-load race', () => {
expect(emittedEvents).not.toContain('join');
});
+ it('listens on the FastAPI research_progress_{id} channel and forwards data', () => {
+ mockSocket.connected = true;
+ const callback = vi.fn();
+
+ socketModule.subscribeToResearch('research-events', callback);
+
+ expect(mockSocket.off).toHaveBeenCalledWith(
+ 'research_progress_research-events'
+ );
+ expect(mockSocket.on).toHaveBeenCalledWith(
+ 'research_progress_research-events',
+ expect.any(Function)
+ );
+ const listenerNames = mockSocket.on.mock.calls.map(([event]) => event);
+ expect(listenerNames).not.toContain('progress_research-events');
+
+ const payload = { status: 'in_progress', progress: 42 };
+ mockSocket._fire('research_progress_research-events', payload);
+
+ expect(callback).toHaveBeenCalledTimes(1);
+ expect(callback).toHaveBeenCalledWith(payload);
+ });
+
+ it('falls back to polling only for a matching FastAPI subscribe_error', () => {
+ const researchId = 'research-subscribe-error';
+ const pollResearchStatus = vi.fn();
+ window.pollResearchStatus = pollResearchStatus;
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(researchId, () => {});
+
+ // The FastAPI protocol always scopes this event. Treat an
+ // unscoped packet as malformed instead of assigning it to the
+ // currently active run.
+ mockSocket._fire('subscribe_error', {
+ error: 'Unscoped subscription failure',
+ });
+ mockSocket._fire('subscribe_error', {
+ error: 'Not authorized',
+ research_id: 'previous-research',
+ });
+
+ expect(pollResearchStatus).not.toHaveBeenCalled();
+ expect(socketModule.isUsingPolling()).toBe(false);
+
+ mockSocket._fire('subscribe_error', {
+ error: 'Not authorized',
+ research_id: researchId,
+ });
+
+ expect(pollResearchStatus).toHaveBeenCalledOnce();
+ expect(pollResearchStatus).toHaveBeenCalledWith(researchId);
+ expect(socketModule.isUsingPolling()).toBe(true);
+
+ // Expired sessions emit subscribe_error immediately before the
+ // server disconnects the socket. That second signal must not
+ // start another polling loop for the same research.
+ mockSocket._fire('disconnect', 'io server disconnect');
+ mockSocket._fire('error', new Error('late transport error'));
+ expect(pollResearchStatus).toHaveBeenCalledOnce();
+ } finally {
+ mockSocket._fire('connect');
+ socketModule.unsubscribeFromResearch(researchId);
+ delete window.pollResearchStatus;
+ }
+ });
+
+ it('matches numeric room IDs to string IDs in FastAPI subscribe_error payloads', () => {
+ const pollResearchStatus = vi.fn();
+ window.pollResearchStatus = pollResearchStatus;
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(42, () => {});
+
+ // FastAPI serializes identifiers in event payloads, while page
+ // callers may retain the numeric route parameter. The rejected
+ // active room must still enter fallback exactly once.
+ mockSocket._fire('subscribe_error', {
+ error: 'Not authorized',
+ research_id: '42',
+ });
+ mockSocket._fire('disconnect', 'io server disconnect');
+
+ expect(pollResearchStatus).toHaveBeenCalledOnce();
+ expect(pollResearchStatus).toHaveBeenCalledWith(42);
+ expect(socketModule.isUsingPolling()).toBe(true);
+ } finally {
+ mockSocket._fire('connect');
+ socketModule.unsubscribeFromResearch(42);
+ delete window.pollResearchStatus;
+ }
+ });
+
+ it('starts a fresh fallback after leaving a previously rejected research', () => {
+ const firstResearchId = 'research-subscribe-error-a';
+ const secondResearchId = 'research-subscribe-error-b';
+ const pollResearchStatus = vi.fn();
+ window.pollResearchStatus = pollResearchStatus;
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(firstResearchId, () => {});
+ mockSocket._fire('subscribe_error', {
+ error: 'Not authorized',
+ research_id: firstResearchId,
+ });
+
+ // The server may close the transport after rejecting A. Leaving
+ // A must clear its poll without pretending the transport has
+ // recovered; B then needs an immediate polling fallback.
+ mockSocket.connected = false;
+ mockSocket._fire('disconnect', 'io server disconnect');
+ socketModule.unsubscribeFromResearch(firstResearchId);
+
+ socketModule.subscribeToResearch(secondResearchId, () => {});
+
+ expect(pollResearchStatus.mock.calls).toEqual([
+ [firstResearchId],
+ [secondResearchId],
+ ]);
+ expect(socketModule.isUsingPolling()).toBe(true);
+ } finally {
+ mockSocket.connected = true;
+ mockSocket._fire('connect');
+ socketModule.unsubscribeFromResearch(secondResearchId);
+ delete window.pollResearchStatus;
+ }
+ });
+
it('clears stale polling intervals when the socket connects', () => {
// Simulate a leftover polling interval from a fallback path.
const intervalId = setInterval(() => {}, 9999);
@@ -116,6 +264,143 @@ describe('subscribeToResearch — page-load race', () => {
expect(subscribeCalls.length).toBe(1);
expect(subscribeCalls[0][1]).toEqual({ research_id: 'research-deferred' });
});
+
+ it('returns from polling fallback to the canonical websocket channel', () => {
+ const researchId = 'research-recovery';
+ const pollResearchStatus = vi.fn((id) => {
+ window.pollIntervals[id] = setInterval(() => {}, 9999);
+ });
+ window.pollResearchStatus = pollResearchStatus;
+
+ try {
+ socketModule.subscribeToResearch(researchId, () => {});
+
+ mockSocket._fire('connect_error', new Error('attempt 1'));
+ mockSocket._fire('connect_error', new Error('attempt 2'));
+ expect(pollResearchStatus).not.toHaveBeenCalled();
+
+ mockSocket._fire('connect_error', new Error('attempt 3'));
+ expect(pollResearchStatus).toHaveBeenCalledOnce();
+ expect(pollResearchStatus).toHaveBeenCalledWith(researchId);
+ expect(window.pollIntervals[researchId]).toBeDefined();
+
+ mockSocket.connected = true;
+ mockSocket._fire('connect');
+
+ expect(window.pollIntervals).toEqual({});
+ expect(mockSocket.emit).toHaveBeenCalledWith(
+ 'subscribe_to_research',
+ { research_id: researchId }
+ );
+ expect(mockSocket.off).toHaveBeenCalledWith(
+ `research_progress_${researchId}`
+ );
+ expect(mockSocket.on).toHaveBeenCalledWith(
+ `research_progress_${researchId}`,
+ expect.any(Function)
+ );
+ } finally {
+ if (window.pollIntervals[researchId]) {
+ clearInterval(window.pollIntervals[researchId]);
+ delete window.pollIntervals[researchId];
+ }
+ delete window.pollResearchStatus;
+ }
+ });
+
+ it('delivers a terminal fallback poll and removes its completed interval', async () => {
+ const researchId = 'research-terminal-poll';
+ const callback = vi.fn();
+ const terminalPayload = { status: 'completed', progress: 100 };
+ const originalIsTerminal = window.ResearchStates.isTerminal;
+
+ vi.useFakeTimers();
+ delete window.pollResearchStatus;
+ window.ResearchStates.isTerminal = vi.fn(
+ status => status === 'completed',
+ );
+ window.api.getResearchStatus.mockResolvedValueOnce(terminalPayload);
+
+ try {
+ mockSocket.connected = true;
+ socketModule.subscribeToResearch(researchId, callback);
+
+ // Losing the migrated websocket transport starts socket.js's own
+ // HTTP fallback when the page did not provide a polling helper.
+ mockSocket.connected = false;
+ mockSocket._fire('disconnect', 'transport close');
+
+ expect(window.pollIntervals[researchId]).toBeDefined();
+ expect(window.api.getResearchStatus).not.toHaveBeenCalled();
+
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(window.api.getResearchStatus).toHaveBeenCalledOnce();
+ expect(window.api.getResearchStatus).toHaveBeenCalledWith(researchId);
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).toHaveBeenCalledWith(terminalPayload);
+ // A terminal FastAPI status must retire the timer and its public
+ // bookkeeping entry; otherwise every completed run keeps polling.
+ expect(window.pollIntervals).toEqual({});
+ } finally {
+ if (window.pollIntervals[researchId]) {
+ clearInterval(window.pollIntervals[researchId]);
+ delete window.pollIntervals[researchId];
+ }
+ // Test cleanup deliberately restores the shared transport after
+ // awaiting the fake-timer callback above.
+ // eslint-disable-next-line require-atomic-updates
+ mockSocket.connected = true;
+ mockSocket._fire('connect');
+ socketModule.unsubscribeFromResearch(researchId);
+ window.ResearchStates.isTerminal = originalIsTerminal;
+ window.api.getResearchStatus.mockReset();
+ delete window.pollResearchStatus;
+ vi.useRealTimers();
+ }
+ });
+
+ it('isolates progress handlers so one broken consumer cannot block the others', () => {
+ const researchId = 'research-handler-isolation';
+ const brokenHandler = vi.fn(() => {
+ throw new Error('consumer render failed');
+ });
+ const healthyHandler = vi.fn();
+ const payload = { status: 'in_progress', progress: 61 };
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(researchId, brokenHandler);
+ socketModule.subscribeToResearch(researchId, healthyHandler);
+
+ expect(() => {
+ mockSocket._fire(`research_progress_${researchId}`, payload);
+ }).not.toThrow();
+ expect(brokenHandler).toHaveBeenCalledOnce();
+ expect(healthyHandler).toHaveBeenCalledOnce();
+ expect(healthyHandler).toHaveBeenCalledWith(payload);
+ } finally {
+ socketModule.unsubscribeFromResearch(researchId);
+ }
+ });
+
+ it('does not register the same progress consumer twice', () => {
+ const researchId = 'research-handler-dedup';
+ const handler = vi.fn();
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(researchId, handler);
+ socketModule.subscribeToResearch(researchId, handler);
+ mockSocket._fire(`research_progress_${researchId}`, {
+ status: 'in_progress',
+ });
+
+ expect(handler).toHaveBeenCalledOnce();
+ } finally {
+ socketModule.unsubscribeFromResearch(researchId);
+ }
+ });
});
describe('unsubscribeFromResearch', () => {
@@ -125,12 +410,66 @@ describe('unsubscribeFromResearch', () => {
// First subscribe so there's something to leave.
socketModule.subscribeToResearch('research-4', () => {});
mockSocket.emit.mockClear();
+ mockSocket.off.mockClear();
socketModule.unsubscribeFromResearch('research-4');
const emittedEvents = mockSocket.emit.mock.calls.map((c) => c[0]);
expect(emittedEvents).toContain('unsubscribe_from_research');
expect(emittedEvents).not.toContain('leave');
+ expect(mockSocket.off).toHaveBeenCalledWith(
+ 'research_progress_research-4'
+ );
+ expect(mockSocket.off).not.toHaveBeenCalledWith('progress_research-4');
+ });
+
+ it('keeps the newer room active when an older room is unsubscribed', () => {
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch('research-old', () => {});
+ socketModule.subscribeToResearch('research-current', () => {});
+ socketModule.unsubscribeFromResearch('research-old');
+ mockSocket.emit.mockClear();
+
+ // A reconnect must restore the current room, not the stale room
+ // whose page cleanup arrived after the newer subscription.
+ mockSocket._fire('connect');
+
+ const roomSubscriptions = mockSocket.emit.mock.calls.filter(
+ ([event]) => event === 'subscribe_to_research'
+ );
+ expect(roomSubscriptions).toEqual([
+ [
+ 'subscribe_to_research',
+ { research_id: 'research-current' },
+ ],
+ ]);
+ } finally {
+ socketModule.unsubscribeFromResearch('research-current');
+ }
+ });
+
+ it('treats numeric and string room IDs as the same unsubscribe owner', () => {
+ mockSocket.connected = true;
+
+ try {
+ socketModule.subscribeToResearch(3299, () => {});
+ socketModule.unsubscribeFromResearch('3299');
+ mockSocket.emit.mockClear();
+
+ // FastAPI event payloads commonly stringify identifiers. Once the
+ // equivalent string ID leaves, reconnect must not resurrect the
+ // numerically supplied room.
+ mockSocket._fire('connect');
+
+ expect(mockSocket.emit).not.toHaveBeenCalledWith(
+ 'subscribe_to_research',
+ expect.anything(),
+ );
+ } finally {
+ socketModule.unsubscribeFromResearch(3299);
+ }
});
});
diff --git a/tests/js/services/socket_lazy_chat.test.js b/tests/js/services/socket_lazy_chat.test.js
index fedb6c1e76..920fb91567 100644
--- a/tests/js/services/socket_lazy_chat.test.js
+++ b/tests/js/services/socket_lazy_chat.test.js
@@ -35,6 +35,7 @@ describe('Socket.IO auto-connect gating (#4431)', () => {
afterEach(() => {
vi.useRealTimers();
delete globalThis.io;
+ delete window.pollResearchStatus;
});
it('does NOT auto-connect on a /chat/ page (lazy)', async () => {
@@ -50,10 +51,17 @@ describe('Socket.IO auto-connect gating (#4431)', () => {
await import('@js/services/socket.js');
vi.advanceTimersByTime(300);
expect(io).toHaveBeenCalledTimes(1);
+ expect(io).toHaveBeenCalledWith(
+ 'http://localhost',
+ expect.objectContaining({
+ path: '/ws/socket.io',
+ transports: ['websocket', 'polling'],
+ }),
+ );
});
- it('DOES auto-connect on a /research page (eager, unchanged)', async () => {
- const io = setupEnv('/research');
+ it('DOES auto-connect on the live root research page', async () => {
+ const io = setupEnv('/');
await import('@js/services/socket.js');
vi.advanceTimersByTime(300);
expect(io).toHaveBeenCalledTimes(1);
@@ -69,4 +77,24 @@ describe('Socket.IO auto-connect gating (#4431)', () => {
window.socket.subscribeToResearch('research-1', () => {});
expect(io).toHaveBeenCalledTimes(1);
});
+
+ it('starts polling when the lazy Socket.IO initialization throws', async () => {
+ const io = setupEnv('/chat/some-session-id');
+ io.mockImplementation(() => {
+ throw new Error('Socket.IO client unavailable');
+ });
+ const pollResearchStatus = vi.fn();
+ window.pollResearchStatus = pollResearchStatus;
+
+ await import('@js/services/socket.js');
+ vi.advanceTimersByTime(300);
+ expect(io).not.toHaveBeenCalled();
+
+ window.socket.subscribeToResearch('research-fallback', () => {});
+
+ expect(io).toHaveBeenCalledOnce();
+ expect(pollResearchStatus).toHaveBeenCalledOnce();
+ expect(pollResearchStatus).toHaveBeenCalledWith('research-fallback');
+ expect(window.socket.isUsingPolling()).toBe(true);
+ });
});
diff --git a/tests/js/services/socket_polling_terminal.test.js b/tests/js/services/socket_polling_terminal.test.js
new file mode 100644
index 0000000000..81602c5d67
--- /dev/null
+++ b/tests/js/services/socket_polling_terminal.test.js
@@ -0,0 +1,357 @@
+/**
+ * Runtime contracts for Socket.IO's FastAPI polling fallback ownership.
+ *
+ * These use the service's real fallback interval rather than injecting the
+ * page-level pollResearchStatus helper. That exercises the terminal cleanup
+ * and the late-response guard added for the migration's reconnect paths.
+ */
+
+function deferred() {
+ let resolve;
+ const promise = new Promise(res => {
+ resolve = res;
+ });
+ return { promise, resolve };
+}
+
+function createMockSocket() {
+ const handlers = {};
+ return {
+ connected: false,
+ emit: vi.fn(),
+ on: vi.fn((event, callback) => {
+ handlers[event] ||= [];
+ handlers[event].push(callback);
+ }),
+ off: vi.fn(),
+ disconnect: vi.fn(),
+ fire(event, ...args) {
+ (handlers[event] || []).forEach(callback => callback(...args));
+ },
+ };
+}
+
+async function loadSocketService(getResearchStatus) {
+ vi.resetModules();
+ Object.defineProperty(window, 'location', {
+ configurable: true,
+ value: {
+ pathname: '/progress/polling-contract',
+ protocol: 'http:',
+ host: 'localhost',
+ },
+ });
+
+ const socket = createMockSocket();
+ globalThis.io = vi.fn(() => socket);
+ window.api = {
+ getResearchStatus,
+ getCsrfToken: () => '',
+ };
+ window.ResearchStates = {
+ isTerminal: status => ['completed', 'failed', 'cancelled'].includes(status),
+ logLevel: () => 'info',
+ };
+ delete window.pollResearchStatus;
+ window.pollIntervals = {};
+
+ await import('@js/services/socket.js');
+ await vi.advanceTimersByTimeAsync(300);
+ expect(globalThis.io).toHaveBeenCalledOnce();
+
+ return { service: window.socket, socket };
+}
+
+function failSocketIntoPolling(service, socket, researchId) {
+ service.subscribeToResearch(researchId, () => {});
+ socket.fire('connect_error', new Error('attempt 1'));
+ socket.fire('connect_error', new Error('attempt 2'));
+ socket.fire('connect_error', new Error('attempt 3'));
+}
+
+describe('socket polling fallback terminal ownership', () => {
+ let service;
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ service?.disconnect();
+ vi.useRealTimers();
+ delete globalThis.io;
+ delete window.pollResearchStatus;
+ delete window.pollIntervals;
+ delete window.ResearchStates;
+ service = undefined;
+ });
+
+ it('does not let a late terminal response release the newer research poll', async () => {
+ const oldResponse = deferred();
+ const getResearchStatus = vi.fn(researchId => {
+ if (researchId === 'research-old') return oldResponse.promise;
+ return new Promise(() => {});
+ });
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ failSocketIntoPolling(service, loaded.socket, 'research-old');
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ expect(getResearchStatus).toHaveBeenCalledWith('research-old');
+
+ service.unsubscribeFromResearch('research-old');
+ service.subscribeToResearch('research-current', () => {});
+ const currentInterval = window.pollIntervals['research-current'];
+ expect(currentInterval).toBeDefined();
+
+ oldResponse.resolve({ status: 'completed', progress: 100 });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ // A later transport signal asks for fallback again. If the stale A
+ // response incorrectly released B's private polling ownership, this
+ // would allocate a second interval and overwrite the registry entry.
+ loaded.socket.fire('disconnect', 'late transport close');
+
+ expect(window.pollIntervals['research-current']).toBe(currentInterval);
+ expect(service.isUsingPolling()).toBe(true);
+ });
+
+ it('keeps the current fallback alive when an older room cleans up late', async () => {
+ const currentCallback = vi.fn();
+ const getResearchStatus = vi.fn(researchId => {
+ if (researchId === 'research-current') {
+ return Promise.resolve({ status: 'completed', progress: 100 });
+ }
+ return new Promise(() => {});
+ });
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ failSocketIntoPolling(service, loaded.socket, 'research-old');
+ service.subscribeToResearch('research-current', currentCallback);
+
+ expect(window.pollIntervals['research-old']).toBeDefined();
+ expect(window.pollIntervals['research-current']).toBeDefined();
+
+ // Page cleanup for A may arrive after B already owns the service. It
+ // must retire only A's fallback generation, not B's.
+ service.unsubscribeFromResearch('research-old');
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(getResearchStatus).toHaveBeenCalledWith('research-current');
+ expect(currentCallback).toHaveBeenCalledOnce();
+ expect(currentCallback).toHaveBeenCalledWith({
+ status: 'completed',
+ progress: 100,
+ });
+ expect(window.pollIntervals['research-current']).toBeUndefined();
+ });
+
+ it('keeps a fallback started synchronously by a terminal callback alive', async () => {
+ const currentCallback = vi.fn();
+ const getResearchStatus = vi.fn(researchId => Promise.resolve(
+ researchId === 'research-old'
+ ? { status: 'completed', progress: 100 }
+ : { status: 'in_progress', progress: 40 },
+ ));
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ service.subscribeToResearch('research-old', () => {
+ service.unsubscribeFromResearch('research-old');
+ service.subscribeToResearch('research-current', currentCallback);
+ });
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(window.pollIntervals['research-current']).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(getResearchStatus).toHaveBeenCalledWith('research-current');
+ expect(currentCallback).toHaveBeenCalledOnce();
+ expect(currentCallback).toHaveBeenCalledWith({
+ status: 'in_progress',
+ progress: 40,
+ });
+ expect(window.pollIntervals['research-current']).toBeDefined();
+ });
+
+ it('polls a later subscription when the transport failed before a room was known', async () => {
+ const getResearchStatus = vi.fn(() => new Promise(() => {}));
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ // Eager connection attempts can be exhausted before a page component
+ // discovers its research id. That state must arm, rather than lose,
+ // the first subsequent subscription's HTTP fallback.
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+ expect(service.isUsingPolling()).toBe(true);
+ expect(window.pollIntervals).toEqual({});
+
+ service.subscribeToResearch('research-discovered-late', () => {});
+ expect(window.pollIntervals['research-discovered-late']).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(3000);
+ expect(getResearchStatus).toHaveBeenCalledOnce();
+ expect(getResearchStatus).toHaveBeenCalledWith(
+ 'research-discovered-late',
+ );
+ });
+
+ it('retries after a fallback request rejects and retires on terminal status', async () => {
+ const callback = vi.fn();
+ const getResearchStatus = vi.fn()
+ .mockRejectedValueOnce(new Error('temporary status outage'))
+ .mockResolvedValueOnce({ status: 'completed', progress: 100 });
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+ vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ service.subscribeToResearch('research-retry', callback);
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(getResearchStatus).toHaveBeenCalledOnce();
+ expect(callback).not.toHaveBeenCalled();
+ expect(window.pollIntervals['research-retry']).toBeDefined();
+
+ await vi.advanceTimersByTimeAsync(3000);
+
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).toHaveBeenCalledWith({
+ status: 'completed',
+ progress: 100,
+ });
+ expect(window.pollIntervals).toEqual({});
+ expect(service.isUsingPolling()).toBe(true);
+ });
+
+ it('ignores an in-flight fallback response after websocket recovery', async () => {
+ const stalePoll = deferred();
+ const callback = vi.fn();
+ const getResearchStatus = vi.fn(() => stalePoll.promise);
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ service.subscribeToResearch('research-reconnected', callback);
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ expect(getResearchStatus).toHaveBeenCalledOnce();
+
+ loaded.socket.connected = true;
+ loaded.socket.fire('connect');
+ loaded.socket.fire('research_progress_research-reconnected', {
+ status: 'in_progress',
+ progress: 80,
+ });
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).toHaveBeenLastCalledWith({
+ status: 'in_progress',
+ progress: 80,
+ });
+
+ stalePoll.resolve({ status: 'in_progress', progress: 20 });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(callback).toHaveBeenCalledOnce();
+ expect(window.pollIntervals).toEqual({});
+ expect(service.isUsingPolling()).toBe(false);
+ });
+
+ it('does not regress when fallback polls for one run resolve out of order', async () => {
+ const olderPoll = deferred();
+ const newerPoll = deferred();
+ const callback = vi.fn();
+ const getResearchStatus = vi.fn()
+ .mockImplementationOnce(() => olderPoll.promise)
+ .mockImplementationOnce(() => newerPoll.promise)
+ .mockImplementation(() => new Promise(() => {}));
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ service.subscribeToResearch('research-overlap', callback);
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+
+ newerPoll.resolve({ status: 'in_progress', progress: 70 });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).toHaveBeenLastCalledWith({
+ status: 'in_progress',
+ progress: 70,
+ });
+
+ olderPoll.resolve({ status: 'in_progress', progress: 20 });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).not.toHaveBeenCalledWith({
+ status: 'in_progress',
+ progress: 20,
+ });
+ });
+
+ it('applies an older-request terminal snapshot after a newer nonterminal poll', async () => {
+ const terminalPoll = deferred();
+ const newerPoll = deferred();
+ const callback = vi.fn();
+ const getResearchStatus = vi.fn()
+ .mockImplementationOnce(() => terminalPoll.promise)
+ .mockImplementationOnce(() => newerPoll.promise)
+ .mockImplementation(() => new Promise(() => {}));
+ const loaded = await loadSocketService(getResearchStatus);
+ service = loaded.service;
+
+ service.subscribeToResearch('research-terminal', callback);
+ loaded.socket.fire('connect_error', new Error('attempt 1'));
+ loaded.socket.fire('connect_error', new Error('attempt 2'));
+ loaded.socket.fire('connect_error', new Error('attempt 3'));
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ vi.advanceTimersByTime(3000);
+ await Promise.resolve();
+ expect(getResearchStatus).toHaveBeenCalledTimes(2);
+
+ newerPoll.resolve({ status: 'in_progress', progress: 70 });
+ await Promise.resolve();
+ await Promise.resolve();
+ expect(callback).toHaveBeenCalledOnce();
+ expect(callback).toHaveBeenLastCalledWith({
+ status: 'in_progress',
+ progress: 70,
+ });
+
+ terminalPoll.resolve({ status: 'completed', progress: 100 });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(callback).toHaveBeenCalledTimes(2);
+ expect(callback).toHaveBeenLastCalledWith({
+ status: 'completed',
+ progress: 100,
+ });
+ expect(window.pollIntervals).toEqual({});
+ });
+});
diff --git a/tests/js/services/theme-lifecycle-runtime.test.js b/tests/js/services/theme-lifecycle-runtime.test.js
new file mode 100644
index 0000000000..3a8e93e86e
--- /dev/null
+++ b/tests/js/services/theme-lifecycle-runtime.test.js
@@ -0,0 +1,205 @@
+/** Runtime coverage for theme identity, hydration, and browser lifecycle hooks. */
+
+const originalReadyState = Object.getOwnPropertyDescriptor(
+ document,
+ 'readyState',
+);
+const originalVisibilityState = Object.getOwnPropertyDescriptor(
+ document,
+ 'visibilityState',
+);
+
+const mediaListeners = [];
+const mediaQuery = {
+ matches: true,
+ addEventListener: vi.fn((event, callback) => {
+ if (event === 'change') mediaListeners.push(callback);
+ }),
+};
+
+let theme;
+
+beforeAll(async () => {
+ Object.defineProperty(document, 'readyState', {
+ configurable: true,
+ get: () => 'loading',
+ });
+ window.LDR_THEME_METADATA = {
+ hashed: { label: 'Hashed', icon: 'fa-hashtag', group: 'core' },
+ light: { label: 'Light', icon: 'fa-sun', group: 'core' },
+ nord: { label: 'Nord', icon: 'fa-snowflake', group: 'dev' },
+ dracula: { label: 'Dracula', icon: 'fa-ghost', group: 'dev' },
+ sepia: { label: 'Sepia', icon: 'fa-book', group: 'research' },
+ system: { label: 'System', icon: 'fa-desktop', group: 'system' },
+ };
+ vi.stubGlobal('matchMedia', vi.fn(() => mediaQuery));
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-theme-lifecycle') };
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
+ ok: false,
+ status: 404,
+ json: vi.fn().mockResolvedValue({}),
+ }));
+
+ await import('@js/services/theme.js');
+ theme = window.themeService;
+});
+
+beforeEach(() => {
+ localStorage.clear();
+ document.head.querySelectorAll('meta[name="user-id"]').forEach(node => (
+ node.remove()
+ ));
+ document.body.replaceChildren();
+ delete document.body.dataset.userId;
+ mediaQuery.matches = true;
+ mediaListeners.length = 0;
+ mediaQuery.addEventListener.mockClear();
+ window.api = { getCsrfToken: vi.fn(() => 'csrf-theme-lifecycle') };
+ vi.mocked(fetch).mockReset().mockResolvedValue({
+ ok: false,
+ status: 404,
+ json: vi.fn().mockResolvedValue({}),
+ });
+});
+
+afterAll(() => {
+ localStorage.clear();
+ document.body.replaceChildren();
+ delete window.LDR_THEME_METADATA;
+ delete window.api;
+ vi.unstubAllGlobals();
+ if (originalReadyState) {
+ Object.defineProperty(document, 'readyState', originalReadyState);
+ } else {
+ delete document.readyState;
+ }
+ if (originalVisibilityState) {
+ Object.defineProperty(
+ document,
+ 'visibilityState',
+ originalVisibilityState,
+ );
+ } else {
+ delete document.visibilityState;
+ }
+});
+
+it('isolates persisted themes by meta user, body user, and anonymous context', () => {
+ const meta = document.createElement('meta');
+ meta.name = 'user-id';
+ meta.content = ' alice ';
+ document.head.appendChild(meta);
+ document.body.dataset.userId = 'ignored-body-user';
+
+ theme.setTheme('light', false);
+ expect(localStorage.getItem('ldr-theme-alice')).toBe('light');
+
+ meta.remove();
+ document.body.dataset.userId = ' bob ';
+ expect(theme.getCurrentTheme()).toBe('system');
+ theme.setTheme('nord', false);
+ expect(localStorage.getItem('ldr-theme-bob')).toBe('nord');
+
+ delete document.body.dataset.userId;
+ expect(theme.getCurrentTheme()).toBe('system');
+ theme.setTheme('hashed', false);
+ expect(localStorage.getItem('ldr-theme-anonymous')).toBe('hashed');
+});
+
+it('hydrates a valid migrated setting and updates the live dropdown', async () => {
+ localStorage.setItem('ldr-theme-anonymous', 'light');
+ document.body.innerHTML = '<select id="theme-dropdown"></select>';
+ vi.mocked(fetch).mockResolvedValueOnce({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ value: 'nord' }),
+ });
+
+ theme.initializeTheme();
+
+ await vi.waitFor(() => {
+ expect(theme.getCurrentTheme()).toBe('nord');
+ });
+ expect(fetch).toHaveBeenCalledWith('/settings/api/app.theme');
+ expect(document.documentElement.dataset.theme).toBe('nord');
+ expect(document.getElementById('theme-dropdown').value).toBe('nord');
+ expect(document.querySelectorAll('#theme-dropdown option')).toHaveLength(
+ Object.keys(window.LDR_THEME_METADATA).length,
+ );
+ expect(mediaQuery.addEventListener).toHaveBeenCalledWith(
+ 'change',
+ expect.any(Function),
+ );
+});
+
+it('resets a corrupted stored theme before server hydration settles', () => {
+ localStorage.setItem('ldr-theme-anonymous', 'javascript:alert(1)');
+ vi.mocked(fetch).mockImplementationOnce(() => new Promise(() => {}));
+
+ theme.initializeTheme();
+
+ expect(theme.getCurrentTheme()).toBe('hashed');
+ expect(document.documentElement.dataset.theme).toBe('hashed');
+});
+
+it('reacts to a system color-scheme change only for the system preference', () => {
+ theme.setTheme('system', false);
+ expect(theme.getEffectiveTheme('system')).toBe('hashed');
+ theme.initializeTheme();
+ expect(mediaListeners).toHaveLength(1);
+
+ mediaQuery.matches = false;
+ mediaListeners[0]();
+ expect(document.documentElement.dataset.theme).toBe('sepia');
+
+ theme.setTheme('nord', false);
+ mediaQuery.matches = true;
+ mediaListeners[0]();
+ expect(document.documentElement.dataset.theme).toBe('nord');
+});
+
+it('wires one dropdown change to the migrated settings PUT with CSRF', async () => {
+ document.body.innerHTML = '<select id="theme-dropdown"></select>';
+ vi.mocked(fetch).mockResolvedValue({
+ ok: true,
+ status: 200,
+ json: vi.fn().mockResolvedValue({ status: 'success' }),
+ });
+ theme.setupHeaderDropdown();
+ theme.setupHeaderDropdown();
+
+ const dropdown = document.getElementById('theme-dropdown');
+ dropdown.value = 'dracula';
+ dropdown.dispatchEvent(new Event('change'));
+
+ await vi.waitFor(() => {
+ expect(fetch).toHaveBeenCalledOnce();
+ });
+ expect(fetch).toHaveBeenCalledWith('/settings/api/app.theme', {
+ method: 'PUT',
+ headers: {
+ 'Content-Type': 'application/json',
+ 'X-CSRFToken': 'csrf-theme-lifecycle',
+ },
+ body: JSON.stringify({ value: 'dracula' }),
+ });
+ expect(theme.getCurrentTheme()).toBe('dracula');
+});
+
+it('repopulates an empty dropdown after bfcache restore and tab visibility', () => {
+ document.body.innerHTML = '<select id="theme-dropdown"></select>';
+ const dropdown = document.getElementById('theme-dropdown');
+ const pageShow = new Event('pageshow');
+ Object.defineProperty(pageShow, 'persisted', { value: true });
+
+ window.dispatchEvent(pageShow);
+ expect(dropdown.options.length).toBeGreaterThan(0);
+
+ dropdown.replaceChildren();
+ Object.defineProperty(document, 'visibilityState', {
+ configurable: true,
+ get: () => 'visible',
+ });
+ document.dispatchEvent(new Event('visibilitychange'));
+
+ expect(dropdown.options.length).toBeGreaterThan(0);
+});
diff --git a/tests/js/services/theme.test.js b/tests/js/services/theme.test.js
index 7bafb92a26..0da2aa9161 100644
--- a/tests/js/services/theme.test.js
+++ b/tests/js/services/theme.test.js
@@ -1,9 +1,7 @@
/**
* Tests for services/theme.js
*
- * Tests theme resolution, validation, cycling, and storage.
- * Network calls (server sync) are not tested here as they
- * require a running backend.
+ * Tests theme resolution, validation, storage, and settings API ownership.
*/
// Theme metadata must be set BEFORE the module IIFE runs.
@@ -11,6 +9,20 @@
let theme;
+function deferred() {
+ let resolvePromise;
+ let rejectPromise;
+ const promise = new Promise((resolve, reject) => {
+ resolvePromise = resolve;
+ rejectPromise = reject;
+ });
+ return {
+ promise,
+ resolve: resolvePromise,
+ reject: rejectPromise,
+ };
+}
+
beforeAll(async () => {
// Set up theme metadata before loading the module
window.LDR_THEME_METADATA = {
@@ -212,5 +224,85 @@ describe('themeService', () => {
await expect(theme.saveThemeToServer('nord')).resolves.toBeUndefined();
});
+
+ it('serializes rapid PUTs so the latest theme reaches the server last', async () => {
+ window.api.getCsrfToken = () => 'csrf-test-123';
+ const olderSave = deferred();
+ const newerSave = deferred();
+ globalThis.fetch = vi.fn()
+ .mockImplementationOnce(() => olderSave.promise)
+ .mockImplementationOnce(() => newerSave.promise);
+
+ const olderRequest = theme.saveThemeToServer('light');
+ const newerRequest = theme.saveThemeToServer('nord');
+ await Promise.resolve();
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ expect(JSON.parse(globalThis.fetch.mock.calls[0][1].body))
+ .toEqual({ value: 'light' });
+
+ olderSave.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'success' }),
+ });
+ await olderRequest;
+ await Promise.resolve();
+
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
+ expect(JSON.parse(globalThis.fetch.mock.calls[1][1].body))
+ .toEqual({ value: 'nord' });
+
+ newerSave.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'success' }),
+ });
+ await newerRequest;
+ });
+
+ it('continues the save queue when an older theme write rejects', async () => {
+ window.api.getCsrfToken = () => 'csrf-test-123';
+ const olderSave = deferred();
+ const newerSave = deferred();
+ globalThis.fetch = vi.fn()
+ .mockImplementationOnce(() => olderSave.promise)
+ .mockImplementationOnce(() => newerSave.promise);
+
+ const olderRequest = theme.saveThemeToServer('light');
+ const newerRequest = theme.saveThemeToServer('dracula');
+ await Promise.resolve();
+
+ expect(globalThis.fetch).toHaveBeenCalledOnce();
+ olderSave.reject(new Error('theme service offline'));
+ await olderRequest;
+ await vi.waitFor(() => {
+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);
+ });
+ expect(JSON.parse(globalThis.fetch.mock.calls[1][1].body))
+ .toEqual({ value: 'dracula' });
+
+ newerSave.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ status: 'success' }),
+ });
+ await newerRequest;
+ });
+ });
+
+ it('does not let delayed server hydration undo a newer user theme', async () => {
+ const staleHydration = deferred();
+ globalThis.fetch = vi.fn(() => staleHydration.promise);
+
+ theme.initializeTheme();
+ theme.setTheme('nord', false);
+ staleHydration.resolve({
+ ok: true,
+ json: vi.fn().mockResolvedValue({ value: 'light' }),
+ });
+ await Promise.resolve();
+ await Promise.resolve();
+ await Promise.resolve();
+
+ expect(theme.getCurrentTheme()).toBe('nord');
+ expect(document.documentElement.getAttribute('data-theme')).toBe('nord');
});
});
diff --git a/tests/js/services/ui.test.js b/tests/js/services/ui.test.js
index ae89a89e5e..7cd2011fcb 100644
--- a/tests/js/services/ui.test.js
+++ b/tests/js/services/ui.test.js
@@ -430,3 +430,134 @@ describe('renderMarkdown with KaTeX math', () => {
expect(result).toContain('Bad math:');
});
});
+
+describe('favicon status ownership', () => {
+ let canvasContext;
+
+ beforeEach(() => {
+ document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')
+ .forEach(link => link.remove());
+ canvasContext = {
+ clearRect: vi.fn(),
+ fillText: vi.fn(),
+ beginPath: vi.fn(),
+ arc: vi.fn(),
+ fill: vi.fn(),
+ fillStyle: '',
+ font: '',
+ textAlign: '',
+ textBaseline: '',
+ };
+ vi.spyOn(window.HTMLCanvasElement.prototype, 'getContext')
+ .mockReturnValue(canvasContext);
+ vi.spyOn(window.HTMLCanvasElement.prototype, 'toDataURL')
+ .mockReturnValue('data:image/png;base64,favicon');
+ vi.stubGlobal('ResearchStates', {
+ isCompleted: vi.fn(status => status === 'completed'),
+ isFailed: vi.fn(status => status === 'failed'),
+ isCancelled: vi.fn(status => status === 'cancelled'),
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.URLValidator;
+ document.querySelectorAll('link[rel="icon"], link[rel="shortcut icon"]')
+ .forEach(link => link.remove());
+ });
+
+ it('creates an encoded canvas favicon through the URL validator', () => {
+ window.URLValidator = { safeAssign: vi.fn() };
+
+ ui.createDynamicFavicon('🧪');
+
+ const link = document.querySelector('link[rel="icon"]');
+ expect(link).not.toBeNull();
+ expect(canvasContext.fillText).toHaveBeenCalledWith('🧪', 32, 32);
+ expect(window.URLValidator.safeAssign).toHaveBeenCalledWith(
+ link,
+ 'href',
+ 'data:image/png;base64,favicon',
+ );
+ });
+
+ it.each([
+ ['completed', '#28a745'],
+ ['failed', '#dc3545'],
+ ['cancelled', '#6c757d'],
+ ['in_progress', '#007bff'],
+ ])('maps %s research state to its favicon color', (status, color) => {
+ ui.updateFavicon(status);
+
+ const link = document.querySelector('link[rel="icon"]');
+ expect(link.href).toBe('data:image/png;base64,favicon');
+ expect(canvasContext.fillStyle).toBe(color);
+ expect(canvasContext.fillText).toHaveBeenCalledWith('R', 16, 16);
+ });
+
+ it('contains canvas failures and leaves the page usable', () => {
+ window.HTMLCanvasElement.prototype.getContext.mockReturnValue(null);
+ const error = vi.spyOn(SafeLogger, 'error').mockImplementation(() => {});
+
+ expect(() => ui.updateFavicon('completed')).not.toThrow();
+ expect(error).toHaveBeenCalledWith(
+ 'Error updating favicon:',
+ expect.any(TypeError),
+ );
+ });
+});
+
+describe('page alerts', () => {
+ beforeEach(() => {
+ window.LdrAlertHelpers = {
+ mapAlertType: vi.fn(type => (
+ type === 'error' ? 'danger' : type
+ )),
+ };
+ document.body.innerHTML = '<div id="filtered-settings-alert"></div>';
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ delete window.LdrAlertHelpers;
+ document.body.replaceChildren();
+ });
+
+ it('renders and dismisses a safely escaped migration error', () => {
+ const payload = '<img src=x onerror="window.pwned=true">';
+
+ ui.showAlert(payload, 'error', false);
+
+ const container = document.getElementById('filtered-settings-alert');
+ const alert = container.querySelector('.alert-danger');
+ expect(alert.textContent).toContain(payload);
+ expect(alert.querySelector('img')).toBeNull();
+ expect(window.pwned).toBeUndefined();
+ expect(container.style.display).toBe('block');
+
+ alert.querySelector('.ldr-alert-close').click();
+ expect(container.children).toHaveLength(0);
+ expect(container.style.display).toBe('none');
+ });
+
+ it('auto-hides the fallback alert container after five seconds', () => {
+ document.body.innerHTML = '<div id="research-alert"></div>';
+
+ ui.showAlert('Still working', 'info', false);
+ const container = document.getElementById('research-alert');
+ expect(container.children).toHaveLength(1);
+
+ vi.advanceTimersByTime(5000);
+ expect(container.children).toHaveLength(0);
+ expect(container.style.display).toBe('none');
+ });
+
+ it('does not duplicate an inline alert when the toast owns feedback', () => {
+ ui.showAlert('Saved', 'success');
+
+ expect(document.getElementById('filtered-settings-alert').children)
+ .toHaveLength(0);
+ });
+});
diff --git a/tests/js/utils/sse-completion.test.js b/tests/js/utils/sse-completion.test.js
new file mode 100644
index 0000000000..84d00559a9
--- /dev/null
+++ b/tests/js/utils/sse-completion.test.js
@@ -0,0 +1,104 @@
+/**
+ * Runtime contracts for the completion gate shared by the library and
+ * download-manager FastAPI SSE streams.
+ */
+
+import '@js/utils/sse-completion.js';
+
+const handleSSECompletion = window.handleSSECompletion;
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ window.closeProgressModal = vi.fn();
+ vi.stubGlobal('alert', vi.fn());
+});
+
+afterEach(() => {
+ vi.clearAllTimers();
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+ delete window.closeProgressModal;
+});
+
+it('leaves an in-progress event open without scheduling side effects', () => {
+ const onSuccess = vi.fn();
+
+ expect(handleSSECompletion({ complete: false, current: 3 }, onSuccess))
+ .toBe(false);
+ vi.runAllTimers();
+
+ expect(window.closeProgressModal).not.toHaveBeenCalled();
+ expect(alert).not.toHaveBeenCalled();
+ expect(onSuccess).not.toHaveBeenCalled();
+});
+
+it('closes an errored stream and reports its FastAPI error payload', () => {
+ const onSuccess = vi.fn();
+ const data = { complete: true, error: 'Document extraction failed' };
+
+ expect(handleSSECompletion(data, onSuccess)).toBe(true);
+ vi.advanceTimersByTime(999);
+ expect(window.closeProgressModal).not.toHaveBeenCalled();
+
+ vi.advanceTimersByTime(1);
+ expect(window.closeProgressModal).toHaveBeenCalledOnce();
+ expect(alert).toHaveBeenCalledWith('Document extraction failed');
+ expect(onSuccess).not.toHaveBeenCalled();
+});
+
+it('closes a successful stream and forwards the terminal totals', () => {
+ const onSuccess = vi.fn();
+ const data = { complete: true, total: 17, downloaded: 15, skipped: 2 };
+
+ expect(handleSSECompletion(data, onSuccess)).toBe(true);
+ vi.advanceTimersByTime(2000);
+
+ expect(window.closeProgressModal).toHaveBeenCalledOnce();
+ expect(onSuccess).toHaveBeenCalledOnce();
+ expect(onSuccess).toHaveBeenCalledWith(data);
+ expect(alert).not.toHaveBeenCalled();
+});
+
+it('drops delayed terminal effects after the caller loses ownership', () => {
+ const onSuccess = vi.fn();
+ let isCurrent = true;
+ const data = { complete: true, total: 1 };
+
+ expect(handleSSECompletion(data, onSuccess, () => isCurrent)).toBe(true);
+ isCurrent = false;
+ vi.advanceTimersByTime(2000);
+
+ expect(window.closeProgressModal).not.toHaveBeenCalled();
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(alert).not.toHaveBeenCalled();
+});
+
+it('drops a delayed terminal error after the caller loses ownership', () => {
+ const onSuccess = vi.fn();
+ let isCurrent = true;
+
+ expect(handleSSECompletion(
+ { complete: true, error: 'stale stream failure' },
+ onSuccess,
+ () => isCurrent,
+ )).toBe(true);
+ isCurrent = false;
+ vi.advanceTimersByTime(1000);
+
+ expect(window.closeProgressModal).not.toHaveBeenCalled();
+ expect(onSuccess).not.toHaveBeenCalled();
+ expect(alert).not.toHaveBeenCalled();
+});
+
+it('completes successfully when the current page has no progress modal', () => {
+ delete window.closeProgressModal;
+ const onSuccess = vi.fn();
+ const data = { complete: true, downloaded: 1 };
+
+ expect(handleSSECompletion(data, onSuccess)).toBe(true);
+ vi.advanceTimersByTime(2000);
+
+ expect(onSuccess).toHaveBeenCalledWith(data);
+ expect(alert).not.toHaveBeenCalled();
+});
diff --git a/tests/js/utils/sse-json-parser.test.js b/tests/js/utils/sse-json-parser.test.js
new file mode 100644
index 0000000000..ca0d999d62
--- /dev/null
+++ b/tests/js/utils/sse-json-parser.test.js
@@ -0,0 +1,66 @@
+/**
+ * Unit contracts for the shared boundary-safe JSON SSE parser.
+ */
+
+import '@js/utils/sse-completion.js';
+
+const createSSEJsonParser = window.createSSEJsonParser;
+
+function encode(value) {
+ return new globalThis.TextEncoder().encode(value);
+}
+
+it('buffers a JSON data line split across arbitrary stream chunks', () => {
+ const onData = vi.fn();
+ const parser = createSSEJsonParser(onData);
+
+ parser.push(encode('data: {"status":"suc'));
+ expect(onData).not.toHaveBeenCalled();
+ parser.push(encode('cess","current":1}\n'));
+ parser.finish();
+
+ expect(onData).toHaveBeenCalledOnce();
+ expect(onData).toHaveBeenCalledWith({ status: 'success', current: 1 });
+});
+
+it('keeps a multibyte character intact when its bytes span chunks', () => {
+ const onData = vi.fn();
+ const parser = createSSEJsonParser(onData);
+ const bytes = encode('data: {"file":"résumé.pdf"}\r\n');
+ const firstMultibyteLead = Array.from(bytes).indexOf(0xc3);
+
+ parser.push(bytes.subarray(0, firstMultibyteLead + 1));
+ parser.push(bytes.subarray(firstMultibyteLead + 1));
+ parser.finish();
+
+ expect(onData).toHaveBeenCalledOnce();
+ expect(onData).toHaveBeenCalledWith({ file: 'résumé.pdf' });
+});
+
+it('flushes one final data line when EOF arrives without a newline', () => {
+ const onData = vi.fn();
+ const parser = createSSEJsonParser(onData);
+
+ parser.push(encode('data:{"complete":true}'));
+ expect(onData).not.toHaveBeenCalled();
+ parser.finish();
+
+ expect(onData).toHaveBeenCalledOnce();
+ expect(onData).toHaveBeenCalledWith({ complete: true });
+});
+
+it('ignores comments, blank data fields, and non-data SSE fields', () => {
+ const onData = vi.fn();
+ const parser = createSSEJsonParser(onData);
+
+ parser.push(encode(
+ ': keep-alive\n' +
+ 'event: progress\n' +
+ 'data:\n' +
+ 'data: {"current":2}\n',
+ ));
+ parser.finish();
+
+ expect(onData).toHaveBeenCalledOnce();
+ expect(onData).toHaveBeenCalledWith({ current: 2 });
+});
diff --git a/tests/puppeteer/test_deep_functionality.js b/tests/puppeteer/test_deep_functionality.js
index eeb9dd5e7d..f72cd12557 100644
--- a/tests/puppeteer/test_deep_functionality.js
+++ b/tests/puppeteer/test_deep_functionality.js
@@ -929,6 +929,7 @@ describe('Deep Functionality Tests', function() {
await takeScreenshot(page, 'subscription-create-form');
const subName = `Test Subscription ${TEST_RUN_ID}`;
+ const subQuery = 'artificial intelligence breakthroughs machine learning';
console.log(` Creating subscription: ${subName}`);
// Wait for form to be ready
@@ -941,7 +942,7 @@ describe('Deep Functionality Tests', function() {
}
// Fill required query field
- await page.type('#subscription-query', 'artificial intelligence breakthroughs machine learning');
+ await page.type('#subscription-query', subQuery);
console.log(' ✓ Filled query field');
// Fill name field
@@ -954,9 +955,11 @@ describe('Deep Functionality Tests', function() {
// Set interval to daily (1440 minutes)
const intervalInput = await page.$('#subscription-interval');
if (intervalInput) {
- await intervalInput.click({ clickCount: 3 });
- await page.keyboard.press('Backspace');
- await intervalInput.type('1440');
+ await page.$eval('#subscription-interval', input => {
+ input.value = '1440';
+ input.dispatchEvent(new Event('input', { bubbles: true }));
+ input.dispatchEvent(new Event('change', { bubbles: true }));
+ });
console.log(' ✓ Set interval to 1440 (daily)');
}
@@ -964,37 +967,64 @@ describe('Deep Functionality Tests', function() {
// Submit the form - look for submit button
const submitBtn = await page.$('button[type="submit"], .btn-primary[type="submit"]');
- if (submitBtn) {
- console.log(' Clicking submit button...');
- await submitBtn.click();
+ expect(submitBtn, 'subscription submit button').to.not.be.null;
+
+ console.log(' Clicking submit button...');
+ const subscriptionResponsePromise = page.waitForResponse(response =>
+ response.url().endsWith('/news/api/subscribe') &&
+ response.request().method() === 'POST',
+ );
+ await submitBtn.click();
+
+ const subscriptionResponse = await subscriptionResponsePromise;
+ const responseBody = await subscriptionResponse.text();
+ expect(
+ subscriptionResponse.ok(),
+ `subscription POST failed (${subscriptionResponse.status()}): ${responseBody}`,
+ ).to.equal(true);
+
+ await page.waitForFunction(
+ () => window.location.pathname.replace(/\/+$/, '') === '/news',
+ { timeout: 10000 },
+ );
+ await takeScreenshot(page, 'subscription-after-submit');
- // Wait for response
- await delay(3000);
- await takeScreenshot(page, 'subscription-after-submit');
-
- const currentUrl = page.url();
- console.log(` After submit URL: ${currentUrl}`);
-
- // Check for success indicators
- const bodyText = await page.$eval('body', el => el.textContent.toLowerCase());
- const hasSuccess = bodyText.includes('success') ||
- bodyText.includes('created') ||
- currentUrl.includes('/subscriptions') && !currentUrl.includes('/new');
- console.log(` Creation success indicators: ${hasSuccess}`);
- } else {
- console.log(' Submit button not found');
- }
+ const currentUrl = page.url();
+ console.log(` After submit URL: ${currentUrl}`);
+ expect(new URL(currentUrl).pathname.replace(/\/+$/, '')).to.equal('/news');
// Verify subscription appears in list
await page.goto(`${BASE_URL}/news/subscriptions`, { waitUntil: 'domcontentloaded' });
- await delay(2000);
+ await page.waitForFunction(
+ (expectedName, expectedQuery) => {
+ return Array.from(document.querySelectorAll('.ldr-subscription-card'))
+ .some(card => {
+ const text = card.textContent;
+ return text.includes(expectedName) && text.includes(expectedQuery);
+ });
+ },
+ { timeout: 10000 },
+ subName,
+ subQuery,
+ );
await takeScreenshot(page, 'subscriptions-list-after-create');
- const bodyText = await page.$eval('body', el => el.textContent);
- const foundName = bodyText.includes(subName) || bodyText.includes('Test Subscription');
- const foundQuery = bodyText.includes('artificial intelligence') || bodyText.includes('machine learning');
+ const { foundName, foundQuery } = await page.$$eval(
+ '.ldr-subscription-card',
+ (cards, expectedName, expectedQuery) => {
+ const card = cards.find(candidate => candidate.textContent.includes(expectedName));
+ return {
+ foundName: Boolean(card),
+ foundQuery: card ? card.textContent.includes(expectedQuery) : false,
+ };
+ },
+ subName,
+ subQuery,
+ );
console.log(` Subscription name found: ${foundName}`);
console.log(` Subscription query found: ${foundQuery}`);
+ expect(foundName, `subscription list should contain ${subName}`).to.equal(true);
+ expect(foundQuery, `subscription list should contain ${subQuery}`).to.equal(true);
});
});
diff --git a/tests/security/test_client_side_xss_sinks.py b/tests/security/test_client_side_xss_sinks.py
index 8eeacdf87c..17415571fb 100644
--- a/tests/security/test_client_side_xss_sinks.py
+++ b/tests/security/test_client_side_xss_sinks.py
@@ -318,9 +318,6 @@ REVIEWED_NON_ENTITY_ESCAPERS = {
# NOT safe inside a quoted attribute (see the attribute census).
"components/context-overflow.js::escapeHtml": TEXT_NODE_ONLY,
"components/progress.js::escapeHtml": TEXT_NODE_ONLY,
- # A JavaScript-string escaper, despite the name and the "for use in
- # HTML attributes (onclick, etc)" comment above it.
- "pages/news.js::escapeAttr": JS_STRING,
# Identity fallback: when ``window.escapeHtml`` is absent this
# escapes nothing at all, and ESLint accepts it because it is
# spelled ``esc``.
@@ -474,26 +471,6 @@ KNOWN_ATTRIBUTE_ESCAPER_MISUSES = {
"escapeHtml(req.research_query)",
"escapeHtml(stat.model)",
],
- # LATENT. ``escapeAttr`` backslash-escapes for a JS string literal,
- # not for an HTML attribute, and is used inside ``onclick="..."``.
- # Nine of the eleven sites pass a server-issued id; the recent
- # search list passes ``item.query``. All of them are rendered
- # through ``safeRenderHTML`` (DOMPurify), which is what actually
- # stops the breakout -- and which also strips the ``onclick`` these
- # sites are trying to install.
- "pages/news.js": [
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.id)",
- "escapeAttr(item.query)",
- "escapeAttr(item.type)",
- ],
}
@@ -511,18 +488,38 @@ def test_attribute_escaper_misuses_are_exactly_the_reviewed_set():
assert found == KNOWN_ATTRIBUTE_ESCAPER_MISUSES
-def test_the_news_attribute_escaper_is_a_javascript_string_escaper():
- """Pin *why* ``escapeAttr`` does not protect an HTML attribute."""
+def test_news_action_values_do_not_enter_inline_javascript_handlers():
+ """Pin the declarative replacement for the removed ``escapeAttr`` sinks."""
text = (STATIC_JS / "pages" / "news.js").read_text(encoding="utf-8")
- body = text.split("function escapeAttr(unsafe) {")[1].split("}")[0]
- assert QUOT_ENTITY not in body, (
- "escapeAttr now emits entities — update the classification"
+ assert "function escapeAttr(" not in text
+
+ render_body = text.split("function renderNewsItems(", 1)[1]
+ render_body = render_body.split("\nfunction ", 1)[0]
+ recent_body = text.split("function displayRecentSearches(", 1)[1]
+ recent_body = recent_body.split("\nfunction ", 1)[0]
+
+ # Static handlers elsewhere in these functions are not an injection
+ # boundary. What must not return is a template substitution inside one.
+ for body in (render_body, recent_body):
+ handlers = re.findall(r'\bon\w+\s*=\s*"([^"]*)"', body)
+ assert all("${" not in handler for handler in handlers), handlers
+
+ # Untrusted values are entity-escaped into declarative data attributes;
+ # stable listeners read them back instead of evaluating JavaScript text.
+ assert 'data-news-id="${escapeHtml(item.id)}"' in render_body
+ assert 'data-news-action="toggle-read"' in render_body
+ assert 'data-query="${escapeHtml(item.query)}"' in recent_body
+ assert (
+ "data-search-type=\"${escapeHtml(item.type || 'quick')}\""
+ in recent_body
)
- assert '.replace(/"/g' in body and "\\\\" in body
+ assert "e.target.closest('[data-news-action]')" in text
+ assert "newsItem.dataset.newsId" in text
+ assert "e.target.closest('[data-news-page-action]')" in text
def test_news_html_is_rendered_through_dompurify_not_raw_innerhtml():
- """The mitigation for the escapeAttr sites, pinned in place."""
+ """Pin DOMPurify as defense in depth for dynamic news markup."""
text = (STATIC_JS / "pages" / "news.js").read_text(encoding="utf-8")
helper = text.split("function safeRenderHTML(container, htmlString) {")
assert len(helper) == 2, "safeRenderHTML was renamed or removed"
diff --git a/tests/web/routers/test_chat_page_login_redirect.py b/tests/web/routers/test_chat_page_login_redirect.py
index 45dbfdb987..20f8356f13 100644
--- a/tests/web/routers/test_chat_page_login_redirect.py
+++ b/tests/web/routers/test_chat_page_login_redirect.py
@@ -53,7 +53,7 @@ def test_anonymous_chat_page_redirects_to_login_carrying_the_path():
def test_anonymous_chat_page_redirect_preserves_the_q_query_string():
"""``/chat/?q=<question>`` must survive the login bounce.
- chat.js reads ``?q=`` at components/chat.js:282-288 and calls
+ chat.js reads ``?q=`` in its routed-query bootstrap and calls
handleSend(), so the query is not merely pre-filled -- it is
auto-submitted as a research run. Dropping it stranded a signed-out user
who followed a shared link on an empty chat box with the question gone.
diff --git a/tests/web/routers/test_library_download_outcomes.py b/tests/web/routers/test_library_download_outcomes.py
index 81a65b0ea6..bae158941a 100644
--- a/tests/web/routers/test_library_download_outcomes.py
+++ b/tests/web/routers/test_library_download_outcomes.py
@@ -6,7 +6,7 @@ every string asserted here lives in ``web/routers/library.py`` (or, for
``favorites_only``, in ``research_library/services/library_service.py``) and
appeared in no test on the branch.
-Six guarantees, all of them things a user reads or a template branches on:
+Seven guarantees, all of them things a user reads or a template branches on:
* ``"Already downloaded"`` -- ``/library/api/download-source`` short-circuits
only when a **completed** Document already exists for the resource. The
@@ -29,6 +29,8 @@ Six guarantees, all of them things a user reads or a template branches on:
Both templates gate the download controls on it. If either copy drifts,
a user who has turned PDF storage off is shown download buttons on one
page and not the other.
+* ``load_error`` -- a document read failure renders an honest retry state,
+ not either empty-library claim, through the real ``library.html`` template.
* ``"pages/document_details.html"`` -- ``document_details_page`` renders it
for a document that exists and must answer a JSON 404 for one that does
not, *without* rendering the page. A details template rendered against a
@@ -57,6 +59,7 @@ from pathlib import Path
from unittest.mock import MagicMock, Mock, patch
import pytest
+from bs4 import BeautifulSoup
from starlette.requests import Request
from local_deep_research.research_library.services import (
@@ -746,6 +749,91 @@ class TestEnablePdfStorage:
assert context["storage_path"] == "/tmp/library"
+class TestLibraryPageLoadFailure:
+ def test_service_read_failure_renders_an_honest_retry_state(self, app):
+ service = Mock()
+ service.get_library_stats.return_value = {
+ "total_pdfs": 3,
+ "total_size_mb": 4.25,
+ "storage_path": "/tmp/library",
+ }
+ service.count_documents.side_effect = RuntimeError(
+ "injected library read failure"
+ )
+
+ @contextmanager
+ def fake_db_session(*args, **kwargs):
+ yield Mock()
+
+ requests = [
+ _get_request(),
+ _get_request(query_string=b"domain=example.org"),
+ ]
+ for request in requests:
+ request.scope.update(
+ {
+ "app": app,
+ "router": app.router,
+ "scheme": "http",
+ "server": ("testserver", 80),
+ "root_path": "",
+ }
+ )
+
+ with (
+ patch.object(
+ library_module,
+ "get_user_db_session",
+ side_effect=fake_db_session,
+ ),
+ patch.object(
+ library_module,
+ "get_settings_manager",
+ return_value=_settings_manager("database"),
+ ),
+ patch.object(
+ library_module, "LibraryService", return_value=service
+ ),
+ patch(
+ "local_deep_research.database.library_init.get_default_library_id",
+ return_value="col-default",
+ ),
+ ):
+ responses = [
+ library_page(request, username="alice") for request in requests
+ ]
+
+ for response in responses:
+ assert response.status_code == 200
+ empty_state = BeautifulSoup(
+ response.body.decode("utf-8"), "html.parser"
+ ).select_one(".ldr-empty-state")
+ assert empty_state is not None
+ assert empty_state.find("h3").get_text(strip=True) == (
+ "Your library could not be loaded"
+ )
+ assert [
+ paragraph.get_text(" ", strip=True)
+ for paragraph in empty_state.find_all("p")
+ ] == [
+ "Something went wrong reading your documents, so this page "
+ "cannot show them right now. Your documents have not been "
+ "deleted."
+ ]
+ retry = empty_state.find("a")
+ assert retry is not None
+ assert retry.get_text(" ", strip=True) == "Try Again"
+ assert retry.get("href", "").endswith("/library/")
+
+ visible_copy = empty_state.get_text(" ", strip=True)
+ assert "No documents in your library yet" not in visible_copy
+ assert "No documents match the current filters" not in visible_copy
+
+ assert service.get_library_stats.call_count == 2
+ assert service.count_documents.call_count == 2
+ service.get_documents.assert_not_called()
+
+
# ===========================================================================
# favorites_only
# ===========================================================================
diff --git a/tests/web/routers/test_research_mutating_route_effects.py b/tests/web/routers/test_research_mutating_route_effects.py
index e126dfb123..8094cc4bc4 100644
--- a/tests/web/routers/test_research_mutating_route_effects.py
+++ b/tests/web/routers/test_research_mutating_route_effects.py
@@ -226,6 +226,26 @@ def _terminate_mocks(active, cleanup):
]
+ "status", ["completed", "failed", "error", "suspended"]
+)
+def test_terminate_reports_existing_terminal_status_without_cancelling(
+ authenticated_client, db, status
+):
+ row = _add_research(db, "already-terminal", status=status)
+ with (
+ _patch_session(db),
+ patch(f"{_RR}.set_termination_flag") as terminate_flag,
+ ):
+ response = authenticated_client.post("/api/terminate/already-terminal")
+
+ assert response.status_code == 200
+ assert response.json()["status"] == "success"
+ assert response.json()["research_status"] == status
+ assert row.status == status
+ terminate_flag.assert_not_called()
+
+
def test_terminate_parses_a_progress_log_stored_as_a_json_string(
authenticated_client, db
):
diff --git a/tests/web/test_js_fetch_parity.py b/tests/web/test_js_fetch_parity.py
index 29cef4fa2d..ae490ccb26 100644
--- a/tests/web/test_js_fetch_parity.py
+++ b/tests/web/test_js_fetch_parity.py
@@ -948,21 +948,21 @@ class LiveCase:
LIVE_CASES = (
LiveCase(
- js_ref="components/settings_sync.js:10",
+ js_ref="components/settings_sync.js:16",
method="PUT",
url="/settings/api/llm.temperature",
good={"value": 0.5},
bad={"val": 0.5},
),
LiveCase(
- js_ref="components/research.js:2934",
+ js_ref="components/research.js:2989",
method="POST",
url="/settings/api/search-favorites/toggle",
good={"engine_id": "zzz_no_such_engine"},
bad={"engineId": "zzz_no_such_engine"},
),
LiveCase(
- js_ref="followup.js:248",
+ js_ref="followup.js:279",
method="POST",
url="/api/followup/prepare",
good={"parent_research_id": NOPE_UUID, "question": "q"},
@@ -973,35 +973,35 @@ LIVE_CASES = (
# That is a separate defect (unguarded lookup) and out of scope here;
# what matters for *this* test is that 500 means the body passed
# validation and the handler ran.
- js_ref="pages/news.js:1258",
+ js_ref="pages/news.js:1425",
method="POST",
url=f"/news/api/feedback/{NOPE_UUID}",
good={"vote": "up"},
bad={"rating": "up"},
),
LiveCase(
- js_ref="components/chat.js:2408",
+ js_ref="components/chat.js:2631",
method="PATCH",
url=f"/api/chat/sessions/{NOPE_UUID}",
good={"title": "t"},
bad={"name": "t"},
),
LiveCase(
- js_ref="pages/note-detail.js:2888",
+ js_ref="pages/note-detail.js:2909",
method="POST",
url=f"/notes/api/notes/{NOPE_UUID}/accept-link",
good={"target_note_id": NOPE_UUID},
bad={"targetNoteId": NOPE_UUID},
),
LiveCase(
- js_ref="components/save_to_collection.js:195",
+ js_ref="components/save_to_collection.js:197",
method="POST",
url=f"/library/api/research/{NOPE_UUID}/add-to-collection",
good={"collection_id": 999999},
bad={"collectionId": 999999},
),
LiveCase(
- js_ref="pages/note-detail.js:1722",
+ js_ref="pages/note-detail.js:1743",
method="POST",
url=f"/notes/api/notes/{NOPE_UUID}/research",
good={"research_id": NOPE_UUID},