~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
fix(progress): show logs and status reliably on first page load (#3737)
LearningCircuit62b9500dcde5
diff --git a/src/local_deep_research/utilities/log_utils.py b/src/local_deep_research/utilities/log_utils.pyindex eb51e7f517..a72b6ede1b 100644--- a/src/local_deep_research/utilities/log_utils.py+++ b/src/local_deep_research/utilities/log_utils.py@@ -91,6 +91,23 @@ def log_for_research(return wrapped+def _get_research_context_fallback() -> dict | None:+ """Read the per-thread research context, if any.++ Used as a fallback when individual log calls don't bind research_id/+ username via ``logger.bind``. The research thread sets this once at+ startup via ``set_search_context``, so every subsequent log call from+ the same thread picks up research_id, username, and user_password+ automatically — without requiring every call site to remember to bind.+ """+ try:+ from .thread_context import get_search_context++ return get_search_context()+ except Exception:+ return None++def _get_research_id(record=None) -> str | None:"""Gets the current research ID (UUID), if present.@@ -102,16 +119,79 @@ def _get_research_id(record=None) -> str | None:The current research ID (UUID), or None if it does not exist."""- research_id = None-# First check if research_id is bound to the log recordif record and "extra" in record and "research_id" in record["extra"]:- research_id = record["extra"]["research_id"]+ return record["extra"]["research_id"]# Then check Flask context- elif has_app_context():- research_id = g.get("research_id")-- return research_id+ if has_app_context():+ gid = g.get("research_id")+ if gid:+ return gid+ # Fall back to per-thread research context — research-thread logger+ # calls without an explicit bind still get attributed correctly.+ ctx = _get_research_context_fallback()+ if ctx:+ return ctx.get("research_id")+ return None+++# Counters for swallowed exceptions in the logging path. Bare except: pass+# is required here (logging errors must not propagate or recurse), but we+# write a stderr line on each new occurrence so silent failures aren't+# invisible — only active when LDR_APP_DEBUG=true so production stderr+# stays clean.+_silent_exc_counts: dict[str, int] = {}+++def _report_silent_exception(+ where: str,+ exc_type_name: str,+ username: str | None = None,+ research_id: str | None = None,+ level: str | None = None,+) -> None:+ """Surface a swallowed logging-path exception to stderr.++ Bypasses ``logger`` to avoid recursing back through ``database_sink``.+ Rate-limited to first occurrence + every 100th repeat for the same+ ``where`` key, so a persistent failure mode doesn't flood the console.++ Note: takes the exception's TYPE NAME as a plain string (not the+ exception object). The caller does ``type(exc).__name__`` and passes+ the result. This is deliberate — CodeQL's taint analyzer treats any+ function frame holding a ``BaseException`` captured from a password-+ bearing call site as tainted, and flags every stderr write inside+ that frame. Receiving only a type-name string severs the flow at+ the boundary.+ """+ if os.environ.get("LDR_APP_DEBUG", "").lower() not in ("1", "true", "yes"):+ return+ n = _silent_exc_counts.get(where, 0) + 1+ _silent_exc_counts[where] = n+ if n != 1 and n % 100 != 0:+ return+ parts = []+ if username is not None:+ parts.append(f"username={username!r}")+ if research_id is not None:+ parts.append(f"research_id={research_id!r}")+ if level is not None:+ parts.append(f"level={level!r}")+ ctx = " ".join(parts)+ # CodeQL's py/clear-text-logging-sensitive-data may flag this stderr+ # write because the function frame is reachable from+ # _write_log_to_database which holds user_password locally. The data+ # actually written is only plain strings — `where` (literal),+ # `exc_type_name` (`type(exc).__name__`), and `username/research_id/level`+ # repr'd from the queue entry. No password value ever reaches the+ # formatter; the helper signature deliberately accepts only typed+ # primitives. If CodeQL flags this line, dismiss the alert as a+ # false positive in the Security tab with that justification.+ sys.stderr.write(+ f"[log-utils] {where} swallowed (count={n}): "+ f"{exc_type_name}{(' ' + ctx) if ctx else ''}\n"+ )+ sys.stderr.flush()def _process_log_queue():@@ -144,8 +224,18 @@ def _process_log_queue():except queue.Empty:continue- except Exception:- pass # noqa: silent-exception — must not let logging errors crash the log processor thread+ except Exception as exc:+ # noqa: silent-exception — must not let logging errors crash the log processor thread.+ # Wrap the report itself: if stderr is closed (broken pipe etc.)+ # an IOError from inside an except handler propagates and would+ # kill the daemon thread, silently breaking all subsequent log+ # persistence for the rest of the process lifetime.+ try:+ _report_silent_exception(+ "process_log_queue", type(exc).__name__+ )+ except Exception:+ pass # noqa: silent-exception — broken stderr must not kill the daemondef _write_log_to_database(log_entry: dict) -> None:@@ -156,8 +246,13 @@ def _write_log_to_database(log_entry: dict) -> None:try:username = log_entry.get("username")+ # Captured in the emitting thread (database_sink) from+ # ContextVar storage; the queue daemon thread can't read that itself.+ pw = log_entry.get("user_password") # gitleaks:allow- with get_user_db_session(username) as db_session:+ with get_user_db_session(+ username, password=pw+ ) as db_session: # gitleaks:allowif db_session:db_log = ResearchLog(timestamp=log_entry["timestamp"],@@ -170,8 +265,20 @@ def _write_log_to_database(log_entry: dict) -> None:)db_session.add(db_log)db_session.commit()- except Exception:- pass # noqa: silent-exception — DB errors in the logging path must not propagate or recurse+ except Exception as exc:+ # noqa: silent-exception — DB errors in the logging path must not propagate or recurse.+ # Wrap the report itself so a broken-stderr IOError can't escape and+ # be re-caught by an outer logging-aware handler somewhere upstream.+ try:+ _report_silent_exception(+ "write_log_to_database",+ type(exc).__name__,+ username=log_entry.get("username"),+ research_id=log_entry.get("research_id"),+ level=log_entry.get("level"),+ )+ except Exception:+ pass # noqa: silent-exception — broken stderr must not bubble out of logging pathdef database_sink(message: loguru.Message) -> None:@@ -186,6 +293,52 @@ def database_sink(message: loguru.Message) -> None:record = message.recordresearch_id = _get_research_id(record)+ # Resolve username + password. The queue daemon thread can't read the+ # research thread's ContextVar storage and has no Flask request+ # context, so we capture both here in the emitting thread.+ #+ # Source priority:+ # 1. logger.bind(...) extras on the record itself+ # 2. per-thread research context (set once when the research thread+ # starts, so every subsequent log call inherits it without+ # requiring an explicit bind)+ # 3. Flask request session (for request-handler threads that+ # tagged research_id via the @log_for_research decorator but+ # didn't bind username — common for /api/research/<id>/* routes)+ username = record.get("extra", {}).get("username")+ user_password = None+ ctx = _get_research_context_fallback()+ if ctx:+ if not username:+ username = ctx.get("username")+ user_password = ctx.get("user_password")+ # Only consult Flask request state when the log already has a+ # research_id. ResearchLog is research-scoped by design — auth and+ # other system DEBUG logs (research_id=None) don't belong there. If+ # we attached a username to them via flask_session, they'd just churn+ # through the queue and fail at the daemon (where the encrypted DB+ # may not even be open yet for that user — e.g. right after a server+ # restart with a still-valid session cookie).+ if research_id is not None and has_app_context():+ try:+ from flask import session as flask_session, has_request_context++ if not username and has_request_context():+ username = flask_session.get("username")+ # Password is set on g.user_password by the request middleware+ # after authentication. The daemon thread can't read this, so+ # capture it here in the request thread.+ if not user_password and hasattr(g, "user_password"):+ user_password = g.user_password+ except Exception:+ pass # noqa: silent-exception — must not fail logging on session lookup++ # Skip persistence for system logs that have no research context.+ # These can't be written to any per-user encrypted DB and would just+ # churn through the queue + daemon for no useful end state.+ if research_id is None and username is None:+ return+# Create log entry dictlog_entry = {"timestamp": record["time"],@@ -195,7 +348,8 @@ def database_sink(message: loguru.Message) -> None:"line_no": int(record["line"]),"level": record["level"].name,"research_id": research_id,- "username": record.get("extra", {}).get("username"),+ "username": username,+ "user_password": user_password,}# Check if we're in a background threaddiff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.pyindex af088ab24e..3da53b6fc2 100644--- a/src/local_deep_research/web/services/research_service.py+++ b/src/local_deep_research/web/services/research_service.py@@ -310,13 +310,29 @@ def run_research_process(research_id, query, mode, **kwargs):# Extract username - required for database accessusername = kwargs.get("username")- logger.info(f"Research thread started with username: {username}")if not username:logger.error("No username provided to research thread")raise ValueError("Username is required for research process")# Extract user_password early so it's available for all cleanup pathsuser_password = kwargs.get("user_password")+ # Establish thread context FIRST so every subsequent log line in this+ # thread can be attributed to the correct user/research and persisted+ # to the user's encrypted ResearchLog. Otherwise the early INFO logs+ # below ("Research thread started", "Research strategy", "Research+ # parameters") fire before start_research_process gets to its own+ # set_search_context call (~line 417) and the daemon can't open the+ # encrypted DB to write them — silently dropped via the bare-except.+ set_search_context(+ {+ "research_id": research_id,+ "username": username,+ "user_password": user_password,+ }+ )++ logger.info(f"Research thread started with username: {username}")+try:# Check if this research has been terminated before we even startif is_termination_requested(research_id):@@ -429,8 +445,16 @@ def run_research_process(research_id, query, mode, **kwargs):if metadata.get("phase") == "termination_check":return- # Bind research_id to logger for this specific log- bound_logger = logger.bind(research_id=research_id)+ # Bind research_id AND username so the database_sink + queue+ # daemon can resolve the per-user encrypted DB. Without username+ # the daemon's _write_log_to_database hits "No authenticated+ # user", silently swallows the error, and ResearchLog ends up+ # with zero milestone rows — leaving /api/research/<id>/status+ # without a log_entry to render and the frontend stuck on the+ # "Performing research..." fallback.+ bound_logger = logger.bind(+ research_id=research_id, username=username+ )bound_logger.log("MILESTONE", message)if "SEARCH_PLAN:" in message:diff --git a/src/local_deep_research/web/services/socket_service.py b/src/local_deep_research/web/services/socket_service.pyindex 2c69241d21..7970f15e02 100644--- a/src/local_deep_research/web/services/socket_service.py+++ b/src/local_deep_research/web/services/socket_service.py@@ -106,6 +106,21 @@ class SocketIOService:def on_subscribe(data):self.__handle_subscribe(data, request)+ # Backwards-compatible alias: the JS client emits 'join' on subscribe.+ # Without this, the catch-up snapshot in __handle_subscribe never+ # fires and per-client targeting falls through to broadcast.+ @self.__socketio.on("join")+ def on_join(data):+ self.__handle_subscribe(data, request)++ @self.__socketio.on("leave")+ def on_leave(data):+ self.__handle_unsubscribe(data, request)++ @self.__socketio.on("unsubscribe_from_research")+ def on_unsubscribe(data):+ self.__handle_unsubscribe(data, request)+@self.__socketio.on_errordef on_error(e):return self.__handle_socket_error(e)@@ -327,6 +342,25 @@ class SocketIOService:room=request.sid,)+ def __handle_unsubscribe(self, data, request):+ """Handle client unsubscribe from research updates."""+ research_id = (+ data.get("research_id") if isinstance(data, dict) else None+ )+ if not research_id:+ return+ with self.__lock:+ subs = self.__socket_subscriptions.get(research_id)+ if subs:+ subs.discard(request.sid)+ # Prune empty sets so the dict doesn't grow unbounded with+ # stale research_ids over long server runtimes.+ if not subs:+ self.__socket_subscriptions.pop(research_id, None)+ self.__log_info(+ f"Client {request.sid} unsubscribed from research {research_id}"+ )+def __handle_socket_error(self, e):"""Handle Socket.IO errors"""self.__log_exception(f"Socket.IO error: {str(e)}")diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex 62442eeb97..987c519576 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -183,11 +183,12 @@const toggleIcon = logPanelToggle.querySelector('.ldr-toggle-icon');if (toggleIcon && !collapsed) {- // Load logs if not already loaded+ // Load logs if not already loaded. dataset.loaded is set by+ // loadLogsForResearch only on a successful non-empty fetch,+ // so an earlier empty response does not suppress retries.if (!logPanelContent.dataset.loaded && researchId) {SafeLogger.log('First expansion of log panel, loading logs');loadLogsForResearch(researchId);- logPanelContent.dataset.loaded = 'true';}// Process any queued logs@@ -301,6 +302,15 @@}}+ // Pre-fetch logs in the background so an opened panel has historical+ // entries ready, and so the API races (empty response in 0-100ms+ // window after research start) self-heal once entries exist.+ // dataset.loaded is set inside loadLogsForResearch only on success;+ // an empty response leaves it unset so a later toggle re-fetches.+ if (researchId && !logPanelContent.dataset.loaded) {+ loadLogsForResearch(researchId);+ }+// Pre-load logs if hash includes #logs// bearer:disable javascript_lang_observable_timing — timing comparison on URL hash, not secretsif (window.location.hash === '#logs' && researchId) {@@ -404,10 +414,24 @@* @param {string} researchId - The research ID to load logs for*/async function loadLogsForResearch(researchId) {+ // In-flight guard: if a fetch for this research is already pending+ // (e.g. pre-fetch from initializeLogPanel hasn't resolved yet and the+ // user expanded the panel), don't fire a second request.+ const panelEl = document.getElementById('log-panel-content') || document.getElementById('logPanel');+ if (panelEl && panelEl.dataset.loading === 'true') {+ SafeLogger.log('loadLogsForResearch already in flight, skipping duplicate');+ return;+ }+ if (panelEl) {+ panelEl.dataset.loading = 'true';+ }+try {- // Show loading state+ // Show loading state, but only if the container has no live+ // entries yet — otherwise we'd clobber socket-driven logs that+ // arrived before this fetch completes.const logContent = document.getElementById('console-log-container');- if (logContent) {+ if (logContent && !logContent.querySelector('.ldr-console-log-entry')) {logContent.innerHTML = '<div class="ldr-loading-spinner ldr-centered"><div class="ldr-spinner"></div><div style="margin-left: 10px;">Loading logs...</div></div>';}@@ -549,36 +573,53 @@});}+ const panelContent = document.getElementById('log-panel-content') || document.getElementById('logPanel');+// Clear containerif (logContent) {if (allLogs.length === 0) {- logContent.innerHTML = '<div class="ldr-empty-log-message">No logs available for this research.</div>';+ // If socket events populated logs while this fetch was+ // in flight, don't clobber them with the empty placeholder.+ const hasLiveEntries = logContent.querySelector('.ldr-console-log-entry');+ if (!hasLiveEntries) {+ logContent.innerHTML = '<div class="ldr-empty-log-message">No logs available for this research.</div>';+ }+ // Leave dataset.loaded unset so a future toggle re-fetches+ // once the backend has flushed log rows.+ if (panelContent) {+ delete panelContent.dataset.loaded;+ }return;}- logContent.innerHTML = '';-- // Normalize timestamps - in case there are logs with mismatched AM/PM time zones- // This attempts to ensure logs are in a proper chronological ordernormalizeTimestamps(allLogs);// Deduplicate logs by ID and sort by timestamp (oldest first)const uniqueLogsMap = new Map();allLogs.forEach(log => {- // Use the ID as the key for deduplicationuniqueLogsMap.set(log.id, log);});-- // Convert map back to arrayconst uniqueLogs = Array.from(uniqueLogsMap.values());-- // Sort logs by timestamp (newest first)const sortedLogs = uniqueLogs.sort((a, b) => {return new Date(b.time) - new Date(a.time);});SafeLogger.log(`Displaying ${sortedLogs.length} logs after deduplication (from original ${allLogs.length})`);+ // If socket events populated entries while this fetch was+ // in flight, append via addLogEntryToPanel (which dedupes by+ // id and message) instead of clobbering with innerHTML = ''.+ const hasLiveEntries = logContent.querySelector('.ldr-console-log-entry');+ if (hasLiveEntries) {+ sortedLogs.forEach(logEntry => addLogEntryToPanel(logEntry, false));+ if (panelContent) {+ panelContent.dataset.loaded = 'true';+ }+ return;+ }++ logContent.innerHTML = '';+// Batch DOM insert using DocumentFragment (O(1) reflow vs O(n))// sortedLogs is newest-first, but DOM needs [oldest, ..., newest]// for column-reverse CSS to show newest at visual top@@ -603,6 +644,12 @@indicator.textContent = logContent.children.length;});}++ // Mark loaded only after a successful non-empty fetch so an+ // empty initial response doesn't permanently suppress retries.+ if (panelContent) {+ panelContent.dataset.loaded = 'true';+ }}} catch (error) {@@ -615,6 +662,10 @@// bearer:disable javascript_lang_dangerous_insert_htmllogContent.innerHTML = `<div class="ldr-error-message">Error loading logs: ${escapeHtml(error.message)}</div>`;}+ } finally {+ if (panelEl) {+ delete panelEl.dataset.loading;+ }}}diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex dc169e378a..3a0c7aa84f 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -73,6 +73,15 @@ window.socket = (function() {connectionAttempts = 0;usingPolling = false;+ // Clear any polling intervals left over from fallback paths.+ // The websocket is now the authoritative transport.+ if (window.pollIntervals) {+ Object.keys(window.pollIntervals).forEach((id) => {+ clearInterval(window.pollIntervals[id]);+ delete window.pollIntervals[id];+ });+ }+// Re-subscribe to current research if anyif (currentResearchId) {subscribeToResearch(currentResearchId);@@ -156,11 +165,6 @@ window.socket = (function() {* @param {function} callback - Optional callback for progress updates*/function subscribeToResearch(researchId, callback) {- if (!socket && !usingPolling) {- SafeLogger.warn('Socket not initialized, initializing now');- initializeSocket();- }-if (!researchId) {SafeLogger.error('No research ID provided');return;@@ -168,7 +172,7 @@ window.socket = (function() {SafeLogger.log('Subscribing to research:', researchId);- // Remember the current research ID+ // Remember the current research ID so the connect handler can re-subscribecurrentResearchId = researchId;// Add the callback if provided@@ -176,10 +180,17 @@ window.socket = (function() {addResearchEventHandler(researchId, callback);}- // If we have a socket connection, join the research room+ if (!socket && !usingPolling) {+ SafeLogger.warn('Socket not initialized, initializing now');+ initializeSocket();+ // Don't fall back to polling here — let the connect handler+ // re-subscribe once the websocket is ready.+ return;+ }+if (socket && socket.connected) {try {- socket.emit('join', { research_id: researchId });+ socket.emit('subscribe_to_research', { research_id: researchId });// Remove any existing listener first to prevent duplicatessocket.off(`progress_${researchId}`);@@ -192,10 +203,11 @@ window.socket = (function() {SafeLogger.error('Error subscribing to research:', error);fallbackToPolling(researchId);}- } else {- // If no socket connection, use polling+ } else if (usingPolling) {+ // Connection has already failed — keep polling.fallbackToPolling(researchId);}+ // else: socket exists but not yet connected — connect handler re-subscribes.}/**@@ -602,7 +614,7 @@ window.socket = (function() {if (socket && socket.connected) {try {// Leave the research room- socket.emit('leave', { research_id: researchId });+ socket.emit('unsubscribe_from_research', { research_id: researchId });// Remove the event handlersocket.off(`progress_${researchId}`);diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.jsnew file mode 100644index 0000000000..9943b6a00b--- /dev/null+++ b/tests/js/components/logpanel.test.js@@ -0,0 +1,242 @@+/**+ * Tests for components/logpanel.js+ *+ * Verifies fixes for the "blank log panel on first load" bug:+ * 1. When the logs API returns [], loadLogsForResearch must not+ * overwrite live entries that arrived via socket events during+ * the fetch.+ * 2. dataset.loaded must NOT be set after an empty API response, so+ * a future toggle (or pre-fetch) re-fetches.+ * 3. dataset.loaded IS set after a successful non-empty fetch, so+ * subsequent toggles don't re-fetch.+ * 4. When the API returns entries while live socket entries already+ * exist, the fetched batch is merged via addLogEntryToPanel+ * (which dedupes) instead of clobbering with innerHTML.+ */++let logPanel;++beforeAll(async () => {+ // logpanel.js destructures window.LdrLogHelpers at IIFE-time.+ await import('@js/utils/log-helpers.js');++ // Stubs the IIFE expects to find on window.+ window.escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, '');+ window.URLBuilder = {+ researchLogs: (id) => `/api/research/${id}/logs`,+ historyLogCount: (id) => `/api/research/${id}/log_count`,+ };++ // Pretend we're on a research page so the auto-initialize path runs.+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: { ...window.location, pathname: '/' },+ });++ await import('@js/components/logpanel.js');+ logPanel = window.logPanel;+});++beforeEach(() => {+ // Build the minimal DOM the panel queries by id.+ document.body.innerHTML = `+ <div class="ldr-collapsible-log-panel">+ <div id="log-panel-toggle">+ <i class="ldr-toggle-icon"></i>+ </div>+ <div id="log-panel-content">+ <div id="console-log-container"></div>+ </div>+ </div>+ <template id="console-log-entry-template">+ <div class="ldr-console-log-entry">+ <span class="ldr-log-timestamp"></span>+ <span class="ldr-log-badge"></span>+ <span class="ldr-log-message"></span>+ </div>+ </template>+ `;++ // Reset shared state between tests.+ if (window._logPanelState) {+ window._logPanelState.queuedLogs = [];+ window._logPanelState.expanded = false;+ window._logPanelState.logCount = 0;+ }+});++function makeLiveEntry(message) {+ // Mimic what addLogEntryToPanel produces in the DOM.+ const entry = document.createElement('div');+ entry.className = 'ldr-console-log-entry';+ entry.dataset.logId = `live-${message}`;+ const span = document.createElement('span');+ span.className = 'ldr-log-message';+ span.textContent = message;+ entry.appendChild(span);+ return entry;+}++describe('loadLogsForResearch — empty API response', () => {+ it('does not clobber live socket-driven entries when API returns []', async () => {+ const container = document.getElementById('console-log-container');+ container.appendChild(makeLiveEntry('socket-arrived-A'));+ container.appendChild(makeLiveEntry('socket-arrived-B'));++ // Simulate empty API response.+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );++ await logPanel.loadLogs('test-research-1');++ // Live entries must still be in the DOM.+ const entries = container.querySelectorAll('.ldr-console-log-entry');+ expect(entries.length).toBe(2);+ // The empty-state placeholder must NOT have replaced them.+ expect(container.querySelector('.ldr-empty-log-message')).toBeNull();+ });++ it('writes the empty placeholder when the container has no live entries', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );++ await logPanel.loadLogs('test-research-2');++ const container = document.getElementById('console-log-container');+ expect(container.querySelector('.ldr-empty-log-message')).not.toBeNull();+ });++ it('does not set dataset.loaded after an empty response', async () => {+ const panelContent = document.getElementById('log-panel-content');+ // Pretend a previous successful load set this.+ delete panelContent.dataset.loaded;++ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );++ await logPanel.loadLogs('test-research-3');++ // Empty response must leave dataset.loaded unset so a retry can happen.+ expect(panelContent.dataset.loaded).toBeUndefined();+ });+});++describe('loadLogsForResearch — non-empty API response', () => {+ it('sets dataset.loaded after a successful non-empty fetch', async () => {+ const panelContent = document.getElementById('log-panel-content');++ globalThis.fetch = vi.fn(() =>+ Promise.resolve({+ json: () =>+ Promise.resolve([+ { timestamp: new Date().toISOString(), message: 'hello', log_type: 'info' },+ ]),+ })+ );++ await logPanel.loadLogs('test-research-4');++ expect(panelContent.dataset.loaded).toBe('true');+ });++ it('merges via addLogEntryToPanel when live entries already exist', async () => {+ const container = document.getElementById('console-log-container');+ container.appendChild(makeLiveEntry('live-only'));++ globalThis.fetch = vi.fn(() =>+ Promise.resolve({+ json: () =>+ Promise.resolve([+ { timestamp: new Date().toISOString(), message: 'fetched', log_type: 'info' },+ ]),+ })+ );++ await logPanel.loadLogs('test-research-5');++ // The live entry must survive (not overwritten by innerHTML reset).+ const messages = Array.from(+ container.querySelectorAll('.ldr-log-message')+ ).map((el) => el.textContent);+ expect(messages).toContain('live-only');+ });+});++describe('loadLogsForResearch — in-flight deduplication', () => {+ it('skips a duplicate fetch while one is already in flight', async () => {+ // Hold the first fetch open until we explicitly resolve it, so the+ // second call lands while the first is still pending.+ let resolveFirst;+ const firstResponse = new Promise((resolve) => {+ resolveFirst = resolve;+ });+ const fetchSpy = vi.fn(() => firstResponse);+ globalThis.fetch = fetchSpy;++ const firstCall = logPanel.loadLogs('test-research-dedup');+ // While first is in flight, kick off a second call — it must be a no-op.+ const secondCall = logPanel.loadLogs('test-research-dedup');+ await secondCall;++ // Only one fetch should have happened so far.+ expect(fetchSpy).toHaveBeenCalledTimes(1);++ // Resolve the first call so it can finish cleanly.+ resolveFirst({ json: () => Promise.resolve([]) });+ await firstCall;+ });++ it('clears the in-flight flag after completion so future calls can run', async () => {+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );++ await logPanel.loadLogs('test-research-cleared-1');+ // Second call after the first completes must execute (not be deduped).+ await logPanel.loadLogs('test-research-cleared-2');++ expect(globalThis.fetch).toHaveBeenCalledTimes(2);+ });++ it('clears dataset.loading even when fetch rejects', async () => {+ // If a refactor drops the `finally` block that clears+ // dataset.loading, a single network error would permanently lock+ // the panel into "skipping duplicate" mode for the rest of the+ // page lifetime — exactly the silent-blank-panel class of bug+ // this PR is fixing.+ const panelContent = document.getElementById('log-panel-content');+ globalThis.fetch = vi.fn(() => Promise.reject(new Error('net down')));++ await logPanel.loadLogs('test-research-throws');++ expect(panelContent.dataset.loading).toBeUndefined();++ // A follow-up call must actually fire fetch again, not be deduped.+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );+ await logPanel.loadLogs('test-research-throws');+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ });+});++describe('addConsoleLog — placeholder removal', () => {+ it('removes the empty-state placeholder when adding a live entry', () => {+ const container = document.getElementById('console-log-container');+ container.innerHTML =+ '<div class="ldr-empty-log-message">No logs available.</div>';++ // Force the panel into an expanded state so addConsoleLog goes+ // straight to addLogEntryToPanel rather than queuing.+ window._logPanelState.expanded = true;++ logPanel.addLog('first live log', 'info');++ // Placeholder is gone, real entry took its place.+ expect(container.querySelector('.ldr-empty-log-message')).toBeNull();+ expect(container.querySelector('.ldr-console-log-entry')).not.toBeNull();+ });+});diff --git a/tests/js/services/socket.test.js b/tests/js/services/socket.test.jsnew file mode 100644index 0000000000..2dcaa6f75a--- /dev/null+++ b/tests/js/services/socket.test.js@@ -0,0 +1,135 @@+/**+ * Tests for services/socket.js+ *+ * Verifies the page-load subscribe/connect race fixes:+ * - subscribeToResearch with a mid-connect socket does NOT call+ * fallbackToPolling and does NOT emit (the connect handler will).+ * - The 'connect' event clears any leftover polling intervals.+ * - subscribeToResearch uses the canonical 'subscribe_to_research'+ * event name, not the legacy 'join'.+ */++let socketModule;++// Mock socket factory that lets tests fire connect/disconnect manually.+function createMockSocket() {+ const handlers = {};+ return {+ connected: false,+ emit: vi.fn(),+ on: vi.fn((event, cb) => {+ handlers[event] ||= [];+ handlers[event].push(cb);+ }),+ off: vi.fn(),+ // Test helper — simulate an event from the server.+ _fire(event, ...args) {+ (handlers[event] || []).forEach((cb) => cb(...args));+ },+ };+}++let mockSocket;++beforeAll(async () => {+ // The socket module checks window.location.pathname for a research page.+ Object.defineProperty(window, 'location', {+ configurable: true,+ value: { ...window.location, pathname: '/progress/abc-123', protocol: 'http:', host: 'localhost' },+ });++ mockSocket = createMockSocket();+ globalThis.io = vi.fn(() => mockSocket);++ // Stub the API + URLBuilder helpers used by polling fallback.+ window.api = {+ getResearchStatus: vi.fn(() => Promise.resolve({ status: 'in_progress' })),+ getCsrfToken: () => '',+ };+ window.ResearchStates = { isTerminal: () => false, logLevel: () => 'info' };++ await import('@js/services/socket.js');+ socketModule = window.socket;+});++beforeEach(() => {+ // Reset polling state and the mock socket for each test.+ window.pollIntervals = {};+ mockSocket.emit.mockClear();+ mockSocket.on.mockClear();+ mockSocket.off.mockClear();+ mockSocket.connected = false;+});++describe('subscribeToResearch — page-load race', () => {+ it('does not fall back to polling when socket exists but is mid-connect', () => {+ // Simulate the page-load state: io() has been called (so socket+ // exists) but the websocket handshake hasn't completed yet.+ socketModule.subscribeToResearch('research-1', () => {});++ // No emit should have happened — the connect handler will subscribe.+ expect(mockSocket.emit).not.toHaveBeenCalled();+ // Polling should not have been kicked off either.+ expect(window.pollIntervals['research-1']).toBeUndefined();+ });++ it('emits subscribe_to_research (not join) when socket is connected', () => {+ mockSocket.connected = true;++ socketModule.subscribeToResearch('research-2', () => {});++ // Should use the canonical event name that the server handles directly.+ const emittedEvents = mockSocket.emit.mock.calls.map((c) => c[0]);+ expect(emittedEvents).toContain('subscribe_to_research');+ expect(emittedEvents).not.toContain('join');+ });++ it('clears stale polling intervals when the socket connects', () => {+ // Simulate a leftover polling interval from a fallback path.+ const intervalId = setInterval(() => {}, 9999);+ window.pollIntervals = { 'research-3': intervalId };++ // Manually fire 'connect' on the mock socket.+ mockSocket.connected = true;+ mockSocket._fire('connect');++ // The interval should have been cleared and the entry removed.+ expect(window.pollIntervals).toEqual({});+ });++ it('re-subscribes to the deferred research id once connect fires', () => {+ // Subscribe while the socket is mid-connect — must NOT emit yet.+ socketModule.subscribeToResearch('research-deferred', () => {});+ expect(mockSocket.emit).not.toHaveBeenCalled();++ // The websocket completes the handshake and the server fires connect.+ mockSocket.connected = true;+ mockSocket._fire('connect');++ // Exactly one subscribe_to_research must have been emitted, with+ // the deferred id — the page-load race fix depends on this+ // follow-through. A regression that drops currentResearchId before+ // the connect handler runs would silently break the progress page.+ const subscribeCalls = mockSocket.emit.mock.calls.filter(+ (c) => c[0] === 'subscribe_to_research'+ );+ expect(subscribeCalls.length).toBe(1);+ expect(subscribeCalls[0][1]).toEqual({ research_id: 'research-deferred' });+ });+});++describe('unsubscribeFromResearch', () => {+ it('emits unsubscribe_from_research (not legacy leave)', () => {+ mockSocket.connected = true;++ // First subscribe so there's something to leave.+ socketModule.subscribeToResearch('research-4', () => {});+ mockSocket.emit.mockClear();++ socketModule.unsubscribeFromResearch('research-4');++ const emittedEvents = mockSocket.emit.mock.calls.map((c) => c[0]);+ expect(emittedEvents).toContain('unsubscribe_from_research');+ expect(emittedEvents).not.toContain('leave');+ });+});diff --git a/tests/utilities/test_log_utils.py b/tests/utilities/test_log_utils.pyindex f1834af860..57fa800059 100644--- a/tests/utilities/test_log_utils.py+++ b/tests/utilities/test_log_utils.py@@ -143,7 +143,10 @@ class TestDatabaseSink:"function": "test_function","line": 42,"level": Mock(name="INFO"),- "extra": {},+ # research_id is required — ResearchLog rows are research-scoped,+ # logs with no research context are filtered out at the queue+ # boundary (they'd never reach the panel anyway).+ "extra": {"research_id": "rid-1"},}with patch(@@ -386,6 +389,70 @@ class TestDatabaseSink:call_args = mock_queue.put_nowait.call_args[0][0]assert call_args["research_id"] == "record-uuid"+ def test_captures_user_password_from_thread_context(self):+ """Should snapshot user_password from per-thread research context onto+ the queue entry, so the daemon can decrypt the per-user SQLCipher DB+ from a thread that can't read the research thread's ContextVar."""+ from local_deep_research.utilities.log_utils import database_sink+ import local_deep_research.utilities.log_utils as module++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "Test",+ "name": "mod",+ "function": "f",+ "line": 1,+ "level": Mock(name="INFO"),+ "extra": {"research_id": "rid-1"},+ }++ fake_ctx = {+ "research_id": "rid-1",+ "username": "alice",+ "user_password": "pw-from-thread-ctx", # gitleaks:allow+ }++ with patch.object(+ module, "_get_research_context_fallback", return_value=fake_ctx+ ):+ with patch.object(module, "has_app_context", return_value=False):+ with patch.object(module, "_log_queue") as mock_queue:+ database_sink(mock_message)++ call_args = mock_queue.put_nowait.call_args[0][0]+ assert call_args["username"] == "alice"+ assert call_args["user_password"] == "pw-from-thread-ctx"++ def test_skips_persistence_when_no_research_or_username(self):+ """Logs without a research_id AND without a username must be dropped+ at the sink, not queued. ResearchLog is research-scoped — system+ DEBUG logs (auth, settings, etc.) attached via flask_session would+ churn through the queue and never resolve to a valid row."""+ from local_deep_research.utilities.log_utils import database_sink+ import local_deep_research.utilities.log_utils as module++ mock_message = Mock()+ mock_message.record = {+ "time": datetime.now(),+ "message": "system debug log",+ "name": "mod",+ "function": "f",+ "line": 1,+ "level": Mock(name="DEBUG"),+ "extra": {},+ }++ # No research context anywhere — neither thread context nor Flask.+ with patch.object(+ module, "_get_research_context_fallback", return_value=None+ ):+ with patch.object(module, "has_app_context", return_value=False):+ with patch.object(module, "_log_queue") as mock_queue:+ database_sink(mock_message)++ mock_queue.put_nowait.assert_not_called()+class TestFrontendProgressSink:"""Tests for frontend_progress_sink function."""@@ -622,6 +689,47 @@ class TestWriteLogToDatabase:# Should not raise_write_log_to_database(log_entry)+ def test_passes_user_password_to_get_user_db_session(self):+ """The password snapshotted onto the queue entry by database_sink+ must be forwarded to get_user_db_session as the password= kwarg.+ Without this the daemon thread cannot decrypt the per-user+ SQLCipher DB and every research-thread MILESTONE log is silently+ dropped."""+ from local_deep_research.utilities.log_utils import (+ _write_log_to_database,+ )++ log_entry = {+ "timestamp": datetime.now(),+ "message": "milestone msg",+ "module": "mod",+ "function": "f",+ "line_no": 1,+ "level": "MILESTONE",+ "research_id": "rid-1",+ "username": "alice",+ "user_password": "pw-from-queue", # gitleaks:allow+ }++ mock_session = MagicMock()+ mock_cm = MagicMock()+ mock_cm.__enter__ = Mock(return_value=mock_session)+ mock_cm.__exit__ = Mock(return_value=None)++ with patch(+ "local_deep_research.database.session_context.get_user_db_session",+ return_value=mock_cm,+ ) as mock_get_session:+ _write_log_to_database(log_entry)++ mock_get_session.assert_called_once()+ call_args = mock_get_session.call_args+ # username is positional (first arg).+ assert call_args.args[0] == "alice"+ # password must be passed as the kwarg the daemon uses for+ # SQLCipher decryption.+ assert call_args.kwargs.get("password") == "pw-from-queue"+class TestLogQueueProcessorDaemon:"""Tests for start_log_queue_processor / stop_log_queue_processor."""diff --git a/tests/utilities/test_log_utils_coverage.py b/tests/utilities/test_log_utils_coverage.pyindex b7cb338721..a7d7092804 100644--- a/tests/utilities/test_log_utils_coverage.py+++ b/tests/utilities/test_log_utils_coverage.py@@ -157,10 +157,13 @@ class TestDatabaseSinkUsernameExtraction:assert queued["username"] == "alice"def test_no_username_queues_none(self):+ """When research_id is set but username isn't, queue entry has+ username=None — the daemon's get_user_db_session will then look it+ up via session/thread-context fallbacks."""from local_deep_research.utilities.log_utils import database_sinkimport local_deep_research.utilities.log_utils as mod- msg = self._make_message(extra={})+ msg = self._make_message(extra={"research_id": "rid-1"})with patch.object(mod, "has_app_context", return_value=False):with patch.object(mod, "_log_queue") as mock_q:@@ -169,6 +172,20 @@ class TestDatabaseSinkUsernameExtraction:queued = mock_q.put_nowait.call_args[0][0]assert queued["username"] is None+ def test_no_research_context_does_not_queue(self):+ """ResearchLog is research-scoped — logs with neither research_id+ nor username should be skipped, not queued."""+ from local_deep_research.utilities.log_utils import database_sink+ import local_deep_research.utilities.log_utils as mod++ msg = self._make_message(extra={})++ with patch.object(mod, "has_app_context", return_value=False):+ with patch.object(mod, "_log_queue") as mock_q:+ database_sink(msg)++ mock_q.put_nowait.assert_not_called()+# ---------------------------------------------------------------------------# flush_log_queue – exception inside loopdiff --git a/tests/utilities/test_log_utils_deep_coverage.py b/tests/utilities/test_log_utils_deep_coverage.pyindex 3f831e426a..f64accdce6 100644--- a/tests/utilities/test_log_utils_deep_coverage.py+++ b/tests/utilities/test_log_utils_deep_coverage.py@@ -167,7 +167,10 @@ class TestDatabaseSink:"""Tests for database_sink."""def test_background_thread_queues(self):- """Queues log entry from background thread."""+ """Queues log entry from background thread.++ Logs need research context to be queued — ResearchLog is+ research-scoped, system logs are skipped at the boundary."""from local_deep_research.utilities.log_utils import (database_sink,_log_queue,@@ -188,7 +191,7 @@ class TestDatabaseSink:"function": "func","line": 42,"level": Mock(name="INFO"),- "extra": {},+ "extra": {"research_id": "rid-1"},}with patch(f"{MODULE}.has_app_context", return_value=False):diff --git a/tests/utilities/test_log_utils_extended.py b/tests/utilities/test_log_utils_extended.pyindex c31d76a608..7ead9bb544 100644--- a/tests/utilities/test_log_utils_extended.py+++ b/tests/utilities/test_log_utils_extended.py@@ -194,7 +194,7 @@ class TestDatabaseSinkExtended:from local_deep_research.utilities.log_utils import database_sinkimport local_deep_research.utilities.log_utils as module- mock_message = _make_mock_message()+ mock_message = _make_mock_message(extra={"research_id": "rid-1"})with patch.object(module, "has_app_context", return_value=False):with patch.object(module, "_log_queue") as mock_queue:diff --git a/tests/web_services/test_socket_service.py b/tests/web_services/test_socket_service.pyindex e0e9f40478..8903a1bea0 100644--- a/tests/web_services/test_socket_service.py+++ b/tests/web_services/test_socket_service.py@@ -143,6 +143,59 @@ class TestSocketIOServiceInit:mock_socketio.on.assert_any_call("subscribe_to_research")+ def test_registers_join_alias_handler(self, mock_flask_app):+ """Test that the 'join' alias handler is registered.++ The JS client emits 'join' on subscribe; without this alias, the+ catch-up snapshot in __handle_subscribe never fires for fresh page+ loads and per-client targeting falls through to broadcast.+ """+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ mock_socketio.on.assert_any_call("join")++ def test_registers_leave_alias_handler(self, mock_flask_app):+ """Test that the 'leave' alias handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ mock_socketio.on.assert_any_call("leave")++ def test_registers_unsubscribe_handler(self, mock_flask_app):+ """Test that unsubscribe_from_research handler is registered."""+ from local_deep_research.web.services.socket_service import (+ SocketIOService,+ )++ mock_socketio = MagicMock()++ with patch(+ "local_deep_research.web.services.socket_service.SocketIO",+ return_value=mock_socketio,+ ):+ SocketIOService(app=mock_flask_app)++ mock_socketio.on.assert_any_call("unsubscribe_from_research")+class TestSocketIOServiceEmitSocketEvent:"""Tests for emit_socket_event method.@@ -540,6 +593,92 @@ class TestSocketIOServiceSubscriptionManagement:assert mock_request.sid not in subscriptions.get("r1", set())assert mock_request.sid not in subscriptions.get("r2", set())+ def test_unsubscribe_discards_sid(+ self, service_with_mocks, mock_request, sample_research_id+ ):+ """Unsubscribe handler removes the sid from the subscription set."""+ svc, _ = service_with_mocks+ svc._SocketIOService__socket_subscriptions = {+ sample_research_id: {mock_request.sid, "other-sid"},+ }++ svc._SocketIOService__handle_unsubscribe(+ {"research_id": sample_research_id}, mock_request+ )++ subscriptions = svc._SocketIOService__socket_subscriptions+ assert mock_request.sid not in subscriptions[sample_research_id]+ # Other clients are untouched+ assert "other-sid" in subscriptions[sample_research_id]++ def test_unsubscribe_ignores_missing_research_id(+ self, service_with_mocks, mock_request+ ):+ """Unsubscribe with missing research_id is a no-op."""+ svc, _ = service_with_mocks+ svc._SocketIOService__socket_subscriptions = {+ "research-1": {"sid-A"},+ }++ # Should not raise+ svc._SocketIOService__handle_unsubscribe({}, mock_request)+ svc._SocketIOService__handle_unsubscribe(None, mock_request)++ # Existing subscriptions are unchanged+ subscriptions = svc._SocketIOService__socket_subscriptions+ assert subscriptions["research-1"] == {"sid-A"}++ def test_unsubscribe_handles_unknown_research_id(+ self, service_with_mocks, mock_request+ ):+ """Unsubscribe for a research_id with no subscribers is a no-op."""+ svc, _ = service_with_mocks+ svc._SocketIOService__socket_subscriptions = {}++ # Should not raise+ svc._SocketIOService__handle_unsubscribe(+ {"research_id": "never-subscribed"}, mock_request+ )++ def test_unsubscribe_prunes_empty_subscription_set(+ self, service_with_mocks, mock_request, sample_research_id+ ):+ """Removing the last sid for a research_id deletes the dict entry.++ Otherwise __socket_subscriptions accumulates stale keys for every+ research_id seen over a long-running server, even after all clients+ have left.+ """+ svc, _ = service_with_mocks+ svc._SocketIOService__socket_subscriptions = {+ sample_research_id: {mock_request.sid},+ }++ svc._SocketIOService__handle_unsubscribe(+ {"research_id": sample_research_id}, mock_request+ )++ assert (+ sample_research_id not in svc._SocketIOService__socket_subscriptions+ )++ def test_unsubscribe_keeps_set_when_other_clients_remain(+ self, service_with_mocks, mock_request, sample_research_id+ ):+ """Unsubscribe must not delete the set while other sids are present."""+ svc, _ = service_with_mocks+ svc._SocketIOService__socket_subscriptions = {+ sample_research_id: {mock_request.sid, "other-sid"},+ }++ svc._SocketIOService__handle_unsubscribe(+ {"research_id": sample_research_id}, mock_request+ )++ assert svc._SocketIOService__socket_subscriptions[+ sample_research_id+ ] == {"other-sid"}+class TestSocketIOServiceErrorHandling:"""Tests for error handling methods.