Skip to content

fix(utils): formatBytes returns NaN undefined and invalid units for negative, sub-1, or non-finite inputs #1446

Description

@hsusul

Affected Component

src/utils/formatBytes.ts

User Impact

When displaying download progress, cache sizes, or file size measurements in the UI (e.g. progress bars, settings panels, model downloads), negative byte values, non-finite values (like NaN), or sub-1 byte values cause formatBytes to return invalid strings such as "NaN undefined" or "512 undefined".

Exact Reproduction

import { formatBytes } from "./src/utils/formatBytes.ts";

formatBytes(-100); // returns "NaN undefined"
formatBytes(0.5);  // returns "512 undefined"
formatBytes(NaN);  // returns "NaN undefined"

Actual Behavior

  • formatBytes(-100) returns "NaN undefined"
  • formatBytes(0.5) returns "512 undefined"
  • formatBytes(NaN) returns "NaN undefined"

Expected Behavior

  • formatBytes should validate that inputs are positive finite numbers (!Number.isFinite(bytes) || bytes <= 0 returns "0 Bytes").
  • Sub-kilobyte fractional values (0 < bytes < 1024) should format cleanly under the "Bytes" unit (e.g., "0.5 Bytes").
  • The calculated index i should be clamped safely within array bounds [0, sizes.length - 1].

Root Cause

formatBytes only checks bytes === 0 and calculates the log index i = Math.floor(Math.log(bytes) / Math.log(k)). For bytes <= 0 or non-finite inputs, Math.log returns NaN. For 0 < bytes < 1, Math.log is negative so i becomes -1. In both cases, sizes[i] evaluates to undefined.

Proposed Scope

Update formatBytes in src/utils/formatBytes.ts to validate inputs and clamp the unit index, and add unit tests covering these boundary conditions in test/helpers/formatBytes.test.js.

I intend to work on this issue and open a pull request.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions