Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(web): harden and deduplicate formatBytes (#5003)

LearningCircuit743166a36725
diff --git a/changelog.d/5003.bugfix.md b/changelog.d/5003.bugfix.md
new file mode 100644
index 0000000000..ed7b035bed
--- /dev/null
+++ b/changelog.d/5003.bugfix.md
@@ -0,0 +1 @@
+Fixed the shared byte-size formatter returning `"NaN undefined"` for negative, `NaN`, or undefined inputs; only finite `number` values are formatted now, and everything else -- including negative, non-finite, and numeric-string inputs like `"1024"` -- renders as `"0 Bytes"`.
diff --git a/src/local_deep_research/web/static/js/collection_details.js b/src/local_deep_research/web/static/js/collection_details.js
index 21fd7febe9..5a1cc10c3b 100644
--- a/src/local_deep_research/web/static/js/collection_details.js
+++ b/src/local_deep_research/web/static/js/collection_details.js
@@ -419,7 +419,7 @@ function renderDocuments() {
${doc.in_other_collections ? `<i class="fas fa-link" style="color: var(--accent-primary); margin-left: 8px;" title="In ${escapeHtml(String(doc.other_collections_count + 1))} collections"></i>` : ''}
</div>
<div class="ldr-document-meta">
- ${doc.file_size ? `Size: ${formatBytes(doc.file_size)} • ` : ''}
+ ${doc.file_size ? `Size: ${window.formatBytes(doc.file_size)} • ` : ''}
${doc.source_type && doc.source_type !== 'unknown' ? `<span class="ldr-badge ldr-badge-info">${escapeHtml(doc.source_type.replace('_', ' '))}</span> • ` : ''}
${doc.indexed ?
`<span class="ldr-badge ldr-badge-success">Indexed (${escapeHtml(String(doc.chunk_count))} chunks)</span>` :
@@ -867,17 +867,6 @@ async function deleteCollection() {
}
}
-/**
- * Format bytes to human readable
- */
-function formatBytes(bytes) {
- if (bytes === 0) return '0 B';
- const k = 1024;
- const sizes = ['B', 'KB', 'MB', 'GB'];
- const i = Math.floor(Math.log(bytes) / Math.log(k));
- return Math.round(bytes / k ** i * 100) / 100 + ' ' + sizes[i];
-}
-
/**
* Show success message
*/
diff --git a/src/local_deep_research/web/static/js/deletion/delete_manager.js b/src/local_deep_research/web/static/js/deletion/delete_manager.js
index c74c5c1e3d..9c69815d6d 100644
--- a/src/local_deep_research/web/static/js/deletion/delete_manager.js
+++ b/src/local_deep_research/web/static/js/deletion/delete_manager.js
@@ -62,10 +62,22 @@ async function postRequest(url, body) {
* Delegates to the shared window.formatBytes (utils/format-bytes.js, loaded
* globally in base.html). Kept as a thin local wrapper so the internal call
* sites and the DeleteManager.formatBytes export stay unchanged.
+ *
+ * `const` (not `function`) is deliberate: this file is a classic
+ * (non-module) script, and window.formatBytes is a plain property --
+ * whichever classic script assigns it LAST owns it. A top-level `function
+ * formatBytes` declaration would join that race (classic-script function
+ * declarations create a window property too): if this file ever loaded
+ * from a component_scripts/page_scripts block instead -- base.html
+ * renders those AFTER its own shared deferred scripts, including
+ * format-bytes.js -- that declaration would run after format-bytes.js and
+ * bind window.formatBytes to a wrapper that calls itself, recursing
+ * forever the first time anything invoked it. A top-level `const` only
+ * creates a lexical binding scoped to this script; it never touches
+ * window.formatBytes, so this file is removed from that race entirely and
+ * script order stops mattering.
*/
-function formatBytes(bytes) {
- return window.formatBytes(bytes);
-}
+const formatBytes = (bytes) => window.formatBytes(bytes);
// =============================================================================
// Document Operations
diff --git a/src/local_deep_research/web/static/js/utils/format-bytes.js b/src/local_deep_research/web/static/js/utils/format-bytes.js
index 35ec7f5643..3feb07dda6 100644
--- a/src/local_deep_research/web/static/js/utils/format-bytes.js
+++ b/src/local_deep_research/web/static/js/utils/format-bytes.js
@@ -15,7 +15,13 @@
* @returns {string} e.g. "0 Bytes", "1.5 KB", "1 MB".
*/
function formatBytes(bytes) {
- if (bytes === 0) return '0 Bytes';
+ // Covers 0, negatives, NaN, undefined, and null. Relational
+ // comparison coerces null to 0 and undefined to NaN.
+ // Without it, Math.log(-1) is NaN, which propagates through the
+ // clamp and yields "NaN undefined". Number.isFinite additionally
+ // rejects Infinity, which the relational check lets through and
+ // the unit clamp would render as "Infinity EB".
+ if (!(bytes > 0) || !Number.isFinite(bytes)) return '0 Bytes';
const k = 1024;
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB'];
// Clamp both ends: the upper bound stops indexing past the unit list
diff --git a/src/local_deep_research/web/templates/base.html b/src/local_deep_research/web/templates/base.html
index cc60439f94..cd3d998718 100644
--- a/src/local_deep_research/web/templates/base.html
+++ b/src/local_deep_research/web/templates/base.html
@@ -256,7 +256,14 @@
IMPORTANT: ui.js defines the global `escapeHtmlFallback` constant.
All subsequent scripts can reference it directly. Do NOT redeclare
escapeHtmlFallback at top-level in any other script — it will cause
- a SyntaxError and crash the page. See the comment in ui.js. -->
+ a SyntaxError and crash the page. See the comment in ui.js.
+
+ deletion/delete_manager.js (loaded by collection_details.html and
+ library.html) similarly declares a top-level `const formatBytes`
+ wrapping the shared utils/format-bytes.js global. On those pages,
+ do NOT redeclare formatBytes at top-level in any other script
+ either — same SyntaxError, same crash. See the comment in
+ delete_manager.js. -->
<script defer src="/static/js/services/theme.js"></script>
<script defer src="/static/js/services/formatting.js"></script>
<script defer src="/static/js/services/ui.js"></script>
diff --git a/tests/js/collection-details-direct-runtime.test.js b/tests/js/collection-details-direct-runtime.test.js
index c47e17ff92..cb9c8cf559 100644
--- a/tests/js/collection-details-direct-runtime.test.js
+++ b/tests/js/collection-details-direct-runtime.test.js
@@ -252,6 +252,11 @@ it('hydrates collection content and searches indexed members through real listen
const documents = document.getElementById('documents-list');
expect(documents.textContent).toContain(payload.documents[0].filename);
expect(documents.textContent).toContain('2 KB');
+ // Non-vacuousness guard: querySelector('img') below would also return
+ // null on a silently-empty (crashed/unrendered) list, which would let
+ // the XSS check "pass" without actually exercising the escaper. Pin
+ // that the document item actually rendered before trusting the negative.
+ expect(documents.children.length).toBeGreaterThan(0);
expect(documents.querySelector('img')).toBeNull();
expect(documents.querySelector('a').getAttribute('href'))
.toBe('/library/document/doc%2Findexed');
diff --git a/tests/js/collection-details.test.js b/tests/js/collection-details.test.js
index 6c1ed12ebb..73b0b9f64d 100644
--- a/tests/js/collection-details.test.js
+++ b/tests/js/collection-details.test.js
@@ -1,8 +1,11 @@
/**
- * Tests for collection_details.js — getProviderLabel + indexing-failure UI.
+ * Tests for collection_details.js — provider labels, document rendering,
+ * and indexing-failure UI.
*
* Covers:
* - getProviderLabel (pure helper, public mapping)
+ * - document size rendering (shared byte formatter, no local classic-script
+ * global shadow)
* - renderIndexingFailure (trims trailing period, uses textContent)
* - hideProgressUI (auto-hides after 5s when keepVisible=false,
* stays visible when keepVisible=true)
@@ -60,6 +63,8 @@ beforeAll(async () => {
Promise.resolve({ ok: true, json: () => Promise.resolve({}) })
);
+ await import('@js/utils/format-bytes.js');
+
// RESEARCH_STATUS / RESEARCH_TERMINAL_STATES are normally injected
// from Python via base.html. Provide stubs so the constants module's
// ``window.ResearchStates`` is fully functional.
@@ -116,6 +121,81 @@ describe('getProviderLabel', () => {
});
});
+describe('document size rendering', () => {
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ document.body.replaceChildren();
+ });
+
+ it('renders a 1 TB document with the shared formatter', async () => {
+ document.body.innerHTML = `
+ <button id="index-collection-btn"></button>
+ <button id="reindex-collection-btn"></button>
+ <button id="delete-collection-btn"></button>
+ <button id="cancel-indexing-btn"></button>
+ <input id="collection-is-public" type="checkbox">
+ <input id="collection-agent-enabled" type="checkbox">
+ <div id="collection-name"></div>
+ <div id="collection-description"></div>
+ <div id="stat-total-docs"></div>
+ <div id="stat-indexed-docs"></div>
+ <div id="stat-unindexed-docs"></div>
+ <div id="stat-total-chunks"></div>
+ <div id="collection-embedding-info"></div>
+ <div id="documents-list"></div>
+ <div id="no-documents-message"></div>
+ <div id="notes-section"></div>
+ <div id="notes-list"></div>
+ <div id="collection-search-section"></div>
+ `;
+
+ vi.stubGlobal('COLLECTION_ID', 'test-collection');
+ vi.stubGlobal('URLS', {
+ LIBRARY_API: {
+ COLLECTION_DOCUMENTS: '/library/api/collections/documents',
+ },
+ });
+ vi.stubGlobal('URLBuilder', {
+ build: (path, collectionId) => `${path}/${collectionId}`,
+ });
+ vi.stubGlobal('escapeHtml', value => String(value));
+ vi.stubGlobal('safeFetch', vi.fn(url => Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve(
+ url.endsWith('/index/status')
+ ? { status: 'idle' }
+ : {
+ success: true,
+ collection: {
+ name: 'Large files',
+ description: '',
+ embedding_model: null,
+ is_protected: false,
+ },
+ documents: [{
+ id: 'large-document',
+ filename: 'large.bin',
+ file_size: 1024 ** 4,
+ indexed: false,
+ chunk_count: 0,
+ has_pdf: false,
+ has_text_db: false,
+ in_other_collections: false,
+ }],
+ notes: [],
+ }
+ ),
+ })));
+
+ document.dispatchEvent(new Event('DOMContentLoaded'));
+
+ await vi.waitFor(() => {
+ expect(document.getElementById('documents-list').textContent)
+ .toContain('Size: 1 TB');
+ });
+ });
+});
+
describe('renderIndexingFailure', () => {
beforeEach(() => {
document.body.innerHTML = '';
diff --git a/tests/js/setup.js b/tests/js/setup.js
index ddb543f92c..995b91d3b2 100644
--- a/tests/js/setup.js
+++ b/tests/js/setup.js
@@ -52,6 +52,20 @@ import '@js/components/notes_shared.js';
// need a custom buildTieredResults still reassign window.SemanticSearch.
import '@js/components/semantic_search.js';
+// Shared byte-size formatter (window.formatBytes) — in production,
+// collection_details.js and delete_manager.js are emitted from
+// {% block content %}, which base.html renders BEFORE its own shared
+// deferred scripts, including utils/format-bytes.js (~line 286); see
+// tests/web/test_template_script_placement.py for the documented
+// ordering model. That's not a problem: both consumers only call
+// window.formatBytes from inside event handlers, after the document (and
+// every deferred script) has finished loading, never at their own
+// top-level script-evaluation time — so every page has it available by
+// the time handlers run, regardless of script order. Load it here so
+// every test gets that same guarantee instead of each consumer's test
+// file importing it individually.
+import '@js/utils/format-bytes.js';
+
// Auth-aware fetch wrapper (security/safe-fetch.js). In production it wraps
// safeFetch and redirects to /auth/login on a 401; page/component scripts call
// it instead of safeFetch. In tests we delegate to whatever safeFetch mock the
diff --git a/tests/js/utils/format-bytes.test.js b/tests/js/utils/format-bytes.test.js
index 6253323305..ff3959af9d 100644
--- a/tests/js/utils/format-bytes.test.js
+++ b/tests/js/utils/format-bytes.test.js
@@ -56,4 +56,17 @@ describe('formatBytes', () => {
// log(bytes) < 0 for bytes < 1 would give a negative index -> undefined.
expect(formatBytes(0.5)).toBe('0.5 Bytes');
});
+
+ it('returns "0 Bytes" for non-positive / non-finite inputs', () => {
+ // Math.log(-1) is NaN, which propagates through the clamp and would
+ // otherwise yield "NaN undefined". The guard short-circuits this.
+ // Infinity passes the relational check but would clamp to "Infinity EB".
+ expect(formatBytes(-1)).toBe('0 Bytes');
+ expect(formatBytes(-1024)).toBe('0 Bytes');
+ expect(formatBytes(NaN)).toBe('0 Bytes');
+ expect(formatBytes(Number.POSITIVE_INFINITY)).toBe('0 Bytes');
+ expect(formatBytes(Number.NEGATIVE_INFINITY)).toBe('0 Bytes');
+ expect(formatBytes(undefined)).toBe('0 Bytes');
+ expect(formatBytes(null)).toBe('0 Bytes');
+ });
});
diff --git a/tests/web/test_collection_details_script_contracts.py b/tests/web/test_collection_details_script_contracts.py
new file mode 100644
index 0000000000..6f40b318a5
--- /dev/null
+++ b/tests/web/test_collection_details_script_contracts.py
@@ -0,0 +1,53 @@
+"""Static contracts for collection-details classic-script globals."""
+
+import re
+from pathlib import Path
+
+import local_deep_research
+
+
+_COLLECTION_DETAILS_JS = (
+ Path(local_deep_research.__file__).parent
+ / "web"
+ / "static"
+ / "js"
+ / "collection_details.js"
+)
+
+# ^-anchored, like test_notes_js_global_shadowing.py's _DECL_RE: only a
+# top-level (column-0) declaration in a classic (non-module) script creates
+# or shadows a global, so only those forms matter here. Narrowed to one
+# name (formatBytes) and kept as its own check here -- rather than folded
+# into that file's full base.html-shared-script sweep -- because that
+# sweep is keyed on every top-level name in this file, and today it would
+# also have to reconcile this file's unrelated, pre-existing top-level
+# `showError` against services/ui.js's own `showError` (a real but
+# separate, out-of-scope collision).
+_LOCAL_FORMAT_BYTES_DECL = re.compile(
+ r"^(?:async\s+)?function\s+formatBytes\b"
+ r"|^(?:let|var|const)\s+formatBytes\b"
+ r"|^class\s+formatBytes\b",
+ re.MULTILINE,
+)
+# The call site should reach the shared global; tolerate whatever argument
+# expression it's called with (e.g. `doc.file_size`, `doc.file_size || 0`).
+_SHARED_FORMAT_BYTES_CALL = re.compile(r"window\.formatBytes\(")
+
+
+def test_collection_details_does_not_shadow_shared_format_bytes():
+ """collection_details.js must not declare its own top-level formatBytes.
+
+ deletion/delete_manager.js is loaded earlier on this same page
+ (collection_details.html) and declares a top-level `const formatBytes`
+ wrapping the shared window.formatBytes. Classic (non-module) scripts
+ loaded on one page share a global lexical scope for top-level
+ let/const/class/function declarations, so a second top-level
+ formatBytes declaration here -- in any of those forms -- is no longer
+ a harmless overwrite. It is a fatal
+ `SyntaxError: Identifier 'formatBytes' has already been declared`,
+ and this whole script fails to run, not just the duplicate name.
+ """
+ source = _COLLECTION_DETAILS_JS.read_text(encoding="utf-8")
+
+ assert not _LOCAL_FORMAT_BYTES_DECL.search(source)
+ assert _SHARED_FORMAT_BYTES_CALL.search(source)
diff --git a/tests/web/test_notes_js_global_shadowing.py b/tests/web/test_notes_js_global_shadowing.py
index 9e9fe86a4d..7f67c6b698 100644
--- a/tests/web/test_notes_js_global_shadowing.py
+++ b/tests/web/test_notes_js_global_shadowing.py
@@ -44,10 +44,26 @@ _DECL_RE = re.compile(
re.MULTILINE,
)
-# The notes page scripts that had the collisions.
+# The notes page scripts that had the collisions, plus other classic
+# (non-module) page scripts that declare a top-level name of their own and
+# must not collide with one of the base.html-shared scripts' top-level
+# names: delete_manager.js declares a top-level `const formatBytes`
+# wrapping the shared window.formatBytes (see the comment there) -- a
+# same-named top-level declaration later added to a base.html-shared
+# script would crash with SyntaxError, not silently shadow it.
+#
+# collection_details.js is deliberately NOT in this list: it is also
+# loaded on every page that loads delete_manager.js, but this file's
+# shared_names sweep is keyed on top-level names, and collection_details.js
+# already has an unrelated, pre-existing top-level `showError` that
+# collides with services/ui.js's own `showError` -- a real bug, but not
+# one this list exists to catch. See
+# test_collection_details_script_contracts.py for its (narrower)
+# formatBytes-only guard.
_NOTES_PAGE_SCRIPTS = [
"js/pages/note-detail.js",
"js/pages/notes.js",
+ "js/deletion/delete_manager.js",
]