Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion ui/src/api/chat/attachments.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { MAX_TOTAL_BYTES, isAllowedFile, mediaTypeOf, stageFiles, textLinks } from "./attachments";
import { MAX_TOTAL_BYTES, formatBytes, isAllowedFile, mediaTypeOf, stageFiles, textLinks } from "./attachments";

const sized = (name: string, type: string, size: number) =>
({ name, type, size }) as File;
Expand Down Expand Up @@ -103,3 +103,19 @@ describe("stageFiles", () => {
expect(stageFiles([], [sized("a.md", "", 10)]).error).toBeUndefined();
});
});

describe("formatBytes", () => {
it.each([
[0, "0 B"],
[1023, "1023 B"],
[1024, "1 KB"],
[1536, "1.5 KB"],
[1048524, "1023.9 KB"],
[1048525, "1 MB"],
[1048575, "1 MB"],
[1048576, "1 MB"],
[5 * 1024 * 1024, "5 MB"],
])("formats %d bytes as %s", (bytes, expected) => {
expect(formatBytes(bytes)).toBe(expected);
});
});
5 changes: 4 additions & 1 deletion ui/src/api/chat/attachments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,10 @@ export function fileNameFromUrl(url: string): string {

export function formatBytes(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${Number((bytes / 1024).toFixed(1))} KB`;
// Pick the unit after rounding: 1,048,525 bytes is 1023.95 KB, which
// rounds to "1024 KB" and should read as 1 MB.
const kb = Number((bytes / 1024).toFixed(1));
if (kb < 1024) return `${kb} KB`;
return `${Number((bytes / (1024 * 1024)).toFixed(1))} MB`;
}

Expand Down
Loading