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.

feat: add backup status UI to settings page and research warnings (#3075)

LearningCircuit4f1489eae218
diff --git a/src/local_deep_research/utilities/formatting.py b/src/local_deep_research/utilities/formatting.py
new file mode 100644
index 0000000000..b697a8197e
--- /dev/null
+++ b/src/local_deep_research/utilities/formatting.py
@@ -0,0 +1,17 @@
+"""Shared formatting utilities."""
+
+
+def human_size(size_bytes: float) -> str:
+ """Convert bytes to human-readable size string.
+
+ Args:
+ size_bytes: Size in bytes.
+
+ Returns:
+ Human-readable string like "247.0 MB" or "1.5 GB".
+ """
+ for unit in ("B", "KB", "MB", "GB"):
+ if abs(size_bytes) < 1024:
+ return f"{size_bytes:.1f} {unit}"
+ size_bytes /= 1024
+ return f"{size_bytes:.1f} TB"
diff --git a/src/local_deep_research/web/routes/settings_routes.py b/src/local_deep_research/web/routes/settings_routes.py
index ef6d021a4d..79ba00a413 100644
--- a/src/local_deep_research/web/routes/settings_routes.py
+++ b/src/local_deep_research/web/routes/settings_routes.py
@@ -40,7 +40,7 @@ optimal experience when JavaScript is available.
import platform
from typing import Any, Optional, Tuple
-from datetime import datetime, UTC, timedelta
+from datetime import UTC, datetime, timedelta, timezone
import requests
from flask import (
@@ -1906,6 +1906,64 @@ def api_get_warnings():
return jsonify({"error": "Failed to retrieve warnings"}), 500
+@settings_bp.route("/api/backup-status", methods=["GET"])
+@login_required
+def api_get_backup_status():
+ """Get backup status for the current user."""
+ try:
+ from ...config.paths import get_user_backup_directory
+
+ username = session.get("username")
+ if not username:
+ return jsonify({"error": "Not authenticated"}), 401
+
+ from ...utilities.formatting import human_size
+
+ backup_dir = get_user_backup_directory(username)
+
+ # Sort by modification time (not filename) for robustness
+ backup_list = []
+ total_size = 0
+ for b in backup_dir.glob("ldr_backup_*.db"):
+ try:
+ stat = b.stat()
+ total_size += stat.st_size
+ backup_list.append(
+ {
+ "filename": b.name,
+ "size_bytes": stat.st_size,
+ "size_human": human_size(stat.st_size),
+ "created_at": datetime.fromtimestamp(
+ stat.st_mtime, tz=timezone.utc
+ ).isoformat(),
+ "_mtime": stat.st_mtime,
+ }
+ )
+ except FileNotFoundError:
+ continue
+
+ # Sort newest first by mtime, then remove internal field
+ backup_list.sort(key=lambda x: x["_mtime"], reverse=True)
+ for entry in backup_list:
+ del entry["_mtime"]
+
+ backup_enabled = _get_setting_from_session("backup.enabled", True)
+
+ return jsonify(
+ {
+ "enabled": bool(backup_enabled),
+ "count": len(backup_list),
+ "backups": backup_list,
+ "total_size_bytes": total_size,
+ "total_size_human": human_size(total_size),
+ }
+ )
+
+ except Exception:
+ logger.exception("Error getting backup status")
+ return jsonify({"error": "Failed to retrieve backup status"}), 500
+
+
@settings_bp.route("/api/ollama-status", methods=["GET"])
@login_required
def check_ollama_status():
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 d12339213a..2823bf4f76 100644
--- a/src/local_deep_research/web/static/js/components/settings.js
+++ b/src/local_deep_research/web/static/js/components/settings.js
@@ -1788,6 +1788,185 @@
});
}
+ /**
+ * Render backup status info section
+ */
+ function renderBackupStatusSection() {
+ const sectionId = 'section-ldr-backup-status';
+
+ let html = `
+ <div class="ldr-settings-section ldr-backup-status-section">
+ <div class="ldr-settings-section-header" data-target="${sectionId}">
+ <div class="ldr-settings-section-title">
+ <i class="fas fa-shield-alt"></i> Backup Status
+ </div>
+ <div class="ldr-settings-toggle-icon">
+ <i class="fas fa-chevron-down"></i>
+ </div>
+ </div>
+ <div id="${sectionId}" class="ldr-settings-section-body">
+ <div id="ldr-backup-status-content" class="ldr-backup-status-info">
+ <div class="ldr-loading-spinner">
+ <i class="fas fa-spinner fa-spin"></i> Loading backup status...
+ </div>
+ </div>
+ </div>
+ </div>
+ `;
+
+ setTimeout(() => fetchBackupStatusInfo(), 150);
+
+ return html;
+ }
+
+ /**
+ * Fetch and display backup status information
+ */
+ function fetchBackupStatusInfo() {
+ const contentElement = document.getElementById('ldr-backup-status-content');
+ if (!contentElement) return;
+
+ fetch(URLS.SETTINGS_API.BACKUP_STATUS)
+ .then(response => response.json())
+ .then(data => {
+ const esc = window.escapeHtml || (s => String(s || ''));
+
+ let statusIcon, statusText, statusClass;
+ if (!data.enabled) {
+ statusIcon = 'fa-times-circle';
+ statusText = 'Backups disabled';
+ statusClass = 'ldr-backup-disabled';
+ } else if (data.count === 0) {
+ statusIcon = 'fa-exclamation-triangle';
+ statusText = 'No backups yet';
+ statusClass = 'ldr-backup-warning';
+ } else {
+ statusIcon = 'fa-check-circle';
+ statusText = `${data.count} backup${data.count > 1 ? 's' : ''} (${esc(data.total_size_human)})`;
+ statusClass = 'ldr-backup-ok';
+ }
+
+ let html = '<div class="ldr-backup-status-details">';
+
+ html += `
+ <div class="ldr-backup-status-row ${statusClass}">
+ <i class="fas ${statusIcon}"></i>
+ <span><strong>${esc(statusText)}</strong></span>
+ </div>
+ `;
+
+ if (data.backups && data.backups.length > 0) {
+ const latest = data.backups[0];
+ const date = new Date(latest.created_at);
+ const dateStr = date.toLocaleDateString() + ' ' + date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
+
+ html += `
+ <div class="ldr-backup-detail-grid">
+ <div class="ldr-backup-detail-item">
+ <span class="ldr-backup-detail-label">Last backup:</span>
+ <span>${esc(dateStr)}</span>
+ </div>
+ <div class="ldr-backup-detail-item">
+ <span class="ldr-backup-detail-label">Size:</span>
+ <span>${esc(latest.size_human)}</span>
+ </div>
+ </div>
+ `;
+ }
+
+ if (!data.enabled) {
+ html += `
+ <div class="ldr-backup-hint">
+ <small>Enable backups below to protect your data. Each backup uses disk space equal to your database size.</small>
+ </div>
+ `;
+ } else if (data.count === 0) {
+ html += `
+ <div class="ldr-backup-hint">
+ <small>A backup will be created automatically on your next login.</small>
+ </div>
+ `;
+ } else {
+ html += `
+ <div class="ldr-backup-hint">
+ <small>Backups are created once per day on login. Encrypted backups cannot be compressed. Configure retention below.</small>
+ </div>
+ `;
+ }
+
+ html += '</div>';
+
+ // Add styles
+ if (!document.getElementById('ldr-backup-status-styles')) {
+ const style = document.createElement('style');
+ style.id = 'ldr-backup-status-styles';
+ style.textContent = `
+ .ldr-backup-status-section {
+ margin-bottom: 1.5rem;
+ border: 1px solid var(--border-color, #ddd);
+ border-radius: 8px;
+ background: var(--bg-secondary);
+ }
+
+ .ldr-backup-status-details {
+ padding: 1rem;
+ }
+
+ .ldr-backup-status-row {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ padding: 0.5rem 0;
+ font-size: 1rem;
+ }
+
+ .ldr-backup-status-row.ldr-backup-ok i { color: var(--success-color, #22c55e); }
+ .ldr-backup-status-row.ldr-backup-warning i { color: var(--warning-color, #f59e0b); }
+ .ldr-backup-status-row.ldr-backup-disabled i { color: var(--error-color, #ef4444); }
+
+ .ldr-backup-detail-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
+ gap: 0.5rem;
+ margin-top: 0.75rem;
+ padding: 0.75rem;
+ background: var(--bg-tertiary);
+ border-radius: 6px;
+ }
+
+ .ldr-backup-detail-item {
+ display: flex;
+ gap: 0.5rem;
+ font-size: 0.9rem;
+ }
+
+ .ldr-backup-detail-label {
+ color: var(--text-secondary);
+ font-weight: 500;
+ }
+
+ .ldr-backup-hint {
+ margin-top: 0.75rem;
+ color: var(--text-secondary);
+ font-size: 0.85rem;
+ opacity: 0.8;
+ }
+ `;
+ document.head.appendChild(style);
+ }
+
+ contentElement.innerHTML = html;
+ })
+ .catch(error => {
+ SafeLogger.error('Error fetching backup status:', error);
+ contentElement.innerHTML = '';
+ const alertDiv = document.createElement('div');
+ alertDiv.className = 'ldr-backup-hint';
+ alertDiv.textContent = 'Could not load backup status.';
+ contentElement.appendChild(alertDiv);
+ });
+ }
+
/**
* Render settings based on active tab
* @param {string} tab - The active tab
@@ -1813,9 +1992,10 @@
// Build HTML
let html = '';
- // Add data location section at the beginning if on app or all tab
+ // Add data location and backup status sections on app or all tab
if (tab === 'app' || tab === 'all') {
html += renderDataLocationSection();
+ html += renderBackupStatusSection();
}
// Define the order for the types in "all" tab
diff --git a/src/local_deep_research/web/static/js/config/urls.js b/src/local_deep_research/web/static/js/config/urls.js
index 20fa1e9506..15a669863d 100644
--- a/src/local_deep_research/web/static/js/config/urls.js
+++ b/src/local_deep_research/web/static/js/config/urls.js
@@ -77,6 +77,7 @@ if (typeof URLS !== 'undefined') {
AVAILABLE_MODELS: '/settings/api/available-models',
AVAILABLE_SEARCH_ENGINES: '/settings/api/available-search-engines',
WARNINGS: '/settings/api/warnings',
+ BACKUP_STATUS: '/settings/api/backup-status',
OLLAMA_STATUS: '/settings/api/ollama-status',
LLM_MODEL: '/settings/api/llm.model',
LLM_PROVIDER: '/settings/api/llm.provider',
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 e982289ae1..19486aa79b 100644
--- a/src/local_deep_research/web/static/js/research_form.js
+++ b/src/local_deep_research/web/static/js/research_form.js
@@ -278,7 +278,7 @@ function displayWarnings(warnings) {
const esc = window.escapeHtml || (s => String(s || '').replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":"&#39;"})[m]));
const warningsHtml = warnings.map(warning => {
// Use success styling for recommendations/tips, warning for others
- const isInfo = warning.type === 'searxng_recommendation' || warning.type === 'legacy_server_config';
+ const isInfo = warning.type === 'searxng_recommendation' || warning.type === 'legacy_server_config' || warning.type === 'backup_info';
const alertClass = isInfo ? 'ldr-alert-info' : 'ldr-alert-warning';
return `
diff --git a/src/local_deep_research/web/warning_checks/__init__.py b/src/local_deep_research/web/warning_checks/__init__.py
index 3b72fb5b9f..470a4aee40 100644
--- a/src/local_deep_research/web/warning_checks/__init__.py
+++ b/src/local_deep_research/web/warning_checks/__init__.py
@@ -15,7 +15,11 @@ from .context import (
check_context_below_history,
check_context_truncation_history,
)
-from .backup import check_backup_disabled, check_no_backups_exist
+from .backup import (
+ check_backup_disabled,
+ check_backup_healthy,
+ check_no_backups_exist,
+)
from .hardware import (
LOCAL_PROVIDERS,
check_high_context,
@@ -114,27 +118,46 @@ def calculate_warnings() -> List[dict]:
if w:
warnings.append(w)
- if backup_enabled and not dismiss_no_backups:
- # Check if any backups exist (lightweight filesystem glob)
- try:
- from ...config.paths import get_user_backup_directory
-
- username = session.get("username")
- if username:
- backup_dir = get_user_backup_directory(username)
- backup_count = len(
- list(backup_dir.glob("ldr_backup_*.db"))
- )
- w = _safe_check(
- check_no_backups_exist,
- backup_enabled,
- backup_count,
- dismiss_no_backups,
- )
- if w:
- warnings.append(w)
- except Exception:
- logger.debug("Backup status check skipped")
+ # Check backup file status (lightweight filesystem glob)
+ dismiss_backup_info = settings_manager.get_setting(
+ "app.warnings.dismiss_backup_info", False
+ )
+ try:
+ from ...config.paths import get_user_backup_directory
+ from ...utilities.formatting import human_size
+
+ username = session.get("username")
+ if username:
+ backup_dir = get_user_backup_directory(username)
+ total_size = 0
+ backup_count = 0
+ for f in backup_dir.glob("ldr_backup_*.db"):
+ try:
+ total_size += f.stat().st_size
+ backup_count += 1
+ except FileNotFoundError:
+ continue
+
+ w = _safe_check(
+ check_no_backups_exist,
+ backup_enabled,
+ backup_count,
+ dismiss_no_backups,
+ )
+ if w:
+ warnings.append(w)
+
+ w = _safe_check(
+ check_backup_healthy,
+ backup_enabled,
+ backup_count,
+ human_size(total_size),
+ dismiss_backup_info,
+ )
+ if w:
+ warnings.append(w)
+ except Exception:
+ logger.debug("Backup status check skipped")
# --- History-based checks (need DB queries) ---
if is_local and not dismiss_context_warning:
diff --git a/src/local_deep_research/web/warning_checks/backup.py b/src/local_deep_research/web/warning_checks/backup.py
index 273ac930b4..e265e1f7d8 100644
--- a/src/local_deep_research/web/warning_checks/backup.py
+++ b/src/local_deep_research/web/warning_checks/backup.py
@@ -50,3 +50,33 @@ def check_no_backups_exist(
),
"dismissKey": "app.warnings.dismiss_no_backups",
}
+
+
+def check_backup_healthy(
+ backup_enabled: bool,
+ backup_count: int,
+ total_size_human: str,
+ dismissed: bool,
+) -> Optional[dict]:
+ """Show positive backup status info (dismissable)."""
+ if not backup_enabled:
+ return None
+ if backup_count == 0:
+ return None
+ if dismissed:
+ return None
+
+ return {
+ "type": "backup_info",
+ "icon": "✅",
+ "title": "Database Backup Active",
+ "message": (
+ f"{backup_count} backup{'s' if backup_count > 1 else ''} "
+ f"({total_size_human}) on disk. Encrypted backups cannot be "
+ "compressed, so each backup equals your database size "
+ "(which can be large if PDFs are stored in the database). "
+ "Backups are created once per day on login. Manage backups "
+ "in Settings \u203a Backup."
+ ),
+ "dismissKey": "app.warnings.dismiss_backup_info",
+ }
diff --git a/tests/web/routes/test_backup_status_api.py b/tests/web/routes/test_backup_status_api.py
new file mode 100644
index 0000000000..486b0983f7
--- /dev/null
+++ b/tests/web/routes/test_backup_status_api.py
@@ -0,0 +1,106 @@
+"""Tests for the backup status API endpoint logic."""
+
+from local_deep_research.utilities.formatting import human_size
+
+
+class TestHumanSize:
+ """Tests for the shared human_size formatter."""
+
+ def test_zero_bytes(self):
+ assert human_size(0) == "0.0 B"
+
+ def test_bytes(self):
+ assert human_size(500) == "500.0 B"
+
+ def test_kilobytes(self):
+ assert human_size(1536) == "1.5 KB"
+
+ def test_megabytes(self):
+ result = human_size(258_179_072)
+ assert "MB" in result
+ assert result == "246.2 MB"
+
+ def test_gigabytes(self):
+ result = human_size(2_147_483_648)
+ assert result == "2.0 GB"
+
+ def test_terabytes(self):
+ result = human_size(1_099_511_627_776)
+ assert result == "1.0 TB"
+
+
+class TestBackupStatusResponseShape:
+ """Tests that verify backup status response structure using real filesystem."""
+
+ def test_no_backups_returns_empty(self, tmp_path):
+ """When backup directory is empty, response should have count=0."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ backups = sorted(
+ backup_dir.glob("ldr_backup_*.db"),
+ key=lambda p: p.name,
+ reverse=True,
+ )
+
+ assert len(backups) == 0
+
+ def test_single_backup_detected(self, tmp_path):
+ """A single backup file should be found and sized correctly."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ backup = backup_dir / "ldr_backup_20260326_120000.db"
+ backup.write_bytes(b"x" * 4096)
+
+ backups = sorted(
+ backup_dir.glob("ldr_backup_*.db"),
+ key=lambda p: p.name,
+ reverse=True,
+ )
+
+ assert len(backups) == 1
+ assert backups[0].stat().st_size == 4096
+
+ def test_multiple_backups_sorted_newest_first(self, tmp_path):
+ """Multiple backups should sort newest first."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ (backup_dir / "ldr_backup_20260325_120000.db").write_bytes(b"old")
+ (backup_dir / "ldr_backup_20260326_120000.db").write_bytes(b"new!")
+
+ backups = sorted(
+ backup_dir.glob("ldr_backup_*.db"),
+ key=lambda p: p.name,
+ reverse=True,
+ )
+
+ assert backups[0].name == "ldr_backup_20260326_120000.db"
+ assert backups[1].name == "ldr_backup_20260325_120000.db"
+
+ def test_tmp_files_not_included(self, tmp_path):
+ """Temporary .tmp files should not appear in backup listing."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ (backup_dir / "ldr_backup_20260326_120000.db").write_bytes(b"real")
+ (backup_dir / "ldr_backup_20260326_130000.db.tmp").write_bytes(b"temp")
+
+ backups = list(backup_dir.glob("ldr_backup_*.db"))
+ # .tmp should not match the *.db glob
+ assert len(backups) == 1
+ assert backups[0].name == "ldr_backup_20260326_120000.db"
+
+ def test_total_size_calculation(self, tmp_path):
+ """Total size should sum all backup file sizes."""
+ backup_dir = tmp_path / "backups"
+ backup_dir.mkdir()
+
+ (backup_dir / "ldr_backup_20260325_120000.db").write_bytes(b"x" * 1000)
+ (backup_dir / "ldr_backup_20260326_120000.db").write_bytes(b"x" * 2000)
+
+ backups = list(backup_dir.glob("ldr_backup_*.db"))
+ total = sum(b.stat().st_size for b in backups)
+
+ assert total == 3000
diff --git a/tests/web/warning_checks/test_backup.py b/tests/web/warning_checks/test_backup.py
index 3b7e7b1532..e2bda4ae55 100644
--- a/tests/web/warning_checks/test_backup.py
+++ b/tests/web/warning_checks/test_backup.py
@@ -2,6 +2,7 @@
from local_deep_research.web.warning_checks.backup import (
check_backup_disabled,
+ check_backup_healthy,
check_no_backups_exist,
)
@@ -52,3 +53,46 @@ class TestCheckNoBackupsExist:
backup_enabled=True, backup_count=0, dismissed=True
)
assert result is None
+
+
+class TestCheckBackupHealthy:
+ """Tests for the backup-healthy info message."""
+
+ def test_returns_info_when_backups_exist(self):
+ result = check_backup_healthy(
+ backup_enabled=True,
+ backup_count=1,
+ total_size_human="247.0 MB",
+ dismissed=False,
+ )
+ assert result is not None
+ assert result["type"] == "backup_info"
+ assert "247.0 MB" in result["message"]
+ assert "dismissKey" in result
+
+ def test_returns_none_when_disabled(self):
+ result = check_backup_healthy(
+ backup_enabled=False,
+ backup_count=1,
+ total_size_human="247.0 MB",
+ dismissed=False,
+ )
+ assert result is None
+
+ def test_returns_none_when_no_backups(self):
+ result = check_backup_healthy(
+ backup_enabled=True,
+ backup_count=0,
+ total_size_human="0 B",
+ dismissed=False,
+ )
+ assert result is None
+
+ def test_returns_none_when_dismissed(self):
+ result = check_backup_healthy(
+ backup_enabled=True,
+ backup_count=1,
+ total_size_human="247.0 MB",
+ dismissed=True,
+ )
+ assert result is None