~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(logpanel): recompute counters from DOM after bulk merge (#5128)
S277191be816b
diff --git a/changelog.d/+logpanel-counter-drift-clamp.bugfix.md b/changelog.d/+logpanel-counter-drift-clamp.bugfix.mdnew file mode 100644index 0000000000..adad17aa12--- /dev/null+++ b/changelog.d/+logpanel-counter-drift-clamp.bugfix.md@@ -0,0 +1 @@+Research Logs panel counter drift: re-derive the per-category badge totals and the header indicator from the rendered DOM after every `loadLogsForResearch` bulk path (the empty-DOM batch path and the `hasLiveEntries` merge path). Previously, when socket events populated live entries while the persisted-log fetch was in flight, the merge branch iterated `addLogEntryToPanel(..., false)` over a payload that exceeded the cap; each insert fired a prune decrement with no compensating increment, so the badge totals and the indicator drifted negative even though the DOM stayed at the cap. The structural fix eliminates the drift source so `_logPanelState.counts` and `.ldr-log-indicator` are always consistent with the DOM. The `Math.max(0, ...)` floors in `updateLogCounter` and `updateFilterCounters` remain as defensive guards against future insertion paths that bypass the recompute. Also count every rendered entry (including untracked categories such as `DEBUG`) toward the header indicator and the "All" badge so they stay accurate for valid API output that has no per-filter button — previously both could read `0` even with one rendered row. Also removes the dead-code fallback inside `socket.js` that mutated `#log-indicator` with `+1` directly when neither `window._socketAddLogEntry` nor `window.addConsoleLog` was registered — that path is unreachable on research pages and was a latent source of the same drift.diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex a87d9ae790..9607b83804 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -747,6 +747,17 @@const hasLiveEntries = logContent.querySelector('.ldr-console-log-entry');if (hasLiveEntries) {sortedLogs.forEach(logEntry => addLogEntryToPanel(logEntry, false));+ // Bulk-merge path: addLogEntryToPanel(..., false)+ // emits a prune decrement for every insert above the+ // cap but never issues a compensating increment, so+ // _logPanelState.counts and the header indicator+ // drift below zero even though the DOM ends up at+ // the cap. Re-derive from the rendered DOM here so+ // badges / indicator / state always reflect what's+ // actually shown. See the comment in+ // recomputeCountersFromDom() for why the DOM is the+ // single source of truth.+ recomputeCountersFromDom();if (panelContent) {panelContent.dataset.loaded = 'true';}@@ -772,29 +783,14 @@// even after a long research run flushes the head.pruneToCap(logContent, MAX_LOG_ENTRIES);- // Reset and recompute per-category counts from the DOM- // after the batch insert + prune. Counting off the DOM- // (rather than summing from `allLogs`) ensures the- // badges always match what's actually rendered, even if- // a future refactor adds a third insertion path that- // bypasses `addLogEntryToPanel`. Shape comes from- // emptyCounts() so it stays in sync with the state init.- window._logPanelState.counts = emptyCounts();- logContent.querySelectorAll('.ldr-console-log-entry').forEach((entry) => {- const t = (entry.dataset.logType || 'info').toLowerCase();- if (window._logPanelState.counts[t] !== undefined) {- window._logPanelState.counts[t]++;- }- });- updateFilterCounters();-- // Update log count indicator- const logIndicators = document.querySelectorAll('.ldr-log-indicator');- if (logIndicators.length > 0) {- logIndicators.forEach(indicator => {- indicator.textContent = logContent.children.length;- });- }+ // Reset and recompute per-category counts and the header+ // indicator from the rendered DOM after the batch insert+ // + prune. The DOM is the single source of truth; the+ // helper handles badge + indicator writes too, so any+ // future insertion path that bypasses addLogEntryToPanel+ // can't desync the counters so long as it lands here+ // before any badge / indicator render.+ recomputeCountersFromDom();// Mark loaded only after a successful non-empty fetch so an// empty initial response doesn't permanently suppress retries.@@ -1149,7 +1145,14 @@const logIndicators = document.querySelectorAll('.ldr-log-indicator');if (logIndicators.length > 0) {const currentCount = parseInt(logIndicators[0].textContent, 10) || 0;- const newCount = currentCount + increment;+ // Defensive floor: the bulk-merge path in loadLogsForResearch+ // now recomputes counts from the DOM (see+ // recomputeCountersFromDom), so this delta path shouldn't+ // drive the indicator below zero in practice. The clamp stays+ // to neutralise any future insertion path that bypasses the+ // recompute (e.g. a regression in addLogEntryToPanel's+ // prune/increment pairing) before the user can see "-1".+ const newCount = Math.max(0, currentCount + increment);// Update all indicatorslogIndicators.forEach(indicator => {@@ -1168,10 +1171,33 @@*/function updateFilterCounters() {const counts = window._logPanelState.counts || {};- const total = (counts.info || 0) +- (counts.milestone || 0) +- (counts.warning || 0) +- (counts.error || 0);+ // Defensive floor: the bulk-merge path in loadLogsForResearch+ // recomputes counts from the DOM (see recomputeCountersFromDom),+ // so this badge read shouldn't render a negative number in+ // practice. The clamp stays so a future insertion path that+ // bypasses the recompute can't surface as "Info -1" before a+ // follow-up fixes it.+ const safe = (n) => Math.max(0, n | 0);+ // The 'All' badge has to reflect EVERY rendered entry, not just+ // the four tracked buckets — DEBUG (and any other future category+ // the API emits but no filter button exists for) is valid+ // persisted output that renders in the DOM but never bumps+ // `counts`. Summing the four buckets would under-count.+ // updateLogCounter / recomputeCountersFromDom drive the+ // .ldr-log-indicator text in lockstep with the actual rendered+ // count, so reading the first indicator is the cheapest single+ // source of truth that stays consistent across the live-insert,+ // prune, and bulk-load paths. Falls back to the bucket sum+ // (which is wrong for untracked categories but at least never+ // negative) when no indicator exists in the DOM yet — e.g. in+ // a test harness that builds the badges before the indicator.+ const indicatorEl = document.querySelector('.ldr-log-indicator');+ const total = indicatorEl+ ? safe(parseInt(indicatorEl.textContent, 10) || 0)+ : safe(counts.info || 0) ++ safe(counts.milestone || 0) ++ safe(counts.warning || 0) ++ safe(counts.error || 0);const badges = document.querySelectorAll('.ldr-filter-count');badges.forEach((badge) => {const key = badge.dataset.filterCount;@@ -1183,9 +1209,48 @@if (key === 'all') {badge.textContent = String(total);} else if (Object.prototype.hasOwnProperty.call(counts, key)) {- badge.textContent = String(counts[key]);+ badge.textContent = String(safe(counts[key]));+ }+ });+ }++ /**+ * Re-derive per-category counts and the header indicator from the+ * rendered DOM. Called at the end of every bulk-load path in+ * `loadLogsForResearch` (the empty-DOM batch path and the+ * hasLiveEntries merge path) so the counters always match the DOM+ * rather than the accumulated +-1 deltas, which can drift during a+ * large merge that exercises prune multiple times. The DOM is the+ * single source of truth: any future insertion path that bypasses+ * `addLogEntryToPanel` cannot desync the counters so long as it+ * lands here before any badge / indicator render.+ */+ function recomputeCountersFromDom() {+ const logContent = document.getElementById('console-log-container');+ if (!logContent) return;+ const counts = emptyCounts();+ let total = 0;+ logContent.querySelectorAll('.ldr-console-log-entry').forEach((entry) => {+ const t = (entry.dataset.logType || 'info').toLowerCase();+ // Count every rendered entry toward the total so the header+ // indicator and All badge stay accurate for categories+ // outside the four tracked buckets (e.g. DEBUG, which is+ // valid persisted API output and renders in the DOM but+ // has no corresponding per-filter button). Per-category+ // increments stay conditional on the bucket being tracked+ // so unknown types don't pollute the filter badges.+ total++;+ if (counts[t] !== undefined) {+ counts[t]++;}});+ window._logPanelState.counts = counts;+ // String() coercion matches updateFilterCounters' ""→"0" guard+ // for happy-dom (real browsers coerce to "0" automatically).+ document.querySelectorAll('.ldr-log-indicator').forEach((indicator) => {+ indicator.textContent = String(total);+ });+ updateFilterCounters();}/**diff --git a/src/local_deep_research/web/static/js/services/socket.js b/src/local_deep_research/web/static/js/services/socket.jsindex 7169e5bcb2..978ee0c264 100644--- a/src/local_deep_research/web/static/js/services/socket.js+++ b/src/local_deep_research/web/static/js/services/socket.js@@ -497,62 +497,24 @@ window.socket = (function() {return;}- // Fallback implementation if none of the above is available- SafeLogger.log('Using socket.js fallback log implementation for:', logEntry.message);- const consoleLogContainer = document.getElementById('console-log-container');- if (!consoleLogContainer) return;-- // Clear empty message if present- const emptyMessage = consoleLogContainer.querySelector('.ldr-empty-log-message');- if (emptyMessage) {- emptyMessage.remove();- }-- // Get the log template- const template = document.getElementById('console-log-entry-template');- if (!template) {- SafeLogger.error('Console log entry template not found');- return;- }-- // Create a new log entry from the template- const entry = document.importNode(template.content, true);-- // Determine the log level - check direct type field first- let logLevel = 'info';- if (logEntry.type) {- logLevel = logEntry.type;- } else if (logEntry.metadata && logEntry.metadata.type) {- logLevel = logEntry.metadata.type;- } else if (logEntry.level) {- logLevel = logEntry.level;- } else if (logEntry.metadata && logEntry.metadata.phase) {- if (logEntry.metadata.phase === 'complete' ||- logEntry.metadata.phase === 'iteration_complete' ||- logEntry.metadata.phase === 'report_complete') {- logLevel = 'milestone';- }- }-- // Format the timestamp- const timestamp = new Date(logEntry.time);- const timeStr = timestamp.toLocaleTimeString();-- // Set content- entry.querySelector('.ldr-log-timestamp').textContent = timeStr;- entry.querySelector('.ldr-log-badge').textContent = logLevel.charAt(0).toUpperCase() + logLevel.slice(1);- entry.querySelector('.ldr-log-message').textContent = logEntry.message;-- // DOM order is oldest -> newest. The log container uses- // column-reverse so appending a live log renders it at the visual top.- consoleLogContainer.appendChild(entry);-- // Update log count- const logIndicator = document.getElementById('log-indicator');- if (logIndicator) {- const currentCount = parseInt(logIndicator.textContent, 10) || 0;- logIndicator.textContent = currentCount + 1;- }+ // Fallback implementation if none of the above is available.+ // On research pages (progress/results/chat) logpanel.js sets+ // both window._socketAddLogEntry and window.addConsoleLog before+ // socket.js events arrive, so this branch is unreachable in+ // practice. It exists for non-research pages (e.g. library)+ // that include the log-panel markup without loading logpanel.js.+ //+ // The previous version of this branch directly mutated+ // #log-indicator with `+1`, bypassing the prune / dedup /+ // per-category-counts machinery in addLogEntryToPanel. That+ // path is the source of the "-1" / counter-drift symptom on+ // /results/<id> when the loadLogsForResearch hasLiveEntries+ // branch races with socket inserts. We now log + bail rather+ // than risk writing a stale +1 to the indicator.+ SafeLogger.warn(+ 'socket.js: no log routing function registered; dropping log entry to avoid indicator drift:',+ logEntry.message+ );}/**diff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.jsindex 136d531a66..da048a38e3 100644--- a/tests/js/components/logpanel.test.js+++ b/tests/js/components/logpanel.test.js@@ -1056,6 +1056,218 @@ describe('per-category counters', () => {});});+describe('loadLogsForResearch — counter drift when live entries already exist', () => {+ // Regression test for the "/results/<id> shows Info -1" symptom.+ //+ // Repro: socket events populated live entries while the persisted+ // logCount fetch was in flight. loadLogsForResearch then fires and+ // sees `hasLiveEntries=true`, so it processes sortedLogs through+ // `addLogEntryToPanel(logEntry, false)` in a tight loop. Each+ // insert with sortedLogs.length over the cap fires prune decrements+ // (`updateLogCounter(-removed.length)`, `counts[prunedType]--`)+ // with no compensating increment, so the per-category counters+ // and the header indicator drift below zero even though the DOM+ // ends up back at the cap.+ //+ // The structural fix (recompute from the DOM in+ // loadLogsForResearch before exiting the merge path) is what this+ // suite locks in. A second test pins the defensive Math.max(0, ...)+ // floor in updateLogCounter / updateFilterCounters so a future+ // refactor that drops the clamp doesn't surface as "Info -1".+ //+ // setupPanelDom() is intentionally NOT used here: it calls+ // logPanel.initialize(rid), which auto-fires a pre-fetch and+ // would race with the deterministic seed below. The DOM is built+ // inline so we own every piece of state the test drives.++ function getFilterCount(key) {+ const el = document.querySelector(+ `.ldr-filter-count[data-filter-count="${key}"]`+ );+ if (!el) return null;+ const trimmed = el.textContent.trim();+ return trimmed === '' ? 0 : parseInt(trimmed, 10);+ }++ function getIndicatorCount() {+ const els = document.querySelectorAll('.ldr-log-indicator');+ if (els.length === 0) return null;+ const trimmed = els[0].textContent.trim();+ return trimmed === '' ? 0 : parseInt(trimmed, 10);+ }++ function buildPanelDom() {+ // Equivalent layout to log_panel.html: container ++ // per-category filter badges + a header indicator. The badge+ // and indicator spans are what updateFilterCounters and+ // updateLogCounter write into; without them the test passes+ // vacuously.+ document.body.innerHTML = `+ <div id="log-panel-content">+ <div id="console-log-container"></div>+ </div>+ <div class="ldr-filter-buttons">+ <span class="ldr-filter-count" data-filter-count="all">0</span>+ <span class="ldr-filter-count" data-filter-count="info">0</span>+ <span class="ldr-filter-count" data-filter-count="milestone">0</span>+ <span class="ldr-filter-count" data-filter-count="warning">0</span>+ <span class="ldr-filter-count" data-filter-count="error">0</span>+ </div>+ <span class="ldr-log-indicator" id="log-indicator">0</span>+ <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>+ `;+ }++ it('recomputes counters from the DOM after a bulk merge that reaches the cap', async () => {+ buildPanelDom();+ const container = document.getElementById('console-log-container');+ for (let i = 0; i < MAX_LOG_ENTRIES; i++) {+ container.appendChild(makeLiveEntry(`seed-${i}`, 'info'));+ }+ window._logPanelState.counts = emptyCounts();+ window._logPanelState.counts.info = MAX_LOG_ENTRIES;+ document.getElementById('log-indicator').textContent =+ String(MAX_LOG_ENTRIES);++ globalThis.fetch = vi.fn(() =>+ Promise.resolve({+ json: () => Promise.resolve({+ logs: [{+ timestamp: '2026-06-09T08:00:00Z',+ message: 'distinct-batch-entry',+ log_type: 'info',+ }],+ }),+ })+ );++ await logPanel.loadLogs('test-research-counter-drift');++ const domEntries = container.querySelectorAll('.ldr-console-log-entry');+ const domCounts = emptyCounts();+ domEntries.forEach((entry) => {+ const type = entry.dataset.logType || 'info';+ if (domCounts[type] !== undefined) {+ domCounts[type]++;+ }+ });+ const domTotal = Object.values(domCounts).reduce(+ (total, count) => total + count,+ 0+ );++ expect(domEntries.length).toBe(MAX_LOG_ENTRIES);+ expect(getIndicatorCount()).toBe(domTotal);+ expect(getFilterCount('all')).toBe(domTotal);+ Object.entries(domCounts).forEach(([type, count]) => {+ expect(getFilterCount(type)).toBe(count);+ expect(window._logPanelState.counts[type]).toBe(count);+ });+ });++ it('clamps the indicator and badges to >= 0 when the underlying state is negative', () => {+ // Guards the defensive Math.max(0, ...) floor in+ // updateLogCounter / updateFilterCounters. The structural+ // recompute in loadLogsForResearch handles the bulk-merge+ // path; this test pins that a future insertion path that+ // bypasses the recompute (e.g. a regression in+ // addLogEntryToPanel's prune/increment pairing) can't surface+ // as "Info -1" before the recompute is extended to cover it.+ //+ // Seed DOM/state directly so the test stays fast and+ // deterministic — no initialize(), no real fetch, no real+ // addLog round-trip.+ buildPanelDom();+ window._logPanelState.counts = emptyCounts();+ window._logPanelState.counts.info = -50;+ window._logPanelState.counts.warning = -10;+ document.getElementById('log-indicator').textContent = '-60';++ // Trigger a re-render via the public addLog path, which+ // reaches updateFilterCounters. We have to initialize()+ // first so window._socketAddLogEntry is registered and the+ // addConsoleLog fallback (which logs-and-bails after #5128)+ // doesn't drop the entry. initialize() with a fresh research+ // id is cheap (no DOM changes happen because state is+ // already seeded) and bounded by the fetch mock below.+ globalThis.fetch = vi.fn(() =>+ Promise.resolve({ json: () => Promise.resolve([]) })+ );+ logPanel.initialize('clamp-guard-rid');++ // addLog writes through _socketAddLogEntry (set up by+ // initialize) into addLogEntryToPanel(logEntry, true), which+ // calls updateLogCounter(1) and updateFilterCounters(). With+ // counts.info seeded at -50, incrementCounter=true adds +1 to+ // counts.info (now -49) and updateFilterCounters' clamp keeps+ // the badge at "0". Indicator textContent was "-60"; +1 from+ // updateLogCounter clamps to "0".+ logPanel.addLog('trigger-render', 'info');++ expect(getIndicatorCount()).toBeGreaterThanOrEqual(0);+ expect(getFilterCount('info')).toBeGreaterThanOrEqual(0);+ expect(getFilterCount('warning')).toBeGreaterThanOrEqual(0);+ expect(getFilterCount('all')).toBeGreaterThanOrEqual(0);+ });++ it('counts untracked categories (e.g. DEBUG) toward the header indicator and All badge after a bulk load', async () => {+ // Regression test for the "All badge stays at 0 for a single+ // DEBUG row" symptom found at PR #5128 head.+ //+ // DEBUG is valid persisted API output — it renders in the DOM+ // via the standard bulk-load path but has no corresponding+ // entry in emptyCounts() (info / milestone / warning / error).+ // The previous recomputeCountersFromDom() guarded the per-+ // category bucket increment behind `counts[t] !== undefined`+ // AND bundled the total bump into the same branch, so DEBUG+ // entries contributed nothing to either the header indicator+ // or the All badge. updateFilterCounters() then summed the+ // four tracked buckets for the All badge, which only made it+ // worse. The fix is: total counts every rendered entry; the+ // per-category increment stays conditional so DEBUG doesn't+ // pollute the per-filter badges.+ buildPanelDom();++ globalThis.fetch = vi.fn(() =>+ Promise.resolve({+ json: () => Promise.resolve({+ logs: [{+ timestamp: '2026-07-01T00:00:00Z',+ message: 'debug-probe-row',+ log_type: 'debug',+ }],+ }),+ })+ );++ await logPanel.loadLogs('test-research-debug-counter');++ const container = document.getElementById('console-log-container');+ const renderedRows = container.querySelectorAll('.ldr-console-log-entry');++ // Exactly one row must be rendered for the probe payload.+ expect(renderedRows.length).toBe(1);+ expect(renderedRows[0].dataset.logType).toBe('debug');++ // The header indicator and All badge must reflect that one+ // rendered row — DEBUG is a rendered log, even though it has+ // no per-filter button. The four tracked buckets stay at zero+ // because the row isn't in any of them.+ expect(getIndicatorCount()).toBe(1);+ expect(getFilterCount('all')).toBe(1);+ expect(getFilterCount('info')).toBe(0);+ expect(getFilterCount('milestone')).toBe(0);+ expect(getFilterCount('warning')).toBe(0);+ expect(getFilterCount('error')).toBe(0);+ });+});+describe('pruneToCap — per-category ordered prune', () => {function seedEntry(container, message, type, index) {const entry = makeLiveEntry(message, type);