Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
refactor: add formatBytes helper (#7982)
Mykhailof46148e77d4d
diff --git a/web-app/src/containers/ChatInput.tsx b/web-app/src/containers/ChatInput.tsxindex ea182b3ad..536666a3f 100644--- a/web-app/src/containers/ChatInput.tsx+++ b/web-app/src/containers/ChatInput.tsx@@ -1,5 +1,5 @@import TextareaAutosize from 'react-textarea-autosize'-import { cn } from '@/lib/utils'+import { cn, formatBytes } from '@/lib/utils'import { usePrompt } from '@/hooks/usePrompt'import { useThreads } from '@/hooks/useThreads'import { useCallback, useEffect, useMemo, useRef, useState, memo } from 'react'@@ -910,18 +910,6 @@ const ChatInput = memo(function ChatInput({}}- const formatBytes = (bytes?: number): string => {- if (!bytes || bytes <= 0) return ''- const units = ['B', 'KB', 'MB', 'GB']- let i = 0- let val = bytes- while (val >= 1024 && i < units.length - 1) {- val /= 1024- i++- }- return `${val.toFixed(i === 0 ? 0 : 1)} ${units[i]}`- }-const hashBase64 = async (base64: string): Promise<string> => {const binary = atob(base64)const bytes = new Uint8Array(binary.length)@@ -1517,7 +1505,10 @@ const ChatInput = memo(function ChatInput({? `.${ext}`: 'document'}{att.size- ? ` · ${formatBytes(att.size)}`+ ? ` · ${formatBytes(att.size, {+ decimals: (_, unit) =>+ unit === 'B' ? 0 : 1,+ })}`: ''}</div></div>diff --git a/web-app/src/containers/DownloadManegement.tsx b/web-app/src/containers/DownloadManegement.tsxindex edd79d23f..06a0bfa5e 100644--- a/web-app/src/containers/DownloadManegement.tsx+++ b/web-app/src/containers/DownloadManegement.tsx@@ -16,6 +16,7 @@ import { useNavigate } from '@tanstack/react-router'import { route } from '@/constants/routes'import { DownloadIcon } from 'lucide-react'import { Button } from '@/components/ui/button'+import { formatBytes } from '@/lib/utils'export function DownloadManagement() {const { t } = useTranslation()@@ -352,11 +353,6 @@ export function DownloadManagement() {onAppUpdateDownloadError,])- function renderGB(bytes: number): string {- const gb = bytes / 1024 ** 3- return ((gb * 100) / 100).toFixed(2)- }-return (<><Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>@@ -420,7 +416,15 @@ export function DownloadManagement() {%</p><p className="text-xs">- {`${renderGB(appUpdateState.downloadedBytes)} / ${renderGB(appUpdateState.totalBytes)}`}{' '}+ {`${formatBytes(appUpdateState.downloadedBytes, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: 2,+ })} / ${formatBytes(appUpdateState.totalBytes, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: 2,+ })}`}{' '}GB</p></div>@@ -438,34 +442,34 @@ export function DownloadManagement() {</p><div className="shrink-0 flex items-center space-x-0.5"><Button variant="secondary" size="icon-xs" onClick={() => {- // TODO: Consolidate cancellation logic- if (download.id.startsWith('llamacpp') || download.id.startsWith('mlx')) {- const downloadManager =- window.core.extensionManager.getByName(- '@janhq/download-extension'- )- downloadManager.cancelDownload(download.id)- } else {- serviceHub- .models()- .abortDownload(download.name)- .then(() => {- toast.info(- t('common:toast.downloadCancelled.title'),- {- id: 'cancel-download',- description: t(- 'common:toast.downloadCancelled.description'- ),- }- )- if (downloadProcesses.length === 0) {- setIsPopoverOpen(false)+ // TODO: Consolidate cancellation logic+ if (download.id.startsWith('llamacpp') || download.id.startsWith('mlx')) {+ const downloadManager =+ window.core.extensionManager.getByName(+ '@janhq/download-extension'+ )+ downloadManager.cancelDownload(download.id)+ } else {+ serviceHub+ .models()+ .abortDownload(download.name)+ .then(() => {+ toast.info(+ t('common:toast.downloadCancelled.title'),+ {+ id: 'cancel-download',+ description: t(+ 'common:toast.downloadCancelled.description'+ ),}- })- }- setIsPopoverOpen(false)- }} >+ )+ if (downloadProcesses.length === 0) {+ setIsPopoverOpen(false)+ }+ })+ }+ setIsPopoverOpen(false)+ }} ><IconXsize={16}className="text-muted-foreground cursor-pointer"@@ -489,10 +493,22 @@ export function DownloadManagement() {</p><p className="text-xs">{download.total > 0- ? `${renderGB(download.current)} / ${renderGB(download.total)} GB`- : download.current > 0- ? `${renderGB(download.current)} GB`- : ''}+ ? `${formatBytes(download.current, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: 2,+ })} / ${formatBytes(download.total, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: 2,+ })} GB`+ : download.current > 0 ?+ `${formatBytes(download.current, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: 2,+ })} GB` : ''+ }</p></div></div>@@ -500,7 +516,7 @@ export function DownloadManagement() {))}</div></>- ) : (+ ) : (<div className="px-3 py-8 flex flex-col items-center justify-center text-center space-y-2"><DownloadIcon className="text-muted-foreground/50 size-6" /><p className="text-muted-foreground leading-normal">diff --git a/web-app/src/containers/ProjectFiles.tsx b/web-app/src/containers/ProjectFiles.tsxindex a630382d9..d5852af28 100644--- a/web-app/src/containers/ProjectFiles.tsx+++ b/web-app/src/containers/ProjectFiles.tsx@@ -8,7 +8,7 @@ import {TooltipContent,TooltipTrigger,} from '@/components/ui/tooltip'-import { cn } from '@/lib/utils'+import { cn, formatBytes } from '@/lib/utils'import { toast } from 'sonner'import { useServiceHub } from '@/hooks/useServiceHub'import { createDocumentAttachment, type Attachment } from '@/types/attachment'@@ -31,18 +31,6 @@ type ProjectFile = {chunk_count: number}-function formatBytes(bytes?: number): string {- if (!bytes || bytes <= 0) return ''- const units = ['B', 'KB', 'MB', 'GB']- let i = 0- let val = bytes- while (val >= 1024 && i < units.length - 1) {- val /= 1024- i++- }- return `${val.toFixed(i === 0 ? 0 : 1)} ${units[i]}`-}-const SUPPORTED_EXTENSIONS = [// Documents'pdf',@@ -595,7 +583,11 @@ export default function ProjectFiles({ projectId, lng }: ProjectFilesProps) {</TooltipContent></Tooltip><p className="text-xs text-muted-foreground">- {file.size ? formatBytes(file.size) : ''}+ {file.size+ ? formatBytes(file.size, {+ decimals: (_, unit) => (unit === 'B' ? 0 : 1),+ })+ : ''}{file.chunk_count > 0 &&` · ${t('common:files.chunksCount', { count: file.chunk_count })}`}</p>diff --git a/web-app/src/containers/SetupScreen.tsx b/web-app/src/containers/SetupScreen.tsxindex 5df5a366f..186fc6bb8 100644--- a/web-app/src/containers/SetupScreen.tsx+++ b/web-app/src/containers/SetupScreen.tsx@@ -12,7 +12,7 @@ import { useLatestJanModel } from '@/hooks/useLatestJanModel'import { toast } from 'sonner'import { Button } from '@/components/ui/button'import { IconEye, IconSquareCheck } from '@tabler/icons-react'-import { cn } from '@/lib/utils'+import { cn, formatBytes } from '@/lib/utils'import { useGeneralSetting } from '@/hooks/useGeneralSetting'import HeaderPage from './HeaderPage'@@ -254,12 +254,6 @@ function SetupScreen() {}}, [defaultVariant, downloadProcesses])- const formatBytes = (bytes: number) => {- if (bytes === 0) return '0'- const gb = bytes / (1024 * 1024 * 1024)- return gb.toFixed(1)- }-const isDownloaded = useMemo(() => {if (!defaultVariant) return falsereturn llamaProvider?.models.some(@@ -461,7 +455,20 @@ function SetupScreen() {d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/></svg>- <span>{formatBytes(downloadedSize.current)} / {formatBytes(downloadedSize.total)}GB</span>+ <span>+ {formatBytes(downloadedSize.current, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: (value) => (value === 0 ? 0 : 1),+ })}{' '}+ /{' '}+ {formatBytes(downloadedSize.total, {+ hideUnit: true,+ minUnit: 'GB',+ decimals: (value) => (value === 0 ? 0 : 1),+ })}+ GB+ </span></div>)}diff --git a/web-app/src/containers/dialogs/AttachmentIngestionDialog.tsx b/web-app/src/containers/dialogs/AttachmentIngestionDialog.tsxindex 0d2ee2b19..bfc226d0c 100644--- a/web-app/src/containers/dialogs/AttachmentIngestionDialog.tsx+++ b/web-app/src/containers/dialogs/AttachmentIngestionDialog.tsx@@ -9,14 +9,7 @@ import {import { Button } from '@/components/ui/button'import { useAttachmentIngestionPrompt } from '@/hooks/useAttachmentIngestionPrompt'import { useTranslation } from '@/i18n'--const formatBytes = (bytes?: number) => {- if (!bytes || bytes <= 0) return ''- const units = ['B', 'KB', 'MB', 'GB']- const exponent = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), units.length - 1)- const value = bytes / Math.pow(1024, exponent)- return `${value.toFixed(value >= 10 || exponent === 0 ? 0 : 1)} ${units[exponent]}`-}+import { formatBytes } from '@/lib/utils'export default function AttachmentIngestionDialog() {const { t } = useTranslation()@@ -47,7 +40,12 @@ export default function AttachmentIngestionDialog() {{currentAttachment.name}</span><span className="text-xs text-muted-foreground shrink-0">- {formatBytes(currentAttachment.size)}+ {currentAttachment.size && currentAttachment.size > 0+ ? formatBytes(currentAttachment.size, {+ decimals: (value, unit) =>+ unit === 'B' || value >= 10 ? 0 : 1,+ })+ : ''}</span></div></div>diff --git a/web-app/src/lib/__tests__/utils.test.ts b/web-app/src/lib/__tests__/utils.test.tsindex e46437c8a..28640d36c 100644--- a/web-app/src/lib/__tests__/utils.test.ts+++ b/web-app/src/lib/__tests__/utils.test.ts@@ -4,6 +4,7 @@ import {getProviderTitle,getReadableLanguageName,toGigabytes,+ formatBytes,formatMegaBytes,formatDuration,getModelDisplayName,@@ -149,6 +150,80 @@ describe('formatMegaBytes', () => {})})+describe('formatBytes', () => {+ it('returns fallback for undefined or non-finite input', () => {+ expect(formatBytes(undefined)).toBe('')+ expect(formatBytes(undefined, { fallback: 'N/A' })).toBe('N/A')+ expect(formatBytes(Number.NaN, { fallback: '-' })).toBe('-')+ expect(formatBytes(Number.POSITIVE_INFINITY, { fallback: 'INF' })).toBe(+ 'INF'+ )+ })++ it('formats bytes with default options', () => {+ expect(formatBytes(0)).toBe('0.0 B')+ expect(formatBytes(512)).toBe('512.0 B')+ expect(formatBytes(1536)).toBe('1.5 KB')+ expect(formatBytes(1024 ** 2 * 2.25)).toBe('2.3 MB')+ expect(formatBytes(1024 ** 3 * 3)).toBe('3.0 GB')+ })++ it('uses 1024 boundaries for unit transitions', () => {+ expect(formatBytes(1023)).toBe('1023.0 B')+ expect(formatBytes(1024)).toBe('1.0 KB')+ expect(formatBytes(1024 ** 2)).toBe('1.0 MB')+ expect(formatBytes(1024 ** 3)).toBe('1.0 GB')+ })++ it('supports numeric decimals option', () => {+ expect(formatBytes(1536, { decimals: 2 })).toBe('1.50 KB')+ expect(formatBytes(1536, { decimals: 0 })).toBe('2 KB')+ expect(formatBytes(1536, { decimals: 3 })).toBe('1.500 KB')+ })++ it('clamps and truncates decimal precision into toFixed range', () => {+ expect(formatBytes(1536, { decimals: -5 })).toBe('2 KB')+ expect(formatBytes(1536, { decimals: 2.9 })).toBe('1.50 KB')+ expect(formatBytes(1536, { decimals: 999 })).toBe(+ '1.50000000000000000000 KB'+ )+ })++ it('supports function-based decimals per unit', () => {+ const decimals = vi.fn((value: number, unit: 'B' | 'KB' | 'MB' | 'GB') => {+ if (unit === 'B') return 0+ if (unit === 'KB') return value < 2 ? 3 : 1+ if (unit === 'MB') return 2+ return 4+ })++ expect(formatBytes(900, { decimals })).toBe('900 B')+ expect(formatBytes(1536, { decimals })).toBe('1.500 KB')+ expect(formatBytes(4096, { decimals })).toBe('4.0 KB')+ expect(formatBytes(1024 ** 2 * 1.25, { decimals })).toBe('1.25 MB')+ expect(formatBytes(1024 ** 3 * 1.5, { decimals })).toBe('1.5000 GB')+ expect(decimals).toHaveBeenCalledTimes(5)+ })++ it('supports separator and hideUnit options', () => {+ expect(formatBytes(1536, { separator: '' })).toBe('1.5KB')+ expect(formatBytes(1536, { separator: ' - ' })).toBe('1.5 - KB')+ expect(formatBytes(1536, { hideUnit: true })).toBe('1.5')+ expect(formatBytes(1536, { hideUnit: true, separator: ' / ' })).toBe('1.5')+ })++ it('honors minUnit floor', () => {+ expect(formatBytes(1, { minUnit: 'KB', decimals: 4 })).toBe('0.0010 KB')+ expect(formatBytes(1024, { minUnit: 'MB', decimals: 4 })).toBe('0.0010 MB')+ expect(formatBytes(1024 ** 2, { minUnit: 'GB', decimals: 4 })).toBe(+ '0.0010 GB'+ )+ expect(formatBytes(1024 ** 2 * 2, { minUnit: 'KB', decimals: 2 })).toBe(+ '2.00 MB'+ )+ })+})+describe('formatDuration', () => {it('formats milliseconds when duration is less than 1 second', () => {const start = Date.now()diff --git a/web-app/src/lib/utils.ts b/web-app/src/lib/utils.tsindex d4d269cc4..60accfd07 100644--- a/web-app/src/lib/utils.ts+++ b/web-app/src/lib/utils.ts@@ -200,6 +200,59 @@ export const toGigabytes = (}}+export type ByteUnit = 'B' | 'KB' | 'MB' | 'GB'++export type FormatBytesOptions = {+ decimals?: number | ((value: number, unit: ByteUnit) => number)+ separator?: string+ hideUnit?: boolean+ minUnit?: ByteUnit+ fallback?: string+}++const BYTE_UNITS: ByteUnit[] = ['B', 'KB', 'MB', 'GB']++export function formatBytes(+ bytes: number | undefined,+ options?: FormatBytesOptions+): string {+ const fallback = options?.fallback ?? ''++ if (bytes === undefined || !Number.isFinite(bytes)) {+ return fallback+ }++ const minUnitIndex =+ options?.minUnit === undefined ? 0 : BYTE_UNITS.indexOf(options.minUnit)++ let unitIndex = 0+ let scaledValue = bytes++ while (scaledValue >= 1024 && unitIndex < BYTE_UNITS.length - 1) {+ scaledValue /= 1024+ unitIndex+++ }++ while (unitIndex < minUnitIndex) {+ scaledValue /= 1024+ unitIndex+++ }++ const unit = BYTE_UNITS[unitIndex]+ const rawDecimals =+ typeof options?.decimals === 'function'+ ? options.decimals(scaledValue, unit)+ : options?.decimals ?? 1+ const decimals = Math.min(20, Math.max(0, Math.trunc(rawDecimals)))+ const formattedValue = scaledValue.toFixed(decimals)++ if (options?.hideUnit) {+ return formattedValue+ }++ return `${formattedValue}${options?.separator ?? ' '}${unit}`+}+export function formatMegaBytes(mb: number) {const tb = mb / (1024 * 1024)if (tb >= 1) {diff --git a/web-app/src/routes/settings/claude-code.tsx b/web-app/src/routes/settings/claude-code.tsxindex 8b2dc5d59..8002d8e34 100644--- a/web-app/src/routes/settings/claude-code.tsx+++ b/web-app/src/routes/settings/claude-code.tsx@@ -28,7 +28,7 @@ import {import { IconChevronDown, IconPlus, IconX } from '@tabler/icons-react'import ProvidersAvatar from '@/containers/ProvidersAvatar'import Capabilities from '@/containers/Capabilities'-import { getModelDisplayName, isLocalProvider } from '@/lib/utils'+import { formatBytes, getModelDisplayName, isLocalProvider } from '@/lib/utils'// eslint-disable-next-line @typescript-eslint/no-explicit-anyexport const Route = createFileRoute(route.settings.claude_code as any)({@@ -634,11 +634,6 @@ function JanCodeRecommendation({)}- const formatBytes = (bytes: number) => {- if (!bytes) return '0'- return (bytes / (1024 * 1024 * 1024)).toFixed(1)- }-if (selectedModel === defaultVariant?.model_id) return nullreturn (@@ -679,8 +674,16 @@ function JanCodeRecommendation({/></svg><span>- {formatBytes(downloadProgress.current)} /{' '}- {formatBytes(downloadProgress.total)}GB+ {formatBytes(downloadProgress.current, {+ hideUnit: true,+ minUnit: 'GB',+ })}{' '}+ /{' '}+ {formatBytes(downloadProgress.total, {+ hideUnit: true,+ minUnit: 'GB',+ })}+ GB</span></div>) : (