From 1541d8a4b28d25738d30f1f58d3171740a1e5876 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?LLM=E4=B8=9A=E5=8A=A1=E6=95=B0=E6=8D=AE=E4=B8=93=E5=AE=B6?= <266125204+alibababye@users.noreply.github.com> Date: Tue, 23 Jun 2026 01:26:37 +0800 Subject: [PATCH] fix: handle invalid byte sizes Guard byte formatting against invalid and sub-byte values so the UI does not render NaN or undefined units. --- frontend/src/lib/utils.test.ts | 20 ++++++++++++++++++++ frontend/src/lib/utils.ts | 4 ++-- frontend/src/test/setup.ts | 1 + 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 frontend/src/lib/utils.test.ts create mode 100644 frontend/src/test/setup.ts diff --git a/frontend/src/lib/utils.test.ts b/frontend/src/lib/utils.test.ts new file mode 100644 index 0000000..6cabae1 --- /dev/null +++ b/frontend/src/lib/utils.test.ts @@ -0,0 +1,20 @@ +import { describe, expect, it } from 'vitest' + +import { formatBytes } from './utils' + +describe('formatBytes', () => { + it('formats zero and whole-byte values', () => { + expect(formatBytes(0)).toBe('0 B') + expect(formatBytes(512)).toBe('512.0 B') + }) + + it('keeps fractional bytes in the byte unit', () => { + expect(formatBytes(0.5)).toBe('0.5 B') + }) + + it('handles invalid sizes without rendering undefined units', () => { + expect(formatBytes(-1)).toBe('0 B') + expect(formatBytes(Number.NaN)).toBe('0 B') + expect(formatBytes(Number.POSITIVE_INFINITY)).toBe('0 B') + }) +}) diff --git a/frontend/src/lib/utils.ts b/frontend/src/lib/utils.ts index 502c33a..8c2ca65 100644 --- a/frontend/src/lib/utils.ts +++ b/frontend/src/lib/utils.ts @@ -20,10 +20,10 @@ export function formatDuration(seconds: number): string { } export function formatBytes(bytes: number): string { - if (bytes === 0) return '0 B' + if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' const k = 1024 const sizes = ['B', 'KB', 'MB', 'GB', 'TB'] - const i = Math.floor(Math.log(bytes) / Math.log(k)) + const i = Math.min(Math.max(Math.floor(Math.log(bytes) / Math.log(k)), 0), sizes.length - 1) return `${(bytes / Math.pow(k, i)).toFixed(1)} ${sizes[i]}` } diff --git a/frontend/src/test/setup.ts b/frontend/src/test/setup.ts new file mode 100644 index 0000000..c44951a --- /dev/null +++ b/frontend/src/test/setup.ts @@ -0,0 +1 @@ +import '@testing-library/jest-dom'