~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(library): show per-collection indexing status + background-index toggle (#3939/#4627 follow-up) (#4649)
LearningCircuitfeac0c98ceaf
diff --git a/changelog.d/+library-index-status-ui.feature.md b/changelog.d/+library-index-status-ui.feature.mdnew file mode 100644index 0000000000..254c3f8499--- /dev/null+++ b/changelog.d/+library-index-status-ui.feature.md@@ -0,0 +1 @@+Library collections now show per-collection indexing status ("X of Y indexed" + a "N pending indexing" badge) with a per-card Reindex action. When the optional scheduled-reconciler setting is available, a toggle to index documents in the background on a schedule also appears (otherwise it stays hidden). (#3939/#4627 follow-up).diff --git a/src/local_deep_research/research_library/routes/rag_routes.py b/src/local_deep_research/research_library/routes/rag_routes.pyindex 541da591ea..1002e65e5b 100644--- a/src/local_deep_research/research_library/routes/rag_routes.py+++ b/src/local_deep_research/research_library/routes/rag_routes.py@@ -21,6 +21,7 @@ from flask import (stream_with_context,)from loguru import logger+from sqlalchemy import case, funcimport atexitimport globimport json@@ -1399,8 +1400,37 @@ def get_collections():# No need to filter by username - each user has their own databasecollections = db_session.query(Collection).all()+ # How many documents in each collection are already indexed for+ # RAG search. Computed once as a grouped aggregate (mirrors+ # LibraryService.get_all_collections) so the per-collection+ # "X of Y indexed" / pending status doesn't trigger an N+1.+ indexed_counts = dict(+ db_session.query(+ DocumentCollection.collection_id,+ func.count(+ case(+ (+ DocumentCollection.indexed == True, # noqa: E712+ DocumentCollection.document_id,+ ),+ else_=None,+ )+ ),+ )+ .group_by(DocumentCollection.collection_id)+ .all()+ )+result = []for coll in collections:+ document_count = (+ len(coll.document_links)+ if hasattr(coll, "document_links")+ else 0+ )+ indexed_document_count = int(+ indexed_counts.get(coll.id, 0) or 0+ )collection_data = {"id": coll.id,"name": coll.name,@@ -1414,9 +1444,8 @@ def get_collections():else False,"is_public": bool(getattr(coll, "is_public", False)),"agent_enabled": _agent_enabled_default_on(coll),- "document_count": len(coll.document_links)- if hasattr(coll, "document_links")- else 0,+ "document_count": document_count,+ "indexed_document_count": indexed_document_count,"folder_count": len(coll.linked_folders)if hasattr(coll, "linked_folders")else 0,@@ -2996,28 +3025,46 @@ def get_index_status(collection_id):try:with get_user_db_session(username, db_password) as db_session:- # Find the most recent indexing task for this collection- task = (+ # Find the most recent indexing task FOR THIS COLLECTION.+ #+ # collection_id is stored inside the metadata_json JSON column, so+ # we can't portably filter on it in SQL (SQLite/SQLCipher JSON+ # support varies). Instead, scan recent indexing tasks newest-first+ # and return the first whose metadata.collection_id matches. This+ # is scoped per collection: a newer indexing task for a DIFFERENT+ # collection no longer makes this one falsely report "idle".+ #+ # This endpoint is polled every ~2s during a reindex and the+ # indexing-task table is never pruned, so an unbounded .all() would+ # materialize the entire history on every poll (and task_type /+ # created_at are unindexed). Bound the scan to the newest N tasks.+ # The task we're looking for was just created by the reindex that+ # started this poll, so it sits near the top; N=200 is large enough+ # that concurrent reindexes of other collections can't push it out+ # of the window before it terminates. Trade-off: if more than ~200+ # newer indexing tasks for OTHER collections appear while this one+ # is still in-flight, the scoped lookup falls back to "idle".+ recent_task_scan_limit = 200+ recent_tasks = (db_session.query(TaskMetadata).filter(TaskMetadata.task_type == "indexing").order_by(TaskMetadata.created_at.desc())- .first()+ .limit(recent_task_scan_limit)+ .all())- if not task:- return jsonify(- {- "status": "idle",- "message": "No indexing task found",- }- )+ task = None+ for candidate in recent_tasks:+ metadata = candidate.metadata_json or {}+ if metadata.get("collection_id") == collection_id:+ task = candidate+ break- # Check if it's for this collection- metadata = task.metadata_json or {}- if metadata.get("collection_id") != collection_id:+ if not task:return jsonify({"status": "idle",+ "collection_id": collection_id,"message": "No indexing task for this collection",})@@ -3025,6 +3072,7 @@ def get_index_status(collection_id):return jsonify({"task_id": task.task_id,+ "collection_id": collection_id,"status": task.status,"progress_current": task.progress_current or 0,"progress_total": task.progress_total or 0,diff --git a/src/local_deep_research/web/static/css/collections.css b/src/local_deep_research/web/static/css/collections.cssindex 3beb26c66d..b0302161f2 100644--- a/src/local_deep_research/web/static/css/collections.css+++ b/src/local_deep_research/web/static/css/collections.css@@ -114,21 +114,39 @@margin-bottom: 2rem;}-/* Collection Cards */-.ldr-collection-card {+/* Collection card wrapper: holds the clickable <a> card plus the actions row+ (Reindex + View) as a sibling, so the interactive button is never nested+ inside the card's anchor. */+.ldr-collection-card-wrapper {display: flex;flex-direction: column;background: linear-gradient(135deg, var(--bg-secondary) 0%, var(--bg-tertiary) 100%);border-radius: 16px;- padding: 1.5rem;border: 1px solid var(--border-color);- transition: all 0.3s ease;+ transition: border-color 0.3s ease, transform 0.3s ease, box-shadow 0.3s ease;position: relative;overflow: hidden;+}++.ldr-collection-card-wrapper:hover {+ transform: translateY(-8px);+ box-shadow: 0 12px 40px rgba(var(--accent-primary-rgb), 0.2);+ border-color: var(--accent-primary);+}++/* Collection Cards */+.ldr-collection-card {+ display: flex;+ flex-direction: column;+ flex: 1;+ padding: 1.5rem 1.5rem 0.5rem 1.5rem;+ transition: all 0.3s ease;+ position: relative;+ z-index: 1;cursor: pointer;}-.ldr-collection-card::before {+.ldr-collection-card-wrapper::before {content: '';position: absolute;top: 0;@@ -137,18 +155,13 @@height: 100%;background: linear-gradient(90deg, transparent, rgba(var(--accent-primary-rgb), 0.1), transparent);transition: left 0.6s ease;+ pointer-events: none;}-.ldr-collection-card:hover::before {+.ldr-collection-card-wrapper:hover::before {left: 100%;}-.ldr-collection-card:hover {- transform: translateY(-8px);- box-shadow: 0 12px 40px rgba(var(--accent-primary-rgb), 0.2);- border-color: var(--accent-primary);-}-.ldr-collection-header {margin-bottom: 1.5rem;}@@ -219,14 +232,61 @@animation: pulse 2s infinite;}+/* Collection card footer: Reindex action + View link */+.ldr-collection-card-actions {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 0.75rem;+ margin-top: auto;+ padding: 0 1.5rem 1.5rem 1.5rem;+ position: relative;+ z-index: 1;+}++/* Per-card Reindex button. Sibling of the card <a> (never nested inside it);+ its click handler preventDefault()/stopPropagation()s defensively. */+.ldr-reindex-btn {+ display: inline-flex;+ align-items: center;+ gap: 0.4rem;+ padding: 0.35rem 0.7rem;+ font-size: 0.85rem;+ font-weight: 500;+ color: var(--text-secondary);+ background: var(--bg-tertiary);+ border: 1px solid var(--border-color);+ border-radius: 6px;+ cursor: pointer;+ transition: all 0.2s ease;+}++.ldr-reindex-btn:hover:not(:disabled) {+ color: var(--accent-primary);+ border-color: var(--accent-primary);+}++.ldr-reindex-btn:disabled {+ opacity: 0.6;+ cursor: progress;+}++.ldr-reindex-btn i.fa-spin {+ animation: fa-spin 1s linear infinite;+}++/* Pending-index badge on the card. */+.ldr-pending-index-badge {+ font-weight: 600;+ color: var(--warning-color);+}+/* Collection View Link */.ldr-collection-view-link {display: flex;align-items: center;justify-content: flex-end;gap: 0.5rem;- margin-top: auto;- padding-top: 1rem;color: var(--text-secondary);font-size: 0.9rem;font-weight: 500;@@ -239,12 +299,12 @@transition: transform 0.3s ease;}-.ldr-collection-card:hover .ldr-collection-view-link {+.ldr-collection-card-wrapper:hover .ldr-collection-view-link {opacity: 1;color: var(--accent-primary);}-.ldr-collection-card:hover .ldr-collection-view-link i {+.ldr-collection-card-wrapper:hover .ldr-collection-view-link i {transform: translateX(4px);}@@ -648,7 +708,7 @@/* Dark theme enhancements */@media (prefers-color-scheme: dark) {- .ldr-collection-card::before {+ .ldr-collection-card-wrapper::before {background: linear-gradient(90deg, transparent, rgba(var(--accent-primary-rgb), 0.15), transparent);}@@ -658,7 +718,7 @@}/* Hover effects for interactive elements */-.ldr-collection-card,+.ldr-collection-card-wrapper,.ldr-btn-collections,.ldr-empty-state {transform-origin: center;diff --git a/src/local_deep_research/web/static/js/collections_manager.js b/src/local_deep_research/web/static/js/collections_manager.jsindex 14b2e0e7cc..321aab8078 100644--- a/src/local_deep_research/web/static/js/collections_manager.js+++ b/src/local_deep_research/web/static/js/collections_manager.js@@ -24,6 +24,13 @@ document.addEventListener('DOMContentLoaded', function() {autoIndexToggle.addEventListener('change', saveAutoIndexSetting);}+ // Setup background-sweep toggle (scheduled reconciler)+ const bgSweepToggle = document.getElementById('background-sweep-toggle');+ if (bgSweepToggle) {+ loadBackgroundSweepSetting();+ bgSweepToggle.addEventListener('change', saveBackgroundSweepSetting);+ }+});/**@@ -67,6 +74,147 @@ async function saveAutoIndexSetting() {}}+/**+ * Read the legacy generate_rag arm of the reconciler gate.+ *+ * Returns true/false for the stored value, or null when it can't be determined+ * (unregistered key or a transient network failure). Never throws. The two+ * callers interpret null DIFFERENTLY by design: the disable action treats it as+ * "maybe armed" and still clears (legacyArmNeedsClear), while the display load+ * path treats it as "not known to be on" and shows the sweep state — so a blip+ * neither leaves the reconciler silently armed nor flashes a false ON.+ */+async function readBackgroundSweepLegacyArm() {+ try {+ const legacy = await safeFetch('/settings/api/document_scheduler.generate_rag');+ if (!legacy.ok) {+ SafeLogger.warn('Could not read legacy generate_rag setting:', legacy.status);+ return null;+ }+ const legacyData = await legacy.json();+ return legacyData.value === true || legacyData.value === 'true';+ } catch (error) {+ SafeLogger.error('Error reading legacy generate_rag setting:', error);+ return null;+ }+}++/**+ * Whether the disable action must clear the legacy generate_rag arm.+ *+ * On OFF we clear it unless we are CERTAIN it is already false: a null (unknown+ * — transient read failure or unregistered key) is treated as "might be armed"+ * so a blip can never leave the toggle showing OFF while the reconciler keeps+ * running. Clearing an already-false key is idempotent and harmless.+ */+function legacyArmNeedsClear(legacyOn) {+ return legacyOn !== false;+}++/**+ * Load the background-sweep setting and update the toggle.+ *+ * Wired to document_scheduler.sweep_library_collections (#4627): an opt-in+ * scheduled reconciler that periodically indexes any library documents that+ * weren't indexed immediately.+ */+async function loadBackgroundSweepSetting() {+ const row = document.getElementById('background-sweep-toggle-row');+ try {+ const response = await safeFetch('/settings/api/document_scheduler.sweep_library_collections');+ if (!response.ok) {+ // Setting isn't registered yet (e.g. 404 before #4627 merges).+ // Hide the whole row so the toggle isn't a dead control; it only+ // appears once the backend setting exists.+ if (row) row.style.display = 'none';+ return;+ }+ const data = await response.json();+ const toggle = document.getElementById('background-sweep-toggle');+ let on = data.value === true || data.value === 'true';+ // The reconciler is OR-gated on (sweep_library_collections OR the+ // legacy generate_rag) — see _schedule_reconciler / the runtime gate+ // in scheduler/background.py. Reflect the EFFECTIVE gate so the toggle+ // can't read OFF while an upgraded generate_rag user is still being+ // indexed every tick. Only the legacy arm needs a second read, and a+ // failure reading it must NOT hide the control (the sweep read already+ // succeeded) — degrade to the sweep-derived state instead.+ if (!on) {+ const legacyOn = await readBackgroundSweepLegacyArm();+ // Display-only: treat ONLY a definite true as ON; null (unknown)+ // degrades to the sweep state. This is deliberately the OPPOSITE of+ // the disable action, which clears on null (legacyArmNeedsClear).+ // Do NOT "unify" this with legacyArmNeedsClear — null-as-ON here+ // would flash a false ON on every transient read blip.+ if (legacyOn === true) {+ on = true;+ }+ }+ toggle.checked = on;+ // Setting exists — reveal the row.+ if (row) row.style.display = 'flex';+ } catch (error) {+ SafeLogger.error('Error loading background-sweep setting:', error);+ if (row) row.style.display = 'none';+ }+}++/**+ * Save the background-sweep setting when toggled.+ */+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) => safeFetch('/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 data = await response.json();+ if (!response.ok || 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);+ toggle.checked = true;+ }+ }+ } catch (error) {+ SafeLogger.error('Error saving background-sweep setting:', error);+ toggle.checked = !desired;+ }+}+/*** Load document collections*/@@ -98,50 +246,257 @@ async function loadCollections() {}}+/**+ * Build the per-collection index-status markup.+ *+ * Shows "<indexed> of <total> indexed" plus a "<pending> pending indexing"+ * badge when documents are still awaiting indexing. All values are coerced+ * to non-negative integers before interpolation (XSS-safe: numeric only).+ */+function indexStatusMarkup(collection) {+ const total = Math.max(0, Math.trunc(Number(collection.document_count) || 0));+ const indexed = Math.min(+ total,+ Math.max(0, Math.trunc(Number(collection.indexed_document_count) || 0))+ );+ const pending = Math.max(0, total - indexed);++ if (total === 0) {+ return `+ <div class="ldr-stat-item ldr-embedding-warning">+ <i class="fas fa-info-circle"></i>+ <span title="No documents to index yet">No documents</span>+ </div>`;+ }++ const allIndexed = pending === 0;+ return `+ <div class="ldr-stat-item ${allIndexed ? 'ldr-embedding-info' : ''}">+ <i class="fas ${allIndexed ? 'fa-check-circle' : 'fa-layer-group'}"></i>+ <span title="${indexed} of ${total} documents indexed for search">${indexed} of ${total} indexed</span>+ </div>+ ${pending > 0 ? `+ <div class="ldr-stat-item ldr-embedding-warning">+ <i class="fas fa-exclamation-triangle"></i>+ <span class="ldr-pending-index-badge" title="${pending} documents are not yet indexed">${pending} pending indexing</span>+ </div>+ ` : ''}`;+}+/*** Render collections grid*/function renderCollections() {const container = document.getElementById('collections-container');- // eslint-disable-next-line no-unsanitized/property -- audited 2026-03-28: all interpolations use escapeHtml/esc, numeric coercion, or hardcoded strings+ // The Reindex <button> must be a SIBLING of the card <a>, never a child+ // (interactive-in-interactive is invalid and pressing Enter on the anchor+ // would still navigate). Each card is therefore a wrapper <div> holding the+ // clickable <a> plus a separate actions row outside the anchor.+ // eslint-disable-next-line no-unsanitized/property -- audited 2026-06-20: all interpolations use escapeHtml/esc, numeric coercion (indexStatusMarkup coerces counts to ints), or hardcoded stringscontainer.innerHTML = collections.map(collection => `- <a href="/library/collections/${encodeURIComponent(collection.id)}" class="ldr-collection-card" data-id="${escapeHtml(collection.id)}" style="text-decoration: none; color: inherit; cursor: pointer;">- <div class="ldr-collection-header">- <h3>${escapeHtml(collection.name)}</h3>- ${collection.description ? `<p class="ldr-collection-description">${escapeHtml(collection.description)}</p>` : ''}- </div>-- <div class="ldr-collection-stats">- <div class="ldr-stat-item">- <i class="fas fa-file"></i>- <span>${collection.document_count || 0} documents</span>- </div>- ${collection.created_at ? `- <div class="ldr-stat-item">- <i class="fas fa-clock"></i>- <span>${new Date(collection.created_at).toLocaleDateString()}</span>+ <div class="ldr-collection-card-wrapper" data-id="${escapeHtml(collection.id)}">+ <a href="/library/collections/${encodeURIComponent(collection.id)}" class="ldr-collection-card" style="text-decoration: none; color: inherit; cursor: pointer;">+ <div class="ldr-collection-header">+ <h3>${escapeHtml(collection.name)}</h3>+ ${collection.description ? `<p class="ldr-collection-description">${escapeHtml(collection.description)}</p>` : ''}</div>- ` : ''}- ${collection.embedding ? `- <div class="ldr-stat-item ldr-embedding-info">- <i class="fas fa-microchip"></i>- <span title="Embedding: ${escapeHtml(collection.embedding.provider)}/${escapeHtml(collection.embedding.model)}">${escapeHtml(collection.embedding.model)}</span>- </div>- ` : `- <div class="ldr-stat-item ldr-embedding-warning">- <i class="fas fa-exclamation-triangle"></i>- <span title="Collection not yet indexed">Not indexed</span>++ <div class="ldr-collection-stats">+ <div class="ldr-stat-item">+ <i class="fas fa-file"></i>+ <span>${Math.max(0, Math.trunc(Number(collection.document_count) || 0))} documents</span>+ </div>+ ${collection.created_at ? `+ <div class="ldr-stat-item">+ <i class="fas fa-clock"></i>+ <span>${new Date(collection.created_at).toLocaleDateString()}</span>+ </div>+ ` : ''}+ ${indexStatusMarkup(collection)}+ ${collection.embedding ? `+ <div class="ldr-stat-item ldr-embedding-info">+ <i class="fas fa-microchip"></i>+ <span title="Embedding: ${escapeHtml(collection.embedding.provider)}/${escapeHtml(collection.embedding.model)}">${escapeHtml(collection.embedding.model)}</span>+ </div>+ ` : ''}</div>- `}- </div>+ </a>- <div class="ldr-collection-view-link">- <span>View</span>- <i class="fas fa-arrow-right"></i>+ <div class="ldr-collection-card-actions">+ <button type="button" class="ldr-reindex-btn" data-reindex-id="${escapeHtml(collection.id)}" title="Index any documents in this collection that aren't indexed yet">+ <i class="fas fa-sync-alt"></i>+ <span class="ldr-reindex-label">Reindex</span>+ </button>+ <a href="/library/collections/${encodeURIComponent(collection.id)}" class="ldr-collection-view-link" style="text-decoration: none;">+ <span>View</span>+ <i class="fas fa-arrow-right"></i>+ </a></div>- </a>+ </div>`).join('');++ bindReindexButtons(container);+}++/**+ * Wire up the per-card Reindex buttons.+ *+ * The Reindex button is a sibling of the card <a> (not a child), so it can't+ * itself trigger navigation. The click is still preventDefault()/+ * stopPropagation()'d defensively so it never bubbles into any ancestor link+ * handler. Uses a single delegated listener on the container.+ */+function bindReindexButtons(container) {+ if (!container || container.dataset.reindexBound === 'true') return;+ container.dataset.reindexBound = 'true';+ container.addEventListener('click', (event) => {+ const btn = event.target.closest('.ldr-reindex-btn');+ if (!btn) return;+ // Defensive: keep the click from bubbling into any ancestor link.+ event.preventDefault();+ event.stopPropagation();+ triggerReindex(btn);+ });+}++/**+ * Build a Library API URL from the templated entry in URLS, substituting {id}.+ */+function collectionApiUrl(template, collectionId) {+ return template.replace('{id}', encodeURIComponent(collectionId));+}++/**+ * Start background indexing for a single collection and reflect progress on+ * its Reindex button. Refreshes the card's counts when indexing finishes.+ *+ * Triggered from the per-card Reindex button (a sibling of the card <a>);+ * the caller has already preventDefault()/stopPropagation()'d the click.+ */+async function triggerReindex(btn) {+ const collectionId = btn.getAttribute('data-reindex-id');+ if (!collectionId || btn.disabled) return;++ const label = btn.querySelector('.ldr-reindex-label');+ const icon = btn.querySelector('i');+ const originalLabel = label ? label.textContent : '';++ const setBusy = (busy, text) => {+ btn.disabled = busy;+ if (icon) icon.classList.toggle('fa-spin', busy);+ if (label && text !== undefined) label.textContent = text;+ };++ setBusy(true, 'Indexing…');++ try {+ const csrfToken = window.api ? window.api.getCsrfToken() : '';+ const startUrl = collectionApiUrl(URLS.LIBRARY_API.COLLECTION_INDEX_START, collectionId);+ const response = await safeFetch(startUrl, {+ method: 'POST',+ headers: {+ 'Content-Type': 'application/json',+ 'X-CSRFToken': csrfToken+ },+ body: JSON.stringify({ force_reindex: false })+ });+ const data = await response.json();++ if (!response.ok || !data.success) {+ // 409 means indexing is already running for this collection — still+ // poll so the button tracks the in-flight task to completion.+ if (response.status !== 409) {+ SafeLogger.error('Failed to start reindex:', data.error);+ showError(data.error || 'Failed to start indexing');+ setBusy(false, originalLabel);+ return;+ }+ }++ const finalStatus = await pollReindexStatus(collectionId);+ // Surface a failure that happened DURING polling (the poller only+ // logs it) so the user isn't left with a silently-failed reindex.+ if (finalStatus) {+ if (finalStatus.status === 'failed' || finalStatus.status === 'error') {+ showError(finalStatus.error_message || finalStatus.error || 'Indexing failed');+ } else if (finalStatus.status === 'timeout') {+ showError('Indexing is taking longer than expected. It may still be running in the background — refresh to check.');+ }+ }+ } catch (error) {+ SafeLogger.error('Error starting reindex:', error);+ showError('Failed to start indexing');+ setBusy(false, originalLabel);+ return;+ }++ setBusy(false, originalLabel);+ // Refresh counts so the "X of Y indexed" / pending status reflects the result.+ await loadCollections();+}++/**+ * Poll the collection index status until it reaches a terminal state.+ * Resolves once indexing is no longer "processing".+ *+ * Bounded so a worker stuck at "processing" (or a flapping endpoint) can't+ * disable the Reindex button forever: gives up after POLL_MAX_ATTEMPTS polls+ * (~10 min at a 2s interval) or POLL_MAX_ERRORS consecutive fetch errors,+ * resolving with a synthetic {status:'timeout'} / null so the caller can+ * re-enable the button and surface a message. Mirrors the bounded poll in+ * components/history_search.js.+ */+async function pollReindexStatus(collectionId) {+ const statusUrl = collectionApiUrl(URLS.LIBRARY_API.COLLECTION_INDEX_STATUS, collectionId);+ const TERMINAL = ['completed', 'failed', 'cancelled', 'error', 'idle'];+ const POLL_INTERVAL_MS = 2000;+ const POLL_MAX_ATTEMPTS = 300; // ~10 minutes at 2s/poll+ const POLL_MAX_ERRORS = 5; // consecutive fetch errors before bailing++ return new Promise((resolve) => {+ let attempts = 0;+ let errorCount = 0;+ const poll = async () => {+ attempts += 1;+ try {+ const response = await safeFetch(statusUrl);+ // safeFetch does NOT throw on HTTP errors, and the status+ // endpoint's except path returns 500 with body {status:'error'}+ // — which is in TERMINAL. Without this guard a single transient+ // 500 would resolve the poll and fire a false "reindex failed"+ // alert while indexing is still running. Treat an HTTP error as+ // a transient failure (counts toward the error budget → retry),+ // mirroring components/history_search.js.+ if (!response.ok) {+ throw new Error(`Status endpoint returned ${response.status}`);+ }+ const data = await response.json();+ errorCount = 0;+ if (TERMINAL.includes(data.status)) {+ if (data.status === 'failed' || data.status === 'error') {+ SafeLogger.error('Reindex failed:', data.error_message || data.error);+ }+ resolve(data);+ return;+ }+ } catch (error) {+ SafeLogger.error('Error polling reindex status:', error);+ errorCount += 1;+ if (errorCount >= POLL_MAX_ERRORS) {+ resolve(null);+ return;+ }+ }+ if (attempts >= POLL_MAX_ATTEMPTS) {+ SafeLogger.warn('Reindex status poll timed out; giving up.');+ resolve({ status: 'timeout' });+ return;+ }+ setTimeout(poll, POLL_INTERVAL_MS);+ };+ poll();+ });}/**@@ -157,3 +512,14 @@ function showSuccess(message) {function showError(message) {alert('Error: ' + message);}++// Expose internals for unit tests (consumed in tests/js; harmless in prod).+if (typeof window !== 'undefined') {+ window.indexStatusMarkup = indexStatusMarkup;+ window.renderCollections = renderCollections;+ window.bindReindexButtons = bindReindexButtons;+ window.triggerReindex = triggerReindex;+ window.collectionApiUrl = collectionApiUrl;+ window.loadBackgroundSweepSetting = loadBackgroundSweepSetting;+ window.saveBackgroundSweepSetting = saveBackgroundSweepSetting;+}diff --git a/src/local_deep_research/web/templates/pages/collections.html b/src/local_deep_research/web/templates/pages/collections.htmlindex 7ca8cf57f9..af69a1166b 100644--- a/src/local_deep_research/web/templates/pages/collections.html+++ b/src/local_deep_research/web/templates/pages/collections.html@@ -38,6 +38,17 @@style="width: 16px; height: 16px;"><span><i aria-hidden="true" class="fas fa-magic"></i> {{ tooltip("Auto-index new documents", "When enabled, documents uploaded or downloaded to any collection are automatically indexed for semantic search.") }}</span></label>+ <!-- Background-Sweep Toggle (scheduled reconciler, #4627).+ Hidden until the backend setting is registered (see+ loadBackgroundSweepSetting): the wrapper starts hidden and+ is only revealed once the GET confirms the setting exists. -->+ <label id="background-sweep-toggle-row" class="ldr-checkbox-label" style="display: none; align-items: center; cursor: pointer; gap: 8px; font-size: 14px;">+ <input type="checkbox"+ id="background-sweep-toggle"+ class="ldr-settings-checkbox"+ style="width: 16px; height: 16px;">+ <span><i aria-hidden="true" class="fas fa-clock-rotate-left"></i> {{ tooltip("Index documents in the background (scheduled)", "When enabled, a scheduled background job periodically scans your collections and indexes any documents that weren't indexed immediately (e.g. when the immediate auto-index queue was full). Requires the document scheduler to be enabled. Off by default.") }}</span>+ </label><a href="/library/collections/create" id="create-collection-btn" class="ldr-btn-collections ldr-btn-collections-primary"><i aria-hidden="true" class="fas fa-plus"></i> Create Collection</a>diff --git a/tests/js/collections-manager.test.js b/tests/js/collections-manager.test.jsnew file mode 100644index 0000000000..2b04833d0d--- /dev/null+++ b/tests/js/collections-manager.test.js@@ -0,0 +1,835 @@+/**+ * Tests for collections_manager.js — the Collections page.+ *+ * Covers the index-status surface and reindex action added in the+ * #3939/#4627 follow-up, plus the background-sweep toggle persistence:+ * - indexStatusMarkup(): "<indexed> of <total> indexed" string + the+ * "<pending> pending indexing" badge, with numeric coercion / clamping.+ * - triggerReindex(): POSTs to the index/start endpoint, polls status to a+ * terminal state, keeps the button disabled in-flight, refreshes counts,+ * and (critically) the card is an <a> so the click must NOT navigate.+ * - loadBackgroundSweepSetting()/saveBackgroundSweepSetting(): read/write the+ * document_scheduler.sweep_library_collections setting.+ */++// --- Global stubs the module reaches for at call time ----------------------+window.URLS = {+ LIBRARY_API: {+ COLLECTIONS: '/library/api/collections',+ COLLECTION_INDEX_START: '/library/api/collections/{id}/index/start',+ COLLECTION_INDEX_STATUS: '/library/api/collections/{id}/index/status',+ },+};+// escapeHtml is captured at module load via `window.escapeHtml || fallback`.+window.escapeHtml = (s) => String(s);+window.api = { getCsrfToken: () => 'test-csrf' };+globalThis.alert = () => {};++// safeFetch is a global the module calls; default to a benign stub so the+// import-time DOMContentLoaded handler (if it fires) doesn't explode.+globalThis.safeFetch = vi.fn(() =>+ Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) })+);++let indexStatusMarkup;+let triggerReindex;+let bindReindexButtons;+let collectionApiUrl;+let loadBackgroundSweepSetting;+let saveBackgroundSweepSetting;++beforeAll(async () => {+ await import('@js/collections_manager.js');+ indexStatusMarkup = window.indexStatusMarkup;+ triggerReindex = window.triggerReindex;+ bindReindexButtons = window.bindReindexButtons;+ collectionApiUrl = window.collectionApiUrl;+ loadBackgroundSweepSetting = window.loadBackgroundSweepSetting;+ saveBackgroundSweepSetting = window.saveBackgroundSweepSetting;+});++beforeEach(() => {+ globalThis.safeFetch.mockReset();+});++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 });+ expect(html).toContain('2 of 5 indexed');+ expect(html).toContain('3 pending indexing');+ expect(html).toContain('ldr-pending-index-badge');+ });++ it('omits the pending badge when everything is indexed', () => {+ const html = indexStatusMarkup({ document_count: 4, indexed_document_count: 4 });+ expect(html).toContain('4 of 4 indexed');+ expect(html).not.toContain('pending indexing');+ // Fully-indexed gets the success styling, not the warning badge.+ expect(html).toContain('fa-check-circle');+ });++ it('shows "No documents" for an empty collection (no divide-by-zero / no badge)', () => {+ const html = indexStatusMarkup({ document_count: 0, indexed_document_count: 0 });+ expect(html).toContain('No documents');+ expect(html).not.toContain('pending indexing');+ });++ it('clamps indexed to total and coerces non-numeric counts to integers', () => {+ // indexed > total (stale payload) must not produce a negative pending.+ const html = indexStatusMarkup({ document_count: 3, indexed_document_count: 9 });+ expect(html).toContain('3 of 3 indexed');+ expect(html).not.toContain('pending indexing');++ // Garbage values coerce to 0, not NaN.+ const html2 = indexStatusMarkup({ document_count: 'x', indexed_document_count: 'y' });+ expect(html2).toContain('No documents');+ expect(html2).not.toContain('NaN');+ });+});++describe('collectionApiUrl', () => {+ it('substitutes {id} with an encoded collection id', () => {+ expect(collectionApiUrl('/a/{id}/b', 'c d')).toBe('/a/c%20d/b');+ });+});++describe('triggerReindex', () => {+ function makeButton(id) {+ // Build via the DOM API (not innerHTML interpolation) so the+ // no-unsanitized lint rule stays clean. Mirrors renderCollections():+ // a wrapper <div> holds the clickable card <a> plus a SIBLING actions+ // row that contains the Reindex button (never nested in the anchor).+ document.body.innerHTML = '';+ const wrapper = document.createElement('div');+ wrapper.className = 'ldr-collection-card-wrapper';+ wrapper.setAttribute('data-id', id);++ const link = document.createElement('a');+ link.href = `/library/collections/${encodeURIComponent(id)}`;+ link.className = 'ldr-collection-card';++ const actions = document.createElement('div');+ actions.className = 'ldr-collection-card-actions';+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'ldr-reindex-btn';+ btn.setAttribute('data-reindex-id', id);+ const icon = document.createElement('i');+ icon.className = 'fas fa-sync-alt';+ const label = document.createElement('span');+ label.className = 'ldr-reindex-label';+ label.textContent = 'Reindex';+ btn.append(icon, label);+ actions.appendChild(btn);++ wrapper.append(link, actions);+ document.body.appendChild(wrapper);+ return btn;+ }++ // triggerReindex() ends with loadCollections(), which writes to+ // #collections-container / #no-collections-message. The bounded-poll tests+ // below assert "no error alert", so those elements must exist or+ // loadCollections() throws and spuriously fires showError('Failed to load+ // collections'). Add them and re-parent the card wrapper into the+ // container (so the loadCollections success path is exercised, not an+ // empty-DOM crash).+ function withCollectionsContainer(btn) {+ const wrapper = btn.closest('.ldr-collection-card-wrapper');+ const container = document.createElement('div');+ container.id = 'collections-container';+ container.appendChild(wrapper);+ const noMsg = document.createElement('div');+ noMsg.id = 'no-collections-message';+ document.body.append(container, noMsg);+ }++ it('POSTs to the start endpoint, polls to completion, and refreshes counts', async () => {+ const btn = makeButton('coll-1');+ const calls = [];+ globalThis.safeFetch.mockImplementation((url, opts) => {+ calls.push({ url, method: opts && opts.method });+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, task_id: 't1' }) });+ }+ if (url.includes('/index/status')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) });+ }+ // loadCollections() refresh+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ await triggerReindex(btn);++ const start = calls.find(c => c.url.includes('/index/start'));+ expect(start).toBeTruthy();+ expect(start.method).toBe('POST');+ expect(start.url).toBe('/library/api/collections/coll-1/index/start');+ // Polled status at least once.+ expect(calls.some(c => c.url.includes('/index/status'))).toBe(true);+ // Refreshed the collection list afterwards.+ expect(calls.some(c => c.url === '/library/api/collections')).toBe(true);+ // Button re-enabled after completion.+ expect(btn.disabled).toBe(false);+ });++ it('keeps the button disabled while indexing is in flight', async () => {+ const btn = makeButton('coll-2');+ let resolveStatus;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ // First status call hangs until we resolve it — simulates in-flight.+ return new Promise((res) => { resolveStatus = () => res({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) }); });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ // Let the start POST + first status fetch be issued.+ await Promise.resolve();+ await Promise.resolve();+ expect(btn.disabled).toBe(true);++ resolveStatus();+ await promise;+ expect(btn.disabled).toBe(false);+ });++ it('does not navigate when the Reindex button is clicked (button is a sibling of the card <a>)', async () => {+ const btn = makeButton('coll-3');+ const container = document.createElement('div');+ container.id = 'collections-container';+ // Move the whole card wrapper into a real container so delegation matches.+ container.appendChild(btn.closest('.ldr-collection-card-wrapper'));+ document.body.appendChild(container);++ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'idle' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ bindReindexButtons(container);++ const event = new window.MouseEvent('click', { bubbles: true, cancelable: true });+ btn.dispatchEvent(event);++ // The delegated handler must have prevented default navigation.+ expect(event.defaultPrevented).toBe(true);+ });++ it('surfaces an error to the user when indexing fails during polling', async () => {+ const btn = makeButton('coll-4');+ // showError() routes through alert(); spy on it.+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'failed', error_message: 'embedding model missing' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ await triggerReindex(btn);++ // The terminal failed status must reach the user, not just the log.+ expect(alertSpy).toHaveBeenCalled();+ const messages = alertSpy.mock.calls.map(c => String(c[0])).join(' ');+ expect(messages).toContain('embedding model missing');+ // Button re-enabled even though it failed.+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ });++ // --- Start-endpoint failure handling -----------------------------------+ // The /index/start POST can come back non-OK. The handler distinguishes a+ // generic start failure (any non-409) — surface the error, skip polling,+ // re-enable the button — from a 409 "already running" (fall THROUGH and+ // poll the in-flight task to completion). The mocks above always return a+ // 200/success start, so neither branch is exercised by them.++ it('on a generic start failure: surfaces the error, does NOT poll, and re-enables the button', async () => {+ const btn = makeButton('coll-start-fail');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ const logSpy = vi.spyOn(globalThis.SafeLogger, 'error');+ const calls = [];+ globalThis.safeFetch.mockImplementation((url) => {+ calls.push({ url });+ if (url.includes('/index/start')) {+ // Non-OK, non-409 start: e.g. the worker is busy / a 500.+ return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({ success: false, error: 'busy' }) });+ }+ if (url.includes('/index/status')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ await triggerReindex(btn);++ // The start error reaches the user (showError → alert) with the message.+ expect(alertSpy).toHaveBeenCalled();+ const messages = alertSpy.mock.calls.map(c => String(c[0])).join(' ');+ expect(messages).toContain('busy');+ expect(logSpy).toHaveBeenCalled();+ // The early return skips polling entirely — the status endpoint is never hit.+ expect(calls.some(c => c.url.includes('/index/status'))).toBe(false);+ // Button re-enabled and label restored so the user can retry.+ expect(btn.disabled).toBe(false);+ expect(btn.querySelector('.ldr-reindex-label').textContent).toBe('Reindex');+ logSpy.mockRestore();+ alertSpy.mockRestore();+ });++ it('on a 409 "already running" start: does NOT early-return — falls through and polls to completion', async () => {+ const btn = makeButton('coll-start-409');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ const calls = [];+ globalThis.safeFetch.mockImplementation((url) => {+ calls.push({ url });+ if (url.includes('/index/start')) {+ // 409 = indexing is already in flight for this collection.+ return Promise.resolve({ ok: false, status: 409, json: () => Promise.resolve({ success: false, error: 'already running' }) });+ }+ if (url.includes('/index/status')) {+ // Drive a terminal status so the fall-through poll resolves.+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ await triggerReindex(btn);++ // 409 must fall through to polling — the status endpoint IS hit, unlike+ // the generic-failure case above which returns before polling.+ expect(calls.some(c => c.url.includes('/index/status'))).toBe(true);+ // The 409 itself is not surfaced as an error; completion is clean.+ expect(alertSpy).not.toHaveBeenCalled();+ // Button re-enabled once the in-flight task is tracked to completion.+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ });++ // --- Bounded-poll loop coverage ----------------------------------------+ // The status mocks above all resolve TERMINAL on the FIRST poll, so the+ // loop's bounding logic (the 2s setTimeout re-poll, the consecutive-error+ // counter + its reset-on-success, the POLL_MAX_ERRORS bail, the+ // POLL_MAX_ATTEMPTS timeout cap, and the !response.ok HTTP-error guard) is+ // never executed by them. These tests drive the loop across multiple polls+ // using fake timers so mutations to that logic fail.++ it('polls across the 2s interval through several "processing" responses before completing', async () => {+ vi.useFakeTimers();+ try {+ const btn = makeButton('coll-poll-1');+ withCollectionsContainer(btn);+ let statusCalls = 0;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ statusCalls += 1;+ // Stay "processing" for the first 3 polls, then complete.+ const status = statusCalls >= 4 ? 'completed' : 'processing';+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ // Each non-terminal poll re-arms a 2s setTimeout; advance enough to+ // walk through all of them.+ await vi.advanceTimersByTimeAsync(2000 * 5);+ await promise;++ // Must have polled more than once (the loop actually iterated).+ expect(statusCalls).toBeGreaterThanOrEqual(4);+ expect(btn.disabled).toBe(false);+ } finally {+ vi.useRealTimers();+ }+ });++ it('retries through consecutive fetch errors (error counter resets on success) and completes', async () => {+ vi.useFakeTimers();+ try {+ const btn = makeButton('coll-poll-errreset');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ let statusCalls = 0;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ statusCalls += 1;+ // Pattern: 4 errors, success(processing), 4 errors,+ // success(completed). 8 transient errors total, but never 5+ // IN A ROW. This is mutation-sensitive: if the reset-on-+ // success (`errorCount = 0;`) is removed, the counter+ // accumulates past POLL_MAX_ERRORS (5) on the 5th cumulative+ // error → the poll bails (resolve null), the loop never+ // reaches the completed status, and statusCalls stops at 5.+ // With the reset, each group of 4 stays under the limit and+ // the poll reaches completion.+ if (statusCalls >= 1 && statusCalls <= 4) {+ return Promise.reject(new Error('network down'));+ }+ if (statusCalls === 5) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'processing' }) });+ }+ if (statusCalls >= 6 && statusCalls <= 9) {+ return Promise.reject(new Error('network down'));+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ await vi.advanceTimersByTimeAsync(2000 * 12);+ await promise;++ // Reached the terminal completed status (statusCall #10) despite 8+ // transient errors — only possible because errorCount resets on the+ // intervening success.+ expect(statusCalls).toBeGreaterThanOrEqual(10);+ // Completion is not a failure → no error alert.+ expect(alertSpy).not.toHaveBeenCalled();+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ } finally {+ vi.useRealTimers();+ }+ });++ it('bails (resolve null, no error alert) after POLL_MAX_ERRORS consecutive fetch errors', async () => {+ vi.useFakeTimers();+ try {+ const btn = makeButton('coll-poll-errbail');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ let statusCalls = 0;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ statusCalls += 1;+ return Promise.reject(new Error('network down'));+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ await vi.advanceTimersByTimeAsync(2000 * 10);+ await promise;++ // Bails after exactly POLL_MAX_ERRORS (5) consecutive errors —+ // does NOT keep polling forever.+ expect(statusCalls).toBe(5);+ // Bail resolves null → triggerReindex shows no error alert.+ expect(alertSpy).not.toHaveBeenCalled();+ // Button re-enabled.+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ } finally {+ vi.useRealTimers();+ }+ });++ it('caps at POLL_MAX_ATTEMPTS, resolves {status:"timeout"}, and shows a timeout error', async () => {+ vi.useFakeTimers();+ try {+ const btn = makeButton('coll-poll-timeout');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ let statusCalls = 0;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ statusCalls += 1;+ // Never terminal → must hit the POLL_MAX_ATTEMPTS cap.+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'processing' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ // POLL_MAX_ATTEMPTS = 300 at 2s/poll ≈ 600s; advance generously.+ await vi.advanceTimersByTimeAsync(2000 * 305);+ await promise;++ // Stopped at the 300-attempt cap, not forever.+ expect(statusCalls).toBe(300);+ // timeout status → showError fires the "taking longer" message.+ expect(alertSpy).toHaveBeenCalled();+ const messages = alertSpy.mock.calls.map(c => String(c[0])).join(' ');+ expect(messages).toContain('taking longer than expected');+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ } finally {+ vi.useRealTimers();+ }+ });++ it('treats a transient HTTP 500 as retryable (not terminal) and completes without a false failure alert', async () => {+ vi.useFakeTimers();+ try {+ const btn = makeButton('coll-poll-http500');+ withCollectionsContainer(btn);+ const alertSpy = vi.spyOn(globalThis, 'alert').mockImplementation(() => {});+ let statusCalls = 0;+ globalThis.safeFetch.mockImplementation((url) => {+ if (url.includes('/index/start')) {+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true }) });+ }+ if (url.includes('/index/status')) {+ statusCalls += 1;+ if (statusCalls === 1) {+ // The endpoint's except path returns 500 {status:'error'}.+ // Without the !response.ok guard this 'error' body is+ // TERMINAL and would fire a false "reindex failed" alert.+ return Promise.resolve({ ok: false, status: 500, json: () => Promise.resolve({ status: 'error' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ status: 'completed' }) });+ }+ return Promise.resolve({ ok: true, status: 200, json: () => Promise.resolve({ success: true, collections: [] }) });+ });++ const promise = triggerReindex(btn);+ await vi.advanceTimersByTimeAsync(2000 * 3);+ await promise;++ // Retried after the 500 and reached completion.+ expect(statusCalls).toBeGreaterThanOrEqual(2);+ // No false "failed" alert — the transient 500 was not treated as terminal.+ expect(alertSpy).not.toHaveBeenCalled();+ expect(btn.disabled).toBe(false);+ alertSpy.mockRestore();+ } finally {+ vi.useRealTimers();+ }+ });+});++describe('background-sweep toggle', () => {+ function makeToggle() {+ // Mirror the template: the checkbox lives inside a wrapper row that+ // starts hidden and is only revealed once the backend setting exists.+ document.body.innerHTML =+ '<label id="background-sweep-toggle-row" style="display: none;">' ++ '<input type="checkbox" id="background-sweep-toggle"></label>';+ return document.getElementById('background-sweep-toggle');+ }++ function getRow() {+ return document.getElementById('background-sweep-toggle-row');+ }++ it('loads the toggle state from document_scheduler.sweep_library_collections', async () => {+ const toggle = makeToggle();+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: true }),+ });++ await loadBackgroundSweepSetting();++ expect(globalThis.safeFetch).toHaveBeenCalledWith(+ '/settings/api/document_scheduler.sweep_library_collections'+ );+ expect(toggle.checked).toBe(true);+ // Setting exists → the row is revealed.+ expect(getRow().style.display).toBe('flex');+ });++ it('leaves the toggle unchecked when the setting value is false', async () => {+ const toggle = makeToggle();+ toggle.checked = true; // start checked to prove it flips off+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: false }),+ });++ await loadBackgroundSweepSetting();++ expect(toggle.checked).toBe(false);+ expect(getRow().style.display).toBe('flex');+ });++ it('treats a stringified "true" value as checked', async () => {+ const toggle = makeToggle();+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: 'true' }),+ });++ await loadBackgroundSweepSetting();++ expect(toggle.checked).toBe(true);+ expect(getRow().style.display).toBe('flex');+ });++ it('hides the row when the setting is not registered (404 / not ok)', async () => {+ // Before #4627 merges, the setting GET returns 404 — the toggle must be+ // hidden rather than shown as a dead, always-unchecked control.+ makeToggle();+ getRow().style.display = 'flex'; // pretend it was visible+ globalThis.safeFetch.mockResolvedValue({+ ok: false,+ status: 404,+ json: () => Promise.resolve({ error: 'not found' }),+ });++ await loadBackgroundSweepSetting();++ expect(getRow().style.display).toBe('none');+ });++ it('persists a toggle change via PUT to the same setting key', async () => {+ const toggle = makeToggle();+ toggle.checked = true;+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: true }),+ });++ await saveBackgroundSweepSetting();++ const [url, opts] = globalThis.safeFetch.mock.calls[0];+ expect(url).toBe('/settings/api/document_scheduler.sweep_library_collections');+ expect(opts.method).toBe('PUT');+ expect(JSON.parse(opts.body)).toEqual({ value: true });+ // Save succeeded, so the optimistic UI state is preserved.+ expect(toggle.checked).toBe(true);+ });++ it('reverts the toggle when the save fails', async () => {+ const toggle = makeToggle();+ toggle.checked = true;+ globalThis.safeFetch.mockResolvedValue({+ ok: false,+ json: () => Promise.resolve({ error: 'boom' }),+ });++ await saveBackgroundSweepSetting();++ expect(toggle.checked).toBe(false);+ });++ it('shows the toggle ON when only the legacy generate_rag arm is set (effective gate)', async () => {+ // The reconciler runs on (sweep OR generate_rag). An upgraded user with+ // generate_rag=true, sweep=false must NOT see an OFF toggle while the+ // sweep is actively running every tick.+ const toggle = makeToggle();+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }); // generate_rag++ await loadBackgroundSweepSetting();++ expect(globalThis.safeFetch).toHaveBeenNthCalledWith(+ 1, '/settings/api/document_scheduler.sweep_library_collections'+ );+ expect(globalThis.safeFetch).toHaveBeenNthCalledWith(+ 2, '/settings/api/document_scheduler.generate_rag'+ );+ expect(toggle.checked).toBe(true);+ expect(getRow().style.display).toBe('flex');+ });++ it('does not read the legacy arm when sweep is already ON', async () => {+ const toggle = makeToggle();+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: true }),+ });++ await loadBackgroundSweepSetting();++ // Only the sweep key is read; the legacy arm is irrelevant when sweep is on.+ expect(globalThis.safeFetch).toHaveBeenCalledTimes(1);+ expect(toggle.checked).toBe(true);+ });++ it('turning OFF clears the legacy generate_rag arm WHEN it is set', async () => {+ // Otherwise OFF would leave generate_rag armed and the sweep running.+ const toggle = makeToggle();+ toggle.checked = false; // user just turned it OFF+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set)+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=false++ await saveBackgroundSweepSetting();++ const calls = globalThis.safeFetch.mock.calls;+ expect(calls).toHaveLength(3);+ expect(calls[0][0]).toBe('/settings/api/document_scheduler.sweep_library_collections');+ expect(calls[0][1].method).toBe('PUT');+ expect(JSON.parse(calls[0][1].body)).toEqual({ value: false });+ expect(calls[1][0]).toBe('/settings/api/document_scheduler.generate_rag');+ expect(calls[1][1]).toBeUndefined(); // a GET (read-first), not a PUT+ expect(calls[2][0]).toBe('/settings/api/document_scheduler.generate_rag');+ expect(JSON.parse(calls[2][1].body)).toEqual({ value: false });+ expect(toggle.checked).toBe(false);+ });++ it('turning OFF does NOT write generate_rag when it is already false', async () => {+ // Read-first: skip the redundant PUT (and the cross-page surprise ++ // extra reschedule) for the common default-install case.+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // GET generate_rag (already off)++ await saveBackgroundSweepSetting();++ const calls = globalThis.safeFetch.mock.calls;+ expect(calls).toHaveLength(2); // sweep PUT + generate_rag GET, no second PUT+ expect(calls[1][1]).toBeUndefined(); // the generate_rag call was a GET+ expect(toggle.checked).toBe(false);+ });++ it('OFF with a failed generate_rag clear stays ON (still armed via legacy arm)', async () => {+ // sweep=false persisted, but clearing generate_rag failed, so the+ // reconciler is still armed — the honest displayed state is ON, not OFF.+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set)+ .mockResolvedValueOnce({ ok: false, json: () => Promise.resolve({ error: 'boom' }) }); // PUT generate_rag fails++ await saveBackgroundSweepSetting();++ expect(toggle.checked).toBe(true);+ });++ it('a transient failure reading the legacy arm on load does not hide the control', async () => {+ // sweep read succeeds (false); the secondary generate_rag read rejects+ // at the network level. The row must be REVEALED (start hidden, as in+ // the template) and show the sweep-derived state.+ const toggle = makeToggle();+ expect(getRow().style.display).toBe('none'); // starts hidden per template+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep+ .mockRejectedValueOnce(new Error('network down')); // generate_rag GET rejects++ await loadBackgroundSweepSetting();++ expect(getRow().style.display).toBe('flex'); // reveal still fired+ expect(toggle.checked).toBe(false);+ });++ it('treats a stringified "true" generate_rag value as ON (effective gate)', async () => {+ const toggle = makeToggle();+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // sweep+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: 'true' }) }); // generate_rag (string)++ await loadBackgroundSweepSetting();++ expect(toggle.checked).toBe(true);+ });++ it('turning OFF still clears generate_rag when its value cannot be read (conservative on unknown)', async () => {+ // The regression the prior fix reopened: a transient generate_rag read+ // failure must NOT be treated as "already off" — OFF must still attempt+ // the clear so the reconciler can never stay silently armed.+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockRejectedValueOnce(new Error('network blip')) // GET generate_rag rejects -> null (unknown)+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=false++ await saveBackgroundSweepSetting();++ const calls = globalThis.safeFetch.mock.calls;+ expect(calls).toHaveLength(3);+ expect(calls[2][0]).toBe('/settings/api/document_scheduler.generate_rag');+ expect(calls[2][1].method).toBe('PUT'); // clear was still attempted+ expect(JSON.parse(calls[2][1].body)).toEqual({ value: false });+ expect(toggle.checked).toBe(false); // clear succeeded -> honest OFF+ });++ it('turning OFF clears generate_rag when the read returns not-ok (unknown, not just reject)', async () => {+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockResolvedValueOnce({ ok: false, status: 500, json: () => Promise.resolve({ error: 'x' }) }) // GET generate_rag !ok -> null+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }); // PUT generate_rag=false++ await saveBackgroundSweepSetting();++ const calls = globalThis.safeFetch.mock.calls;+ expect(calls).toHaveLength(3);+ expect(calls[2][1].method).toBe('PUT'); // unknown -> still cleared+ expect(toggle.checked).toBe(false);+ });++ it('OFF with unknown legacy read AND a failed clear stays ON (conservative)', async () => {+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockRejectedValueOnce(new Error('blip')) // GET generate_rag -> null+ .mockResolvedValueOnce({ ok: false, json: () => Promise.resolve({ error: 'boom' }) }); // PUT generate_rag fails++ await saveBackgroundSweepSetting();++ // Couldn't confirm generate_rag is off -> don't claim a false OFF.+ expect(toggle.checked).toBe(true);+ });++ it('OFF stays ON when the clear PUT rejects at the network level (outer catch)', async () => {+ // The clear-PUT failure must be handled whether it surfaces as {ok:false}+ // or as a thrown network rejection (the outer catch) — both must leave+ // the toggle honestly ON since generate_rag may still be armed.+ const toggle = makeToggle();+ toggle.checked = false;+ globalThis.safeFetch+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: false }) }) // PUT sweep=false+ .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ value: true }) }) // GET generate_rag (set)+ .mockRejectedValueOnce(new Error('network down')); // PUT generate_rag rejects -> outer catch++ await saveBackgroundSweepSetting();++ expect(toggle.checked).toBe(true);+ });++ it('turning ON writes only sweep=true (does not touch the legacy arm)', async () => {+ const toggle = makeToggle();+ toggle.checked = true; // user just turned it ON+ globalThis.safeFetch.mockResolvedValue({+ ok: true,+ json: () => Promise.resolve({ value: true }),+ });++ await saveBackgroundSweepSetting();++ const calls = globalThis.safeFetch.mock.calls;+ expect(calls).toHaveLength(1);+ expect(calls[0][0]).toBe('/settings/api/document_scheduler.sweep_library_collections');+ expect(JSON.parse(calls[0][1].body)).toEqual({ value: true });+ expect(toggle.checked).toBe(true);+ });+});diff --git a/tests/research_library/routes/test_rag_routes.py b/tests/research_library/routes/test_rag_routes.pyindex 395a977ebe..ea1a7449ab 100644--- a/tests/research_library/routes/test_rag_routes.py+++ b/tests/research_library/routes/test_rag_routes.py@@ -2850,3 +2850,396 @@ class TestEmbeddingProviderAvailability:assert option["available"] is Trueassert isinstance(option["available"], bool)+++class TestGetCollectionsIndexedCounts:+ """Real-payload tests for GET /library/api/collections.++ Seeds an in-memory SQLite database with a collection holding a mix of+ indexed and unindexed document links, then asserts the serialized+ payload reports both the total ``document_count`` and the+ ``indexed_document_count`` aggregate (the data backing the UI's+ "X of Y indexed" / pending-index status). The route computes the+ indexed count via a single grouped aggregate, so this also guards+ against an accidental N+1 / per-collection regression.+ """++ @staticmethod+ def _seed_session():+ """Return an in-memory session seeded with TWO collections.++ Collection A: 3 docs, 2 indexed (1 pending).+ Collection B: 2 docs, 1 indexed (1 pending).++ Two collections with *different* indexed/total splits are required so a+ missing ``.group_by(DocumentCollection.collection_id)`` (which would+ collapse the aggregate into a single global count) actually fails the+ assertions rather than coincidentally matching one collection's value.+ Returns ``(session, collection_a_id, collection_b_id)``.+ """+ import hashlib+ import uuid+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker+ from local_deep_research.database.models import Base+ from local_deep_research.database.models.library import (+ Collection,+ Document,+ DocumentCollection,+ DocumentStatus,+ SourceType,+ )++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ source_type = SourceType(+ id=str(uuid.uuid4()),+ name="user_upload",+ display_name="User Upload",+ description="Uploaded by user",+ icon="fas fa-upload",+ )+ session.add(source_type)+ session.commit()++ doc_counter = [0]++ def _add_collection(name, indexed_flags):+ collection = Collection(+ id=str(uuid.uuid4()),+ name=name,+ description="Mixed indexed/unindexed links",+ is_default=False,+ collection_type="user_collection",+ )+ session.add(collection)+ session.commit()++ for indexed in indexed_flags:+ i = doc_counter[0]+ doc_counter[0] += 1+ content = f"document body {i}"+ doc = Document(+ id=str(uuid.uuid4()),+ source_type_id=source_type.id,+ document_hash=hashlib.sha256(+ f"{i}{content}".encode()+ ).hexdigest(),+ file_size=len(content),+ file_type="text",+ text_content=content,+ title=f"Doc {i}",+ status=DocumentStatus.COMPLETED,+ )+ session.add(doc)+ session.commit()+ session.add(+ DocumentCollection(+ document_id=doc.id,+ collection_id=collection.id,+ indexed=indexed,+ )+ )+ session.commit()+ return collection.id++ # A: 3 docs, 2 indexed. B: 2 docs, 1 indexed — distinct splits.+ collection_a_id = _add_collection(+ "Indexed Status Collection A", (True, True, False)+ )+ collection_b_id = _add_collection(+ "Indexed Status Collection B", (True, False)+ )++ return session, collection_a_id, collection_b_id++ def _call_route(self, session):+ """Invoke the real route with auth + DB patched to ``session``."""+ from contextlib import contextmanager+ from flask import Flask+ from local_deep_research.research_library.routes.rag_routes import (+ rag_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["TESTING"] = True+ app.register_blueprint(rag_bp)+ app.register_blueprint(auth_bp)++ @contextmanager+ def fake_get_user_db_session(*a, **kw):+ yield session++ mock_db = Mock()+ mock_db.is_user_connected.return_value = True++ with (+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ mock_db,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=fake_get_user_db_session,+ ),+ ):+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session-id"+ return client.get("/library/api/collections")++ def test_payload_reports_total_and_indexed_counts(self):+ """Payload includes both counts with the seeded values (A: 3 total, 2 indexed)."""+ session, collection_a_id, _collection_b_id = self._seed_session()+ try:+ response = self._call_route(session)+ finally:+ session.close()++ assert response.status_code == 200, response.status_code+ data = response.get_json()+ assert data["success"] is True++ coll = next(+ c for c in data["collections"] if c["id"] == collection_a_id+ )+ # Total link count and the indexed-only aggregate.+ assert coll["document_count"] == 3+ assert coll["indexed_document_count"] == 2+ # Pending = total - indexed; the UI derives the "pending" badge from this.+ assert coll["document_count"] - coll["indexed_document_count"] == 1++ def test_each_collection_counts_are_independent(self):+ """Two collections with different splits must each report their OWN counts.++ Guards the per-collection ``GROUP BY``: collection A is 2-of-3 indexed+ and B is 1-of-2 indexed. If the aggregate dropped its+ ``group_by(collection_id)``, both would collapse to the same global+ count (3 indexed) and these per-collection assertions would fail.+ """+ session, collection_a_id, collection_b_id = self._seed_session()+ try:+ response = self._call_route(session)+ finally:+ session.close()++ assert response.status_code == 200, response.status_code+ by_id = {c["id"]: c for c in response.get_json()["collections"]}++ coll_a = by_id[collection_a_id]+ assert coll_a["document_count"] == 3+ assert coll_a["indexed_document_count"] == 2++ coll_b = by_id[collection_b_id]+ assert coll_b["document_count"] == 2+ assert coll_b["indexed_document_count"] == 1++ # The two collections must NOT share a count (catches a missing GROUP BY).+ assert (+ coll_a["indexed_document_count"] != coll_b["indexed_document_count"]+ )+ assert coll_a["document_count"] != coll_b["document_count"]++ def test_indexed_count_zero_when_nothing_indexed(self):+ """A collection with only unindexed links reports indexed_document_count == 0."""+ import uuid+ from local_deep_research.database.models.library import (+ DocumentCollection,+ )++ session, collection_a_id, _collection_b_id = self._seed_session()+ # Flip every link in collection A to unindexed.+ session.query(DocumentCollection).filter(+ DocumentCollection.collection_id == collection_a_id+ ).update({DocumentCollection.indexed: False})+ session.commit()+ # Sanity: ensure no stray collection id collision.+ assert uuid.UUID(collection_a_id)++ try:+ response = self._call_route(session)+ finally:+ session.close()++ assert response.status_code == 200, response.status_code+ coll = next(+ c+ for c in response.get_json()["collections"]+ if c["id"] == collection_a_id+ )+ assert coll["document_count"] == 3+ assert coll["indexed_document_count"] == 0+++class TestGetIndexStatusScoping:+ """GET /library/api/collections/<id>/index/status is scoped per collection.++ Regression guard for the cross-collection false-idle bug: the endpoint used+ to return the *globally* most-recent indexing task, so kicking off a second+ collection's reindex made the first one report ``idle`` while it was still+ indexing. The status must reflect THIS collection's task regardless of which+ collection has the newest task.+ """++ @staticmethod+ def _seed_session():+ """In-memory session with indexing tasks for two collections.++ Collection A has TWO tasks: an older ``failed`` one and a newer+ ``processing`` one (so the newest-first ordering is exercised — the+ endpoint must return the NEWER task, not the older). Collection B's+ single task is the global newest (completed). The endpoint for A must+ still return A's OWN newest (``processing``) task, not B's.++ Returns ``(session, coll_a_id, coll_b_id)``.+ """+ from datetime import datetime, timedelta, UTC+ from sqlalchemy import create_engine+ from sqlalchemy.orm import sessionmaker+ from local_deep_research.database.models import Base+ from local_deep_research.database.models.queue import TaskMetadata++ engine = create_engine("sqlite:///:memory:")+ Base.metadata.create_all(engine)+ session = sessionmaker(bind=engine)()++ coll_a_id = "collection-a"+ coll_b_id = "collection-b"+ base_time = datetime(2024, 1, 1, 12, 0, 0, tzinfo=UTC)++ # A's OLDER task — a previous failed run. The endpoint must NOT return+ # this one; it must return A's newer ``processing`` task below. This is+ # what makes the newest-first ordering load-bearing: a .desc()->.asc()+ # mutation would surface this stale ``failed`` instead.+ session.add(+ TaskMetadata(+ task_id="task-a-old",+ status="failed",+ task_type="indexing",+ created_at=base_time - timedelta(minutes=5),+ progress_current=0,+ progress_total=3,+ progress_message="Old A run failed",+ error_message="stale failure",+ metadata_json={"collection_id": coll_a_id},+ )+ )+ # A's NEWER task is still processing.+ session.add(+ TaskMetadata(+ task_id="task-a",+ status="processing",+ task_type="indexing",+ created_at=base_time,+ progress_current=1,+ progress_total=3,+ progress_message="Indexing A...",+ metadata_json={"collection_id": coll_a_id},+ )+ )+ # B's task is the NEWEST and already completed.+ session.add(+ TaskMetadata(+ task_id="task-b",+ status="completed",+ task_type="indexing",+ created_at=base_time + timedelta(minutes=5),+ progress_current=2,+ progress_total=2,+ progress_message="Indexed B",+ metadata_json={"collection_id": coll_b_id},+ )+ )+ session.commit()+ return session, coll_a_id, coll_b_id++ def _call_status(self, session, collection_id):+ from contextlib import contextmanager+ from flask import Flask+ from local_deep_research.research_library.routes.rag_routes import (+ rag_bp,+ )++ app = Flask(__name__)+ app.config["SECRET_KEY"] = "test-secret"+ app.config["TESTING"] = True+ app.register_blueprint(rag_bp)+ app.register_blueprint(auth_bp)++ @contextmanager+ def fake_get_user_db_session(*a, **kw):+ yield session++ mock_db = Mock()+ mock_db.is_user_connected.return_value = True++ with (+ patch(+ "local_deep_research.web.auth.decorators.db_manager",+ mock_db,+ ),+ patch(+ "local_deep_research.database.session_context.get_user_db_session",+ side_effect=fake_get_user_db_session,+ ),+ patch(+ "local_deep_research.database.session_passwords.session_password_store.get_session_password",+ return_value=None,+ ),+ ):+ with app.test_client() as client:+ with client.session_transaction() as sess:+ sess["username"] = "testuser"+ sess["session_id"] = "test-session-id"+ return client.get(+ f"/library/api/collections/{collection_id}/index/status"+ )++ def test_returns_this_collections_task_not_global_newest(self):+ """A's status is its OWN processing task, even though B's is newer."""+ session, coll_a_id, coll_b_id = self._seed_session()+ try:+ resp = self._call_status(session, coll_a_id)+ finally:+ session.close()++ assert resp.status_code == 200, resp.status_code+ data = resp.get_json()+ assert data["status"] == "processing"+ assert data["task_id"] == "task-a"+ assert data["collection_id"] == coll_a_id++ def test_returns_newest_task_for_the_collection(self):+ """Among A's OWN tasks, the NEWEST (processing) wins over the older+ (failed) one — locking in the newest-first ordering. Flipping+ ``.desc()`` to ``.asc()`` would return ``task-a-old`` and fail here.+ """+ session, coll_a_id, _coll_b_id = self._seed_session()+ try:+ resp = self._call_status(session, coll_a_id)+ finally:+ session.close()++ assert resp.status_code == 200, resp.status_code+ data = resp.get_json()+ assert data["task_id"] == "task-a"+ assert data["status"] == "processing"+ # The older failed run must NOT be what we returned.+ assert data["task_id"] != "task-a-old"++ def test_returns_idle_only_when_no_task_for_collection(self):+ """A collection with no indexing task at all reports idle (scoped)."""+ session, _coll_a_id, _coll_b_id = self._seed_session()+ try:+ resp = self._call_status(session, "collection-with-no-task")+ finally:+ session.close()++ assert resp.status_code == 200, resp.status_code+ data = resp.get_json()+ assert data["status"] == "idle"+ assert data["collection_id"] == "collection-with-no-task"diff --git a/tests/research_library/routes/test_rag_routes_coverage.py b/tests/research_library/routes/test_rag_routes_coverage.pyindex 480a43b233..212490f8e8 100644--- a/tests/research_library/routes/test_rag_routes_coverage.py+++ b/tests/research_library/routes/test_rag_routes_coverage.py@@ -79,6 +79,7 @@ def _build_mock_query(q.filter_by.return_value = qq.filter.return_value = qq.order_by.return_value = q+ q.group_by.return_value = qq.outerjoin.return_value = qq.join.return_value = qq.limit.return_value = q@@ -127,6 +128,27 @@ def _make_db_session():return db_session+def _collections_query_side_effect(collections):+ """Build a ``db_session.query`` side_effect for GET /api/collections.++ The route runs TWO queries: ``query(Collection).all()`` for the collection+ rows, then a grouped aggregate ``query(DocumentCollection.collection_id,+ func.count(...)).group_by(...).all()`` for the indexed counts. A single+ canned query would feed the collection mocks into ``dict(aggregate.all())``+ and blow up, so distinguish them: the Collection query returns ``collections``+ and the aggregate query returns an empty list (``dict([]) == {}``).+ """+ from local_deep_research.database.models.library import Collection++ def side_effect(*args):+ if args and args[0] is Collection:+ return _build_mock_query(all_result=collections)+ # Aggregate (collection_id, count) query — empty so dict() is happy.+ return _build_mock_query(all_result=[])++ return side_effect++@contextmanagerdef _auth_client(app,@@ -1099,8 +1121,9 @@ class TestGetCollections:mock_coll.embedding_model = Nonedb_session = _make_db_session()- q = _build_mock_query(all_result=[mock_coll])- db_session.query = Mock(return_value=q)+ db_session.query = Mock(+ side_effect=_collections_query_side_effect([mock_coll])+ )with _auth_client(app, mock_db_session=db_session) as (client, ctx):resp = client.get("/library/api/collections")@@ -1127,8 +1150,9 @@ class TestGetCollections:mock_coll.chunk_overlap = 200db_session = _make_db_session()- q = _build_mock_query(all_result=[mock_coll])- db_session.query = Mock(return_value=q)+ db_session.query = Mock(+ side_effect=_collections_query_side_effect([mock_coll])+ )with _auth_client(app, mock_db_session=db_session) as (client, ctx):resp = client.get("/library/api/collections")@@ -1151,8 +1175,9 @@ class TestGetCollections:mock_coll.embedding_model = Nonedb_session = _make_db_session()- q = _build_mock_query(all_result=[mock_coll])- db_session.query = Mock(return_value=q)+ db_session.query = Mock(+ side_effect=_collections_query_side_effect([mock_coll])+ )with _auth_client(app, mock_db_session=db_session) as (client, ctx):resp = client.get("/library/api/collections")@@ -1893,11 +1918,13 @@ class TestGetIndexStatus:assert data["status"] == "idle"def test_task_for_different_collection(self, app):+ # The endpoint scans tasks (query.all()) and matches collection_id in+ # Python, so the candidate must live in all_result, not first_result.task = Mock()task.metadata_json = {"collection_id": "other-coll"}db_session = _make_db_session()- q = _build_mock_query(first_result=task)+ q = _build_mock_query(all_result=[task])db_session.query = Mock(return_value=q)mock_password_store = Mock()@@ -1930,7 +1957,7 @@ class TestGetIndexStatus:task.completed_at = Nonedb_session = _make_db_session()- q = _build_mock_query(first_result=task)+ q = _build_mock_query(all_result=[task])db_session.query = Mock(return_value=q)mock_password_store = Mock()@@ -1952,12 +1979,12 @@ class TestGetIndexStatus:assert data["progress_current"] == 5def test_task_null_metadata_json(self, app):- """Task with metadata_json=None."""+ """Task with metadata_json=None → no collection match → idle."""task = Mock()task.metadata_json = Nonedb_session = _make_db_session()- q = _build_mock_query(first_result=task)+ q = _build_mock_query(all_result=[task])db_session.query = Mock(return_value=q)mock_password_store = Mock()diff --git a/tests/research_library/routes/test_rag_routes_deep_coverage.py b/tests/research_library/routes/test_rag_routes_deep_coverage.pyindex 018e488aaf..cb40d39a70 100644--- a/tests/research_library/routes/test_rag_routes_deep_coverage.py+++ b/tests/research_library/routes/test_rag_routes_deep_coverage.py@@ -1551,7 +1551,8 @@ class TestGetIndexStatusNullDates:mock_task.metadata_json = {"collection_id": "coll-1"}db_session = _make_db_session()- q = _build_mock_query(first_result=mock_task)+ # get_index_status scans query.all() and matches collection_id in Python.+ q = _build_mock_query(all_result=[mock_task])db_session.query = Mock(return_value=q)mock_password_store = Mock()diff --git a/tests/research_library/routes/test_rag_routes_gaps_coverage.py b/tests/research_library/routes/test_rag_routes_gaps_coverage.pyindex d5a77228d6..8ab41c8a67 100644--- a/tests/research_library/routes/test_rag_routes_gaps_coverage.py+++ b/tests/research_library/routes/test_rag_routes_gaps_coverage.py@@ -58,6 +58,7 @@ def _build_mock_query(all_result=None, first_result=None, count_result=0):q.filter_by.return_value = qq.filter.return_value = qq.order_by.return_value = q+ q.group_by.return_value = qq.outerjoin.return_value = qq.join.return_value = qq.options.return_value = q@@ -76,6 +77,25 @@ def _make_db_session():return db_session+def _collections_query_side_effect(collections):+ """``db_session.query`` side_effect for GET /api/collections.++ The route issues ``query(Collection).all()`` then a grouped aggregate+ ``query(DocumentCollection.collection_id, func.count(...))``. Feeding the+ collection mocks into ``dict(aggregate.all())`` would raise, so return the+ collections only for the Collection query and an empty list (→ ``{}``) for+ the aggregate.+ """+ from local_deep_research.database.models.library import Collection++ def side_effect(*args):+ if args and args[0] is Collection:+ return _build_mock_query(all_result=collections)+ return _build_mock_query(all_result=[])++ return side_effect++def _make_settings_mock(overrides=None):mock_sm = Mock()defaults = {@@ -981,8 +1001,8 @@ class TestGetCollectionsAgentEnabled:def _list(self, app, collections):db_session = _make_db_session()- db_session.query.return_value = _build_mock_query(- all_result=collections+ db_session.query = Mock(+ side_effect=_collections_query_side_effect(collections))with _auth_client(app, mock_db_session=db_session) as (client, _ctx):resp = client.get("/library/api/collections")diff --git a/tests/ui_tests/test_library_collections_ci.js b/tests/ui_tests/test_library_collections_ci.jsindex a143880417..99fcc24b2f 100644--- a/tests/ui_tests/test_library_collections_ci.js+++ b/tests/ui_tests/test_library_collections_ci.js@@ -199,11 +199,14 @@ const CollectionsPageTests = {async collectionCardStructure(page, baseUrl) {// Collections render client-side (collections_manager.js) into- // #collections-container as <a class="ldr-collection-card" data-id="<id>">- // with .ldr-collection-header h3 (name) + .ldr-collection-stats +- // .ldr-collection-view-link. The old test scanned for `.collection-card`- // (no such class exists) and SKIPped on an empty DB. Seed a collection- // and assert the real card markup, then clean up.+ // #collections-container as+ // <div class="ldr-collection-card-wrapper" data-id="<id>"> holding the+ // clickable <a class="ldr-collection-card"> (with .ldr-collection-header+ // h3 (name) + .ldr-collection-stats) plus a sibling actions row with the+ // Reindex button + .ldr-collection-view-link. The per-collection data-id+ // lives on the wrapper, not the card <a>. The old test scanned for+ // `.collection-card` (no such class exists) and SKIPped on an empty DB.+ // Seed a collection and assert the real card markup, then clean up.await navigateTo(page, `${baseUrl}/library/collections`);const seeded = await seedCollection(page);if (!seeded) {@@ -212,10 +215,10 @@ const CollectionsPageTests = {try {// navigateTo no-ops (already on this path); reload to render the new card.await page.reload({ waitUntil: 'domcontentloaded' });- await page.waitForSelector(`.ldr-collection-card[data-id="${seeded.id}"]`, { timeout: 10000 });+ await page.waitForSelector(`.ldr-collection-card-wrapper[data-id="${seeded.id}"]`, { timeout: 10000 });const result = await page.evaluate((id) => {- const card = document.querySelector(`.ldr-collection-card[data-id="${id}"]`);+ const card = document.querySelector(`.ldr-collection-card-wrapper[data-id="${id}"]`);if (!card) return { found: false };return {found: true,