~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): show persisted totals for truncated runs (#5115)
S6c91d210932b
diff --git a/changelog.d/5115.bugfix.md b/changelog.d/5115.bugfix.mdnew file mode 100644index 0000000000..b82c9e5ae9--- /dev/null+++ b/changelog.d/5115.bugfix.md@@ -0,0 +1 @@+Research Logs panel now shows the persisted total alongside the rendered slice when a long run has been truncated (for example, "500 of 9,002"), and surfaces a "Load older" action that reloads up to the shared history cap. The "Load older" button is hidden once the panel is already at the history cap so further clicks don't silently re-fetch the same window. Previously the header could look complete even when older rows were not currently visible.diff --git a/src/local_deep_research/web/static/js/components/logpanel.js b/src/local_deep_research/web/static/js/components/logpanel.jsindex 0685ec986c..63cd084ab9 100644--- a/src/local_deep_research/web/static/js/components/logpanel.js+++ b/src/local_deep_research/web/static/js/components/logpanel.js@@ -44,8 +44,66 @@connectedResearchId: null, // Track which research we're connected tocurrentFilter: 'all', // Track current filter typeautoscroll: true, // Track whether autoscroll is enabled.+ // Total number of log rows persisted server-side for the connected+ // research. Sourced from /api/research/<id>/log_count and refreshed+ // on every loadLogs call. Drives the "Showing X of Y" badge in the+ // panel header so users can see at a glance when the DOM is showing+ // a truncated slice of a long run (see issue #4878). Null until the+ // first fetch resolves — distinct from 0, which means "research has+ // zero rows".+ totalLogs: null,+ // Currently rendered limit for this research. Starts at MAX_LOG_ENTRIES+ // and bumps to HISTORY_LOGS_HARD_CAP after the user clicks "Load older",+ // so the panel can show up to the hard cap without a full re-init.+ renderedLimit: null,};+ /**+ * Reset per-research display state when the connected research+ * changes (or on a fresh mount that supersedes a prior ID set on+ * state). Shared between the early-return "already initialized"+ * branch and the fresh-init branch of initializeLogPanel so the+ * two paths can't drift in which fields they clear.+ *+ * Bumps `_countRequestGen` so any in-flight+ * `fetchAndCacheLogCount` promise for the previous research is+ * treated as stale and refused at the response write site+ * (logpanel.js — fetchAndCacheLogCount). Without this guard a+ * late count response for research A could land after research B+ * has loaded and silently overwrite B's badge with A's total.+ *+ * Tears down the "X of Y" / "Load older" cluster that the+ * previous research painted. The button click handler captures+ * `connectedResearchId` at click time, but the element itself is+ * stale — leaving it in the header would either (a) keep the+ * wrong total visible, or (b) trigger a hard-cap fetch against+ * the new research on a stale click. Drop it now so+ * updateLogCountIndicator repaints it fresh for the new research+ * on the next load.+ *+ * @param {string} researchId - New research ID.+ * @param {string|null} previousResearchId - Research ID set on+ * state before the call. Used to decide whether the controls+ * are actually stale (no-op when there is no prior research).+ */+ function resetForResearchSwitch(researchId, previousResearchId) {+ window._logPanelState.connectedResearchId = researchId;+ window._logPanelState.totalLogs = null;+ window._logPanelState.renderedLimit = null;+ window._logPanelState._countRequestGen =+ (window._logPanelState._countRequestGen || 0) + 1;+ if (previousResearchId && previousResearchId !== researchId) {+ document+ .querySelectorAll('.ldr-log-of-total, .ldr-load-older')+ .forEach((el) => el.remove());+ const panelEl = document.getElementById('log-panel-content') ||+ document.getElementById('logPanel');+ if (panelEl) {+ delete panelEl.dataset.loading;+ }+ }+ }+/*** Initialize the log panel* @param {string} researchId - Optional research ID to load logs for@@ -63,7 +121,8 @@// If the research ID has changed, we'll update our connectionSafeLogger.log('Research ID changed from', window._logPanelState.connectedResearchId, 'to', researchId);- window._logPanelState.connectedResearchId = researchId;+ const previousResearchId = window._logPanelState.connectedResearchId;+ resetForResearchSwitch(researchId, previousResearchId);// Reset per-research state for the new research. queuedLogs is// cleared because any queued entries belong to the previous@@ -104,6 +163,14 @@return;}+ // The DOMContentLoaded path stores the ID before calling initialize,+ // but callers such as progress.js and chat.js can invoke this public+ // method directly. Keep the shared ID and per-research display state+ // correct for both entry points.+ const previousResearchId =+ window._logPanelState.connectedResearchId;+ resetForResearchSwitch(researchId, previousResearchId);+// Add callback for log download button.const downloadButton = document.getElementById('log-download-button');if (downloadButton) {@@ -332,23 +399,17 @@// freshly-loaded /chat/ page before a research has started).// URLBuilder.historyLogCount(null) would otherwise produce a// /history/log_count/null request that 404s on every load.+ // The fetch is best-effort; on failure the indicator stays at+ // "0" and loadLogsForResearch will refresh the cached total+ // (or degrade gracefully) once it runs.if (researchId) {- // Fetch the log count from the API and update the indicators- fetch(URLBuilder.historyLogCount(researchId))- .then(response => response.json())- .then(data => {- SafeLogger.log('Log count data:', data);- if (data && typeof data.total_logs === 'number') {- logIndicators.forEach(indicator => {- indicator.textContent = data.total_logs;- });- } else {- SafeLogger.error('Invalid log count data received from API');- }- })- .catch(error => {- SafeLogger.error('Error fetching log count:', error);- });+ fetchAndCacheLogCount(researchId).then((total) => {+ if (typeof total === 'number') {+ logIndicators.forEach(indicator => {+ indicator.textContent = formatNumber(total);+ });+ }+ });}} else {SafeLogger.warn('No log indicators found for initialization');@@ -477,6 +538,62 @@return await response.json();}+ /**+ * Fetch the persisted total row count for a research and cache it on+ * `window._logPanelState.totalLogs`. Shared by initializeLogPanel (initial+ * indicator paint) and loadLogsForResearch (per-load refresh before the+ * "X of Y" badge is rendered).+ *+ * Always clears any previously cached total before re-reading so a+ * transient server error or a research switch leaves the badge+ * honest — the indicator degrades to the rendered count rather than+ * showing a stale "of N" suffix from a previous research. Swallows+ * non-2xx and parse errors: the count endpoint is best-effort, and+ * the panel must keep working when it is unavailable.+ *+ * Generation-guarded: each call snapshots+ * `window._logPanelState._countRequestGen`. If the user switches+ * research while the fetch is in flight, the increment in+ * `initializeLogPanel`'s research-switch branch bumps the+ * generation; this response is then treated as stale and the+ * `totalLogs` write is skipped. Without this guard, a slow count+ * for research A can land after research B has loaded and overwrite+ * B's badge with A's total (PR #5115 follow-up review).+ *+ * @param {string} researchId+ * @returns {Promise<number|null>} The total, or null if the fetch+ * failed / returned a malformed payload / was invalidated by a+ * research switch.+ */+ async function fetchAndCacheLogCount(researchId) {+ window._logPanelState.totalLogs = null;+ if (!researchId) return null;+ const generation = window._logPanelState._countRequestGen || 0;+ try {+ const response = await fetch(URLBuilder.historyLogCount(researchId));+ const data = await response.json();+ // Bail out if the user switched research while this fetch+ // was in flight. The next load (for the new research) will+ // refetch and overwrite totalLogs itself.+ if ((window._logPanelState._countRequestGen || 0) !== generation) {+ SafeLogger.log(+ 'Discarding stale log count response for',+ researchId,+ '— research has changed'+ );+ return null;+ }+ if (data && typeof data.total_logs === 'number') {+ window._logPanelState.totalLogs = data.total_logs;+ return data.total_logs;+ }+ SafeLogger.error('Invalid log count data received from API');+ } catch (e) {+ SafeLogger.warn('Failed to fetch log count:', e);+ }+ return null;+ }+/*** Trim log entries from the container down to `cap`, preferring to drop* the least-actionable categories first.@@ -548,7 +665,7 @@* Load logs for a specific research* @param {string} researchId - The research ID to load logs for*/- async function loadLogsForResearch(researchId) {+ async function loadLogsForResearch(researchId, limit = MAX_LOG_ENTRIES) {// 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.@@ -560,6 +677,13 @@if (panelEl) {panelEl.dataset.loading = 'true';}+ // Track the requested limit on shared state so the "Showing X of Y"+ // header can compare against the persisted total and expose "Load+ // older" only when there is more to load. The "Load older" button+ // re-enters loadLogsForResearch with hard_cap (5000) — we want the+ // header to reflect the *current* limit, not the original default.+ window._logPanelState.renderedLimit = limit;+ const generation = window._logPanelState._countRequestGen || 0;try {// Show loading state, but only if the container has no live@@ -572,9 +696,30 @@SafeLogger.log('Loading logs for research ID:', researchId);- const data = await fetchLogsForResearch(researchId, MAX_LOG_ENTRIES);+ // Fetch the persisted total for every load. Long-running research+ // can add rows between the initial prefetch and a later "Load+ // older" click, so reusing an old total would make the badge lie.+ // A failed or malformed count response clears the cached value so+ // the indicator degrades to the rendered count only.+ await fetchAndCacheLogCount(researchId);++ if ((window._logPanelState._countRequestGen || 0) !== generation) {+ SafeLogger.log('Discarding stale logs load (post-count) for', researchId);+ return;+ }++ // Use the caller's requested limit (MAX_LOG_ENTRIES by default,+ // window.LDR_LOG_LIMITS.hard_cap from the "Load older" button).+ // fetchLogsForResearch clamps ?limit server-side to the hard cap,+ // so a malicious caller can't bypass the safety ceiling.+ const data = await fetchLogsForResearch(researchId, limit);SafeLogger.log('Logs API response:', data);+ if ((window._logPanelState._countRequestGen || 0) !== generation) {+ SafeLogger.log('Discarding stale logs response (post-fetch) for', researchId);+ return;+ }+// Initialize array to hold all logs from different sourcesconst allLogs = [];@@ -796,6 +941,7 @@if (panelContent) {panelContent.dataset.loaded = 'true';}+ updateLogCountIndicator(logContent);return;}@@ -813,10 +959,9 @@}logContent.appendChild(fragment);- // Prune to the cap, preferring to drop info/milestone entries over- // warnings/errors so the panel keeps its diagnostic entries- // even after a long research run flushes the head.- pruneToCap(logContent, MAX_LOG_ENTRIES);+ const renderCap =+ window._logPanelState.renderedLimit ?? MAX_LOG_ENTRIES;+ pruneToCap(logContent, renderCap);// Reset and recompute per-category counts and the header// indicator from the rendered DOM after the batch insert@@ -827,6 +972,14 @@// before any badge / indicator render.recomputeCountersFromDom();+ // Update log count indicator and (if truncated) render a+ // "Showing X of Y" badge with a "Load older" button. The prior+ // implementation always wrote the DOM child count, which+ // overwrote the total set by initializeLogPanel and hid the+ // fact that the user was looking at a truncated slice of a+ // long run (issue #4878 — "500 of 9,002, no indication").+ updateLogCountIndicator(logContent);+// Mark loaded only after a successful non-empty fetch so an// empty initial response doesn't permanently suppress retries.if (panelContent) {@@ -837,6 +990,15 @@} catch (error) {SafeLogger.error('Error loading logs:', error);+ if ((window._logPanelState._countRequestGen || 0) !== generation) {+ SafeLogger.log(+ 'Discarding error DOM write for stale research ID:',+ researchId,+ '— research has changed'+ );+ return;+ }+// Show error in log panel// SECURITY: error.message can contain arbitrary text — must escape before innerHTMLconst logContent = document.getElementById('console-log-container');@@ -845,7 +1007,7 @@logContent.innerHTML = `<div class="ldr-error-message">Error loading logs: ${escapeHtml(error.message)}</div>`;}} finally {- if (panelEl) {+ if (panelEl && (window._logPanelState._countRequestGen || 0) === generation) {delete panelEl.dataset.loading;}}@@ -1137,7 +1299,9 @@// milestones, then warnings, then errors) so a long research run// doesn't flush the panel's diagnostic tail. Mirrors the batch-load// prune above.- const removed = pruneToCap(consoleLogContainer, MAX_LOG_ENTRIES);+ const renderCap =+ window._logPanelState.renderedLimit ?? MAX_LOG_ENTRIES;+ const removed = pruneToCap(consoleLogContainer, renderCap);if (removed.length > 0) {// Keep the per-category counter for the filter badges in sync// with what was actually removed. pruneToCap returns the@@ -1173,29 +1337,150 @@}/**- * Helper function to update the log counter- * @param {number} increment - Amount to increment the counter by+ * Render the log-panel-header indicator (`.ldr-log-indicator`) with the+ * current DOM count, and append a "Load older" button when the persisted+ * total exceeds the rendered slice (issue #4878 — user sees "500" with+ * no indication they're looking at ~5% of a 9,002-row run).+ *+ * Layout:+ * <span class="ldr-log-indicator" id="log-indicator">500</span>+ * <span class="ldr-log-of-total"> of 9,002</span>+ * <button class="ldr-load-older">Load older</button>+ *+ * The button is dynamically created/removed so the header stays compact+ * for short runs. Clicking it calls loadLogsForResearch with the shared+ * hard cap (window.LDR_LOG_LIMITS.hard_cap), which is the same ceiling+ * the existing "Download Logs" button uses. Cursor pagination is out of+ * scope for this fix; the most recent `hard_cap` rows is the largest+ * window the current API can return in a single round trip.+ *+ * The button is suppressed — but the "X of Y" badge is kept — once the+ * requested `renderedLimit` reaches the shared hard cap. Beyond that+ * ceiling the server returns the same window and a second click would+ * be a no-op; hiding the button is a clearer signal than letting users+ * click into a dead end.+ *+ * Safe to call repeatedly — it de-duplicates itself by removing any+ * pre-existing "of Y" suffix / "Load older" button before re-appending.+ *+ * @param {Element} [container] - The log container element. When+ * omitted, falls back to document.getElementById('console-log-container')+ * so the live-insert path doesn't need to pass it.*/- function updateLogCounter(increment) {+ function updateLogCountIndicator(container) {const logIndicators = document.querySelectorAll('.ldr-log-indicator');- if (logIndicators.length > 0) {- const currentCount = parseInt(logIndicators[0].textContent, 10) || 0;- // 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 indicators- logIndicators.forEach(indicator => {- indicator.textContent = newCount;- });+ if (logIndicators.length === 0) return;++ const containerEl =+ container ||+ document.getElementById('console-log-container');+ const rendered = containerEl+ ? containerEl.querySelectorAll('.ldr-console-log-entry').length+ : 0;+ const total = window._logPanelState.totalLogs;+ const truncated =+ typeof total === 'number' &&+ total > rendered;++ // Write the rendered count (the "X" in "X of Y"). The formatNumber+ // helper groups thousands so a 9,002-row run renders as "9,002"+ // instead of "9002".+ const renderedLabel = formatNumber(rendered);+ logIndicators.forEach(indicator => {+ indicator.textContent = renderedLabel;+ });++ // Append / refresh the "of Y · Load older" cluster. We look up the+ // existing button by class so a second updateLogCountIndicator call+ // (e.g. after a live insert) doesn't pile up duplicate buttons.+ const headerEl = logIndicators[0].parentElement;+ if (!headerEl) return;++ // Remove any prior "of Y" suffix / "Load older" button so a count+ // change (live insert, "Load older" click) renders cleanly.+ headerEl.querySelectorAll('.ldr-log-of-total, .ldr-load-older').forEach((el) => {+ el.remove();+ });++ if (!truncated) {+ return;+ }++ const ofTotal = document.createElement('span');+ ofTotal.className = 'ldr-log-of-total';+ ofTotal.textContent = ` of ${formatNumber(total)}`;+ headerEl.appendChild(ofTotal);++ // Hide the button — but keep the "X of Y" badge — once the current+ // request is already at the server-side ceiling. A re-click would+ // re-fetch the same window (server clamps ?limit) and is therefore+ // a silent no-op, which surfaced as a confusing UX after PR #5115+ // for long runs (LearningCircuit review, 2026-07-16).+ const hardCap = window.LDR_LOG_LIMITS?.hard_cap ?? 5000;+ const currentLimit = window._logPanelState.renderedLimit;+ if (typeof currentLimit === 'number' && currentLimit >= hardCap) {+ return;+ }++ const loadOlder = document.createElement('button');+ loadOlder.type = 'button';+ loadOlder.className = 'ldr-small-btn ldr-load-older';+ loadOlder.textContent = 'Load older';+ loadOlder.title =+ 'Load the full server-side cap (' ++ hardCap ++ ' most recent rows)';+ loadOlder.addEventListener('click', (event) => {+ // The button is appended to the same header that owns the+ // collapse/expand toggle. Without stopping propagation the+ // click would bubble up and toggle the panel, hiding the+ // expanded log list the user just asked to load. PR #5115+ // follow-up review (LearningCircuit, 2026-07-19).+ event.stopPropagation();+ const researchId = window._logPanelState.connectedResearchId;+ if (!researchId) return;+ // loadLogsForResearch is the same entry point used by the+ // panel toggle and the live socket path; it handles the+ // in-flight guard, batch-insert, and per-category counter+ // recompute. Re-entering it with `hardCap` re-fetches the+ // most-recent hardCap rows and re-renders "X of Y" (with X+ // now bumped). Once it returns, the renderedLimit-vs-hardCap+ // check above suppresses this same button so the user can't+ // click it again into a no-op.+ loadLogsForResearch(researchId, hardCap);+ });+ headerEl.appendChild(loadOlder);+ }++ /**+ * Localized thousands separator for the log count badge and the+ * "of Y" suffix. Falls back to Intl.NumberFormat with the document's+ * language if available, otherwise comma-grouped English.+ * @param {number} n+ * @returns {string}+ */+ function formatNumber(n) {+ try {+ return new Intl.NumberFormat(document.documentElement.lang || undefined).format(n);+ } catch {+ return String(n).replace(/\B(?=(?:\d{3})+(?!\d))/g, ',');}}+ /**+ * Helper function to update the log counter (used by live socket+ * insert and prune paths). Unlike the original implementation, this+ * now defers to updateLogCountIndicator so the "X of Y" badge and+ * "Load older" button stay in sync with the DOM. The `increment`+ * parameter is retained for callers (addLog, addLogEntryToPanel)+ * but is recomputed from the actual DOM child count to avoid+ * drift between the indicator and the entries.+ * @param {number} _increment - Unused; recomputed from the DOM.+ */+ function updateLogCounter(_increment) {+ updateLogCountIndicator();+ }+/*** Refresh the per-filter count badges (and the "All" total derived* from them) from window._logPanelState.counts. Called whenever thediff --git a/tests/js/components/logpanel.test.js b/tests/js/components/logpanel.test.jsindex ce9c82a065..dcd43b63d9 100644--- a/tests/js/components/logpanel.test.js+++ b/tests/js/components/logpanel.test.js@@ -30,7 +30,8 @@ beforeAll(async () => {// Stubs the IIFE expects to find on window.window.escapeHtml = (s) => String(s ?? '').replace(/[&<>"']/g, '');window.URLBuilder = {- researchLogs: (id) => `/api/research/${id}/logs`,+ researchLogs: (id, limit) =>+ `/api/research/${id}/logs${limit ? `?limit=${limit}` : ''}`,historyLogCount: (id) => `/api/research/${id}/log_count`,};@@ -79,6 +80,8 @@ beforeEach(() => {// tests that only exercise loadLogs/addLog don't rely on this.window._logPanelState.initialized = false;window._logPanelState.connectedResearchId = null;+ window._logPanelState.totalLogs = null;+ window._logPanelState.renderedLimit = null;}});@@ -138,8 +141,10 @@ function setupPanelDom({ page = 'progress', researchId } = {}) {// Each test uses a fresh research ID so initialize() doesn't short-circuit// on the same-ID check at logpanel.js:44.- const rid = researchId || `rid-${Math.random().toString(36).slice(2)}`;- logPanel.initialize(rid);+ if (researchId !== null) {+ const rid = researchId || `rid-${Math.random().toString(36).slice(2)}`;+ logPanel.initialize(rid);+ }}function makeLiveEntry(message, type = 'info') {@@ -261,7 +266,12 @@ describe('loadLogsForResearch — in-flight deduplication', () => {const secondCall = logPanel.loadLogs('test-research-dedup');await secondCall;- // Only one fetch should have happened so far.+ // Only one fetch should have happened so far. loadLogsForResearch+ // makes 2 fetches today (log_count + logs) but the in-flight guard+ // kicks in BEFORE the second fetch is even attempted — both fetches+ // share the same panelEl.dataset.loading flag, set synchronously at+ // the top of loadLogsForResearch, so the second call returns without+ // any fetch happening.expect(fetchSpy).toHaveBeenCalledTimes(1);// Resolve the first call so it can finish cleanly.@@ -278,7 +288,8 @@ describe('loadLogsForResearch — in-flight deduplication', () => {// Second call after the first completes must execute (not be deduped).await logPanel.loadLogs('test-research-cleared-2');- expect(globalThis.fetch).toHaveBeenCalledTimes(2);+ // 2 fetch calls per loadLogs (log_count + logs).+ expect(globalThis.fetch).toHaveBeenCalledTimes(4);});it('clears dataset.loading even when fetch rejects', async () => {@@ -299,7 +310,8 @@ describe('loadLogsForResearch — in-flight deduplication', () => {Promise.resolve({ json: () => Promise.resolve([]) }));await logPanel.loadLogs('test-research-throws');- expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ // 2 fetch calls per loadLogs (log_count + logs).+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);});});@@ -1302,6 +1314,438 @@ describe('per-category counters', () => {});});+describe('log count indicator — persisted total and Load older', () => {+ function addLogIndicator(researchId) {+ const indicator = document.createElement('span');+ indicator.className = 'ldr-log-indicator';+ indicator.id = 'log-indicator';+ indicator.textContent = '0';+ document.getElementById('log-panel-toggle').appendChild(indicator);+ window._logPanelState.connectedResearchId = researchId;+ return indicator;+ }++ function makeLogs(count) {+ return Array.from({ length: count }, (_, index) => ({+ timestamp: `2026-05-08T12:00:${String(index).padStart(2, '0')}Z`,+ message: `history-${index}`,+ log_type: 'info',+ }));+ }++ function mockLogFetch(totalLogs, initialLogs, expandedLogs = initialLogs) {+ const fetchSpy = vi.fn((url) => {+ if (url.endsWith('/log_count')) {+ return Promise.resolve({+ json: () => Promise.resolve({ total_logs: totalLogs }),+ });+ }+ const logs = url.includes('?limit=5000')+ ? expandedLogs+ : initialLogs;+ return Promise.resolve({+ json: () => Promise.resolve(logs),+ });+ });+ globalThis.fetch = fetchSpy;+ return fetchSpy;+ }++ it('shows only the rendered count when the persisted total is fully rendered', async () => {+ const researchId = 'log-count-equal';+ const indicator = addLogIndicator(researchId);+ mockLogFetch(2, makeLogs(2));++ await logPanel.loadLogs(researchId);++ expect(indicator.textContent).toBe('2');+ expect(document.querySelector('.ldr-log-of-total')).toBeNull();+ expect(document.querySelector('.ldr-load-older')).toBeNull();+ });++ it('shows the persisted total and Load older when the rendered slice is truncated', async () => {+ const researchId = 'log-count-truncated';+ const indicator = addLogIndicator(researchId);+ mockLogFetch(9002, makeLogs(2));++ await logPanel.loadLogs(researchId);++ expect(indicator.textContent).toBe('2');+ expect(document.querySelector('.ldr-log-of-total').textContent).toBe(+ ' of 9,002'+ );+ expect(document.querySelector('.ldr-load-older')).not.toBeNull();+ });++ it('degrades to the rendered count when the persisted total cannot be fetched', async () => {+ const researchId = 'log-count-unavailable';+ const indicator = addLogIndicator(researchId);+ const fetchSpy = vi.fn((url) => {+ if (url.endsWith('/log_count')) {+ return Promise.reject(new Error('count endpoint unavailable'));+ }+ return Promise.resolve({+ json: () => Promise.resolve(makeLogs(2)),+ });+ });+ globalThis.fetch = fetchSpy;++ await logPanel.loadLogs(researchId);++ expect(indicator.textContent).toBe('2');+ expect(document.querySelector('.ldr-log-of-total')).toBeNull();+ expect(document.querySelector('.ldr-load-older')).toBeNull();+ });++ it('reloads up to the hard cap and refreshes the badge after Load older', async () => {+ const researchId = 'log-count-load-older';+ const indicator = addLogIndicator(researchId);+ const fetchSpy = mockLogFetch(9002, makeLogs(2), makeLogs(4));++ await logPanel.loadLogs(researchId);+ const loadOlder = document.querySelector('.ldr-load-older');+ expect(loadOlder).not.toBeNull();++ loadOlder.click();+ await vi.waitFor(() => {+ expect(fetchSpy).toHaveBeenCalledWith(+ `/api/research/${researchId}/logs?limit=5000`+ );+ expect(+ document.querySelectorAll('.ldr-console-log-entry').length+ ).toBe(4);+ });++ expect(indicator.textContent).toBe('4');+ expect(document.querySelector('.ldr-log-of-total').textContent).toBe(+ ' of 9,002'+ );+ expect(window._logPanelState.renderedLimit).toBe(5000);++ // After "Load older" the renderedLimit has reached the shared+ // hard cap (5000), so any further click would re-fetch the same+ // window (server clamps ?limit). The button must be removed+ // (suppressed) while the "X of Y" badge stays visible — see the+ // post-PR #5115 review feedback (LearningCircuit, 2026-07-16)+ // about no-op second clicks for 9,002-row runs.+ expect(document.querySelector('.ldr-load-older')).toBeNull();+ expect(document.querySelector('.ldr-log-of-total').textContent).toBe(+ ' of 9,002'+ );+ });++ it('hides the Load older button after a click once renderedLimit reaches the hard cap', async () => {+ // When the rendered limit on a fresh load is at or above the+ // shared hard cap, the button must be suppressed from the start+ // — there is no further row to fetch. We model that by lowering+ // the default render cap below the hard cap first (so the+ // indicator can show a truncated "X of Y" and a Load older+ // button), then clicking Load older with a window that already+ // returns the full hard cap window so renderedLimit = hard cap.+ const researchId = 'log-count-pre-clicked-at-cap';+ const indicator = addLogIndicator(researchId);+ // Initial fetch returns 2 rows; "Load older" fetch returns the+ // same hard-cap window of 4 rows, which matches the real+ // server-side clamp (server returns at most `hard_cap` rows).+ const fetchSpy = mockLogFetch(9002, makeLogs(2), makeLogs(4));++ await logPanel.loadLogs(researchId);+ const loadOlder = document.querySelector('.ldr-load-older');+ expect(loadOlder).not.toBeNull();++ loadOlder.click();+ await vi.waitFor(() => {+ expect(fetchSpy).toHaveBeenCalledWith(+ `/api/research/${researchId}/logs?limit=5000`+ );+ });++ // After the click, the button must be gone even though the+ // panel is still showing fewer entries than the persisted total.+ // The "X of Y" badge must remain so the truncation is still+ // visible to the user.+ expect(document.querySelector('.ldr-load-older')).toBeNull();+ expect(indicator.textContent).toBe('4');+ expect(document.querySelector('.ldr-log-of-total').textContent).toBe(+ ' of 9,002'+ );+ expect(window._logPanelState.renderedLimit).toBe(5000);+ });++ it('stops propagation on the Load older click so the panel does not collapse', async () => {+ // The button is appended inside the same header element that+ // owns the collapse/expand toggle (log-panel-toggle). Without+ // event.stopPropagation the click bubbles up and triggers the+ // toggle handler, hiding the expanded log list the user just+ // asked to load. Lock that stopPropagation is wired in.+ const researchId = 'log-count-stop-propagation';+ addLogIndicator(researchId);+ mockLogFetch(9002, makeLogs(2));++ await logPanel.loadLogs(researchId);+ const loadOlder = document.querySelector('.ldr-load-older');+ expect(loadOlder).not.toBeNull();++ // Spy on stopPropagation. happy-dom's Event dispatches+ // stopPropagation through the normal EventTarget path, so a+ // click on the button should land the call before any bubble+ // listener on the parent runs. The bubble-phase listener+ // (third arg omitted/false) fires AFTER the button handler,+ // so stopPropagation must have run by the time it would+ // execute.+ const stopSpy = vi.spyOn(Event.prototype, 'stopPropagation');+ const toggleEl = document.getElementById('log-panel-toggle');+ const bubbleSpy = vi.fn();+ toggleEl.addEventListener('click', bubbleSpy);++ loadOlder.click();++ expect(stopSpy).toHaveBeenCalled();+ expect(bubbleSpy).not.toHaveBeenCalled();++ stopSpy.mockRestore();+ toggleEl.removeEventListener('click', bubbleSpy);+ });++ it('removes stale "of Y" and "Load older" controls when the research changes', async () => {+ // Initialize for research A and let the indicator paint a+ // truncated "X of Y" with a Load older button. Then re-init+ // with research B — the previous research's controls must be+ // torn down so the header doesn't keep showing A's persisted+ // total next to B's content (PR #5115 follow-up review).+ const researchA = 'log-count-research-a';+ addLogIndicator(researchA);+ mockLogFetch(9002, makeLogs(2));++ await logPanel.loadLogs(researchA);+ expect(document.querySelector('.ldr-log-of-total')).not.toBeNull();+ expect(document.querySelector('.ldr-load-older')).not.toBeNull();++ // Re-init for research B. Same-ID early return must be+ // bypassed — supply a different ID.+ const researchB = 'log-count-research-b';+ logPanel.initialize(researchB);++ // Both controls must be gone immediately after the switch so a+ // pending click on the old button can't fire against B.+ expect(document.querySelector('.ldr-log-of-total')).toBeNull();+ expect(document.querySelector('.ldr-load-older')).toBeNull();+ expect(window._logPanelState.connectedResearchId).toBe(researchB);+ expect(window._logPanelState.totalLogs).toBeNull();+ // Generation must have been bumped so any in-flight count+ // response for A is treated as stale.+ expect(typeof window._logPanelState._countRequestGen).toBe('number');+ });++ it('discards a stale count response from the previous research', async () => {+ // Research A's fetch resolves AFTER the user has switched to+ // research B. The response must NOT overwrite B's badge with+ // A's total — the generation guard should drop it.+ const researchA = 'log-count-stale-a';+ const researchB = 'log-count-stale-b';++ // Build a fetch spy where the count response for A is delayed+ // so we can switch to B while it's in flight.+ let resolveCount;+ const countPromise = new Promise((resolve) => {+ resolveCount = resolve;+ });+ const fetchSpy = vi.fn((url) => {+ if (url.endsWith('/log_count') && url.includes(researchA)) {+ return Promise.resolve({+ json: () => countPromise,+ });+ }+ if (url.endsWith('/logs')) {+ return Promise.resolve({+ json: () => Promise.resolve(makeLogs(2)),+ });+ }+ return Promise.resolve({+ json: () => Promise.resolve({ total_logs: 100 }),+ });+ });+ globalThis.fetch = fetchSpy;++ addLogIndicator(researchA);+ const loadA = logPanel.loadLogs(researchA);+ // Yield so the count fetch for A has been initiated but not+ // yet resolved (it's gated on our manual resolveCount).+ await Promise.resolve();+ await Promise.resolve();++ // Switch to B before A's count resolves.+ logPanel.initialize(researchB);++ // Now resolve A's count late. The guard should treat it as+ // stale and NOT write totalLogs.+ resolveCount({ total_logs: 9002 });+ await loadA;++ // totalLogs should be null (B hasn't fetched its own count+ // yet, and A's was discarded). B's subsequent loadLogs call+ // would set it; here we only verify the stale write was+ // skipped.+ expect(window._logPanelState.totalLogs).toBeNull();+ });++ it('discards stale log responses and DOM commits when switching research while /logs is in flight (success case)', async () => {+ // Research A's fetch resolves AFTER the user has switched to+ // research B. The response must NOT write to the DOM or mark+ // as loaded.+ const researchA = 'log-stale-logs-a';+ const researchB = 'log-stale-logs-b';++ // Build a fetch spy where the logs response for A is delayed+ // so we can switch to B while it's in flight.+ let logsFetchStartedA;+ const fetchStartedPromiseA = new Promise((resolve) => {+ logsFetchStartedA = resolve;+ });++ let resolveLogsA;+ const logsAPromise = new Promise((resolve) => {+ resolveLogsA = resolve;+ });++ const fetchSpy = vi.fn((url) => {+ if (url.includes('/logs') && url.includes(researchA)) {+ logsFetchStartedA();+ return Promise.resolve({+ json: () => logsAPromise,+ });+ }+ if (url.includes('/logs') && url.includes(researchB)) {+ return Promise.resolve({+ json: () => Promise.resolve([+ { timestamp: new Date().toISOString(), message: 'B logs', log_type: 'info' }+ ]),+ });+ }+ // For count and other requests+ return Promise.resolve({+ json: () => Promise.resolve({ total_logs: 100 }),+ });+ });+ globalThis.fetch = fetchSpy;++ // Initialize for A without background pre-fetch.+ setupPanelDom({ researchId: null });+ logPanel.initialize(null);+ window._logPanelState.connectedResearchId = researchA;++ // Trigger loadLogs for A (test owns this request).+ const loadA = logPanel.loadLogs(researchA);++ // Wait until A's /logs request begins.+ await fetchStartedPromiseA;++ // Switch to B before A's logs fetch resolves.+ // B's initialize will clear the container and reset dataset.loaded.+ logPanel.initialize(researchB);+ const loadB = logPanel.loadLogs(researchB);+ await loadB;++ const container = document.getElementById('console-log-container');+ const panelContent = document.getElementById('log-panel-content');++ // B should be successfully loaded and contain its logs+ let texts = Array.from(container.querySelectorAll('.ldr-log-message')).map(el => el.textContent);+ expect(texts).toContain('B logs');+ expect(panelContent.dataset.loaded).toBe('true');+ expect(panelContent.dataset.loading).toBeUndefined();++ // Resolve A's logs late.+ resolveLogsA([+ { timestamp: new Date().toISOString(), message: 'A logs', log_type: 'info' }+ ]);+ await loadA;++ // Verify A's logs did NOT render into B's container.+ texts = Array.from(container.querySelectorAll('.ldr-log-message')).map(el => el.textContent);+ expect(texts).not.toContain('A logs');+ expect(texts).toContain('B logs');+ expect(panelContent.dataset.loaded).toBe('true');+ expect(panelContent.dataset.loading).toBeUndefined();+ });++ it('discards stale log responses and DOM commits when switching research while /logs is in flight (failure/rejection case)', async () => {+ // Research A's fetch rejects AFTER the user has switched to+ // research B. The error response must NOT overwrite B's DOM,+ // clear loaded status, or leave B's container in an error state.+ const researchA = 'log-stale-logs-fail-a';+ const researchB = 'log-stale-logs-fail-b';++ let logsFetchStartedA;+ const fetchStartedPromiseA = new Promise((resolve) => {+ logsFetchStartedA = resolve;+ });++ let rejectLogsA;+ const logsAPromise = new Promise((resolve, reject) => {+ rejectLogsA = reject;+ });++ const fetchSpy = vi.fn((url) => {+ if (url.includes('/logs') && url.includes(researchA)) {+ logsFetchStartedA();+ return Promise.resolve({+ json: () => logsAPromise,+ });+ }+ if (url.includes('/logs') && url.includes(researchB)) {+ return Promise.resolve({+ json: () => Promise.resolve([+ { timestamp: new Date().toISOString(), message: 'B logs', log_type: 'info' }+ ]),+ });+ }+ // For count and other requests+ return Promise.resolve({+ json: () => Promise.resolve({ total_logs: 100 }),+ });+ });+ globalThis.fetch = fetchSpy;++ // Initialize for A without background pre-fetch.+ setupPanelDom({ researchId: null });+ logPanel.initialize(null);+ window._logPanelState.connectedResearchId = researchA;++ // Trigger loadLogs for A (test owns this request).+ const loadA = logPanel.loadLogs(researchA);++ // Wait until A's /logs request begins.+ await fetchStartedPromiseA;++ // Switch to B before A's logs fetch rejects.+ logPanel.initialize(researchB);+ const loadB = logPanel.loadLogs(researchB);+ await loadB;++ const container = document.getElementById('console-log-container');+ const panelContent = document.getElementById('log-panel-content');++ // B should be successfully loaded and contain its logs+ let texts = Array.from(container.querySelectorAll('.ldr-log-message')).map(el => el.textContent);+ expect(texts).toContain('B logs');+ expect(panelContent.dataset.loaded).toBe('true');+ expect(panelContent.dataset.loading).toBeUndefined();++ // Reject A's logs fetch late.+ rejectLogsA(new Error('A logs fetch failed'));+ await loadA;++ // Verify B's DOM, loaded marker, and loading state remain untouched.+ texts = Array.from(container.querySelectorAll('.ldr-log-message')).map(el => el.textContent);+ expect(texts).not.toContain('A logs fetch failed');+ expect(container.querySelector('.ldr-error-message')).toBeNull();+ expect(texts).toContain('B logs');+ expect(panelContent.dataset.loaded).toBe('true');+ expect(panelContent.dataset.loading).toBeUndefined();+ });+});+describe('loadLogsForResearch — counter drift when live entries already exist', () => {// Regression test for the "/results/<id> shows Info -1" symptom.//