Skip to content

A full-featured download manager.

feat(settings): add persistent speed limit unit selectors (#2362)

Dr_rOot9693bd9a8c64
diff --git a/.github/pr-assets/speed-limit-units.png b/.github/pr-assets/speed-limit-units.png
new file mode 100644
index 00000000..a43d0cb5
Binary files /dev/null and b/.github/pr-assets/speed-limit-units.png differ
diff --git a/e2e/settings-speed-limit-units.spec.ts b/e2e/settings-speed-limit-units.spec.ts
new file mode 100644
index 00000000..68c723a1
--- /dev/null
+++ b/e2e/settings-speed-limit-units.spec.ts
@@ -0,0 +1,146 @@
+import { Commands } from '@shared/protocol/commands'
+import { Queries } from '@shared/protocol/queries'
+import type { AppSettings } from '@shared/types/settings'
+import { expect, test, waitForEngineReady } from './fixtures/electron-app'
+
+for (const system of ['decimal', 'binary'] as const) {
+ test(`speed limit units preserve bytes and save fractional ${system} limits`, async ({
+ mainWindow: page,
+ }, testInfo) => {
+ await waitForEngineReady(page)
+ const kilo = system === 'binary' ? 1024 : 1000
+ const mega = kilo ** 2
+ const megaUnit = system === 'binary' ? 'MiB/s' : 'MB/s'
+ const original = 2 * mega + 1
+ await page.evaluate(
+ async ({ channel, units, download }) => {
+ await window.motrix.invoke(channel, {
+ app: { byteUnitSystem: units },
+ speedLimit: {
+ base: { download, upload: 0 },
+ alt: { download: 0 },
+ },
+ })
+ },
+ { channel: Commands.UpdateSettings, units: system, download: original }
+ )
+ await page.reload({ waitUntil: 'domcontentloaded' })
+ const read = () =>
+ page.evaluate(
+ async (channel) => (await window.motrix.invoke(channel)) as AppSettings,
+ Queries.GetSettings
+ )
+ const before = await read()
+ const open = async () => {
+ await page.getByRole('link', { name: 'Settings', exact: true }).click()
+ await page.getByRole('button', { name: /^downloads Downloads / }).click()
+ await expect(
+ page.getByRole('button', { name: 'Save', exact: true })
+ ).toBeEnabled()
+ }
+ const chooseMega = async (field: string) => {
+ const select = page.getByRole('combobox', { name: `Unit for ${field}` })
+ await select.click()
+ await page.getByRole('option', { name: megaUnit, exact: true }).click()
+ await expect(select).toHaveText(megaUnit)
+ await expect(page.getByRole('listbox')).toHaveCount(0)
+ const text = select.locator('[data-slot="select-value"]')
+ expect(
+ await text.evaluate(
+ (element) => element.scrollWidth <= element.clientWidth
+ )
+ ).toBe(true)
+ }
+ const download = page.getByRole('spinbutton', {
+ name: 'Download — Standard limits',
+ })
+ const upload = page.getByRole('spinbutton', {
+ name: 'Upload — Standard limits',
+ })
+ const lowDownload = page.getByRole('spinbutton', {
+ name: 'Download — Low speed limits',
+ })
+
+ await open()
+ await chooseMega('Download (Standard limits)')
+ await expect(download).toHaveValue('2.000001')
+ await chooseMega('Upload (Standard limits)')
+ await expect(upload).toHaveValue('')
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(page.getByRole('dialog')).toHaveCount(0)
+ expect((await read()).speedLimit).toEqual(before.speedLimit)
+ expect((await read()).app.speedLimitUnits).toMatchObject({
+ baseDownload: 'mega',
+ baseUpload: 'mega',
+ })
+
+ await page.reload({ waitUntil: 'domcontentloaded' })
+ await open()
+ await expect(
+ page.getByRole('combobox', { name: 'Unit for Upload (Standard limits)' })
+ ).toHaveText(megaUnit)
+ await expect(
+ page.getByRole('combobox', {
+ name: 'Unit for Download (Standard limits)',
+ })
+ ).toHaveText(megaUnit)
+ await expect(download).toHaveValue('2.000001')
+ await expect(upload).toHaveValue('')
+ await expect(upload).toHaveAttribute('placeholder', 'Unlimited')
+ await upload.pressSequentially('1.1')
+ await expect(upload).toHaveValue('1.1')
+ await chooseMega('Download (Low speed limits)')
+ await expect(lowDownload).toHaveAttribute('placeholder', 'Use standard')
+ await lowDownload.fill('2.5')
+ const lowGroup = lowDownload.locator(
+ 'xpath=ancestor::*[@data-slot="button-group"]'
+ )
+ await lowGroup.getByRole('button', { name: 'Use standard limit' }).click()
+ await expect(lowGroup.getByRole('combobox')).toHaveText(megaUnit)
+ await expect(lowDownload).toHaveValue('')
+ await page
+ .getByRole('heading', { name: 'Speed limits', exact: true })
+ .hover()
+ await expect(page.getByRole('tooltip')).toHaveCount(0)
+ await page.screenshot({
+ path: testInfo.outputPath(`speed-limit-units-${system}.png`),
+ })
+ expect((await read()).speedLimit).toEqual(before.speedLimit)
+ await page.getByRole('button', { name: 'Save', exact: true }).click()
+ await expect(page.getByRole('dialog')).toHaveCount(0)
+ const saved = await read()
+ expect(saved.speedLimit.base).toEqual({
+ download: original,
+ upload: Math.round(1.1 * mega),
+ })
+ expect(saved.speedLimit.alt.download).toBe(0)
+ expect(saved.app.speedLimitUnits.altDownload).toBe('mega')
+ expect(saved.speedLimit.alt.upload).toBe(before.speedLimit.alt.upload)
+
+ await open()
+ await expect(lowGroup.getByRole('combobox')).toHaveText(megaUnit)
+ await expect(lowDownload).toHaveValue('')
+ await expect(upload).toHaveValue('1.1')
+ await page
+ .getByRole('combobox', { name: 'Unit for Upload (Standard limits)' })
+ .click()
+ await page
+ .getByRole('option', {
+ name: system === 'binary' ? 'KiB/s' : 'KB/s',
+ exact: true,
+ })
+ .click()
+ await expect(page.getByRole('listbox')).toHaveCount(0)
+ await upload.fill('42')
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click()
+ expect((await read()).speedLimit).toEqual(saved.speedLimit)
+ expect((await read()).app.speedLimitUnits).toEqual(
+ saved.app.speedLimitUnits
+ )
+ await open()
+ await expect(
+ page.getByRole('combobox', { name: 'Unit for Upload (Standard limits)' })
+ ).toHaveText(megaUnit)
+ await expect(upload).toHaveValue('1.1')
+ })
+}
diff --git a/src/core/settings/downloads-settings.test.ts b/src/core/settings/downloads-settings.test.ts
index 16018b48..eaa981ec 100644
--- a/src/core/settings/downloads-settings.test.ts
+++ b/src/core/settings/downloads-settings.test.ts
@@ -31,6 +31,38 @@ async function fixture() {
return { root, file, change, manager, request }
}
describe('Downloads atomic settings save', () => {
+ it('persists independent unit preferences across reloads without changing byte limits', async () => {
+ const { manager, file, request } = await fixture()
+ const limits = structuredClone(manager.get().speedLimit)
+ const save = createSaveDownloadsSettingsHandler(manager)
+ expect(
+ await save({
+ ...request(),
+ settings: {
+ app: { speedLimitUnits: { baseUpload: 'mega', altDownload: 'mega' } },
+ },
+ })
+ ).toMatchObject({ ok: true })
+ expect(
+ await save({
+ ...request(),
+ settings: { app: { speedLimitUnits: { baseDownload: 'mega' } } },
+ })
+ ).toMatchObject({ ok: true })
+ await manager.update({ app: { byteUnitSystem: 'binary' } })
+ const restored = new SettingsManager(file)
+ await restored.load()
+ expect(restored.getApp().speedLimitUnits).toEqual({
+ baseUpload: 'mega',
+ baseDownload: 'mega',
+ altUpload: 'kilo',
+ altDownload: 'mega',
+ })
+ expect(restored.get().speedLimit).toEqual(limits)
+ expect(
+ restored.getDownloadsSettingsSnapshot().settings.app.speedLimitUnits
+ ).toEqual(restored.getApp().speedLimitUnits)
+ })
it('durably commits folders, clipboard, performance and nested speed edits together', async () => {
const { root, file, change, manager, request } = await fixture()
const folder = path.join(root, 'downloads ')
@@ -152,6 +184,9 @@ describe('Downloads atomic settings save', () => {
{ speedLimit: { base: { download: undefined } } },
{ app: { runMode: 2 } },
{ engine: { split: 129 } },
+ { app: { speedLimitUnits: { baseUpload: 'GB' } } },
+ { app: { speedLimitUnits: { altDownload: undefined } } },
+ { app: { speedLimitUnits: { unknown: 'mega' } } },
])(
'rejects invalid or out-of-scope patches without changing state: %j',
async (settings) => {
diff --git a/src/core/settings/settings-manager.ts b/src/core/settings/settings-manager.ts
index d19cece2..231b1b32 100644
--- a/src/core/settings/settings-manager.ts
+++ b/src/core/settings/settings-manager.ts
@@ -620,6 +620,10 @@ export class SettingsManager {
const merged = {
...next.app,
...partial.app,
+ speedLimitUnits: {
+ ...next.app.speedLimitUnits,
+ ...partial.app.speedLimitUnits,
+ },
// Only dedicated queue actions can change this aggregate.
directoryPreferences: next.app.directoryPreferences,
}
diff --git a/src/renderer/routes/settings/cards/compact-limit-input.test.tsx b/src/renderer/routes/settings/cards/compact-limit-input.test.tsx
new file mode 100644
index 00000000..c2e6abee
--- /dev/null
+++ b/src/renderer/routes/settings/cards/compact-limit-input.test.tsx
@@ -0,0 +1,173 @@
+import '@test-utils/dom-animations'
+import '@testing-library/jest-dom/vitest'
+import { setByteUnitSystem } from '@renderer/hooks/use-byte-format'
+import { i18n } from '@renderer/lib/i18n'
+import type { SpeedLimitUnit } from '@shared/schemas/speed-limit-units'
+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { useState } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { CompactLimitInput } from './compact-limit-input'
+
+function Limit({
+ initialValue = 0,
+ onChange = vi.fn(),
+ inherit = false,
+}: {
+ initialValue?: number
+ onChange?: (value: number) => void
+ inherit?: boolean
+}) {
+ const [value, setValue] = useState(initialValue)
+ const [magnitude, setMagnitude] = useState<SpeedLimitUnit>('kilo')
+ return (
+ <CompactLimitInput
+ aria-label="Download limit"
+ value={value}
+ magnitude={magnitude}
+ onMagnitudeChange={setMagnitude}
+ onValueChange={(next) => {
+ setValue(next)
+ onChange(next)
+ }}
+ unitLabel="Download unit"
+ zeroLabel={inherit ? 'Use standard' : 'Unlimited'}
+ resetLabel={inherit ? 'Use standard limit' : 'Set unlimited'}
+ zeroAction={inherit ? 'inherit' : 'unlimited'}
+ />
+ )
+}
+
+async function chooseUnit(
+ user: ReturnType<typeof userEvent.setup>,
+ unit: string
+) {
+ await user.click(screen.getByRole('combobox', { name: 'Download unit' }))
+ await user.click(await screen.findByRole('option', { name: unit }))
+}
+
+beforeEach(async () => {
+ await i18n.changeLanguage('en-US')
+})
+
+afterEach(() => {
+ cleanup()
+ setByteUnitSystem('decimal')
+})
+
+describe('CompactLimitInput', () => {
+ it.each(['decimal', 'binary'] as const)(
+ 'preserves exact bytes through repeated %s unit switches',
+ async (system) => {
+ setByteUnitSystem(system)
+ const bytes = 1_234_567_891
+ const kilo = system === 'binary' ? 1024 : 1000
+ const units = system === 'binary' ? ['KiB/s', 'MiB/s'] : ['KB/s', 'MB/s']
+ const onChange = vi.fn()
+ render(<Limit initialValue={bytes} onChange={onChange} />)
+ const input = screen.getByRole('spinbutton')
+ const user = userEvent.setup()
+ for (let index = 0; index < 3; index++) {
+ await chooseUnit(user, units[1])
+ expect(input).toHaveValue(Number((bytes / kilo ** 2).toFixed(6)))
+ expect(input).toHaveAttribute(
+ 'aria-valuetext',
+ `${Number((bytes / kilo ** 2).toFixed(6))} ${units[1]}`
+ )
+ await chooseUnit(user, units[0])
+ expect(input).toHaveValue(Number((bytes / kilo).toFixed(3)))
+ }
+ expect(onChange).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each(['decimal', 'binary'] as const)(
+ 'preselects a %s unit while unlimited and accepts fractional input',
+ async (system) => {
+ setByteUnitSystem(system)
+ const mega = system === 'binary' ? 1024 ** 2 : 1000 ** 2
+ const unit = system === 'binary' ? 'MiB/s' : 'MB/s'
+ const onChange = vi.fn()
+ render(<Limit onChange={onChange} />)
+ const user = userEvent.setup()
+ const input = screen.getByRole('spinbutton')
+ await chooseUnit(user, unit)
+ expect(input).toHaveValue(null)
+ expect(input).toHaveAttribute('placeholder', 'Unlimited')
+ expect(onChange).not.toHaveBeenCalled()
+ await user.type(input, '1.1')
+ expect(input).toHaveValue(1.1)
+ expect(onChange).toHaveBeenLastCalledWith(Math.round(1.1 * mega))
+ await user.tab()
+ expect(input).toHaveValue(1.1)
+ expect(screen.getByRole('combobox')).toHaveTextContent(unit)
+ // A unit selection cannot feed the formatted number back into the model.
+ onChange.mockClear()
+ await chooseUnit(user, system === 'binary' ? 'KiB/s' : 'KB/s')
+ await chooseUnit(user, unit)
+ expect(onChange).not.toHaveBeenCalled()
+ }
+ )
+
+ it.each([false, true])(
+ 'keeps the selected unit after resetting (inherit=%s)',
+ async (inherit) => {
+ const onChange = vi.fn()
+ render(
+ <Limit initialValue={1_500_000} inherit={inherit} onChange={onChange} />
+ )
+ const user = userEvent.setup()
+ await chooseUnit(user, 'MB/s')
+ await user.click(
+ screen.getByRole('button', {
+ name: inherit ? 'Use standard limit' : 'Set unlimited',
+ })
+ )
+ expect(onChange).toHaveBeenLastCalledWith(0)
+ expect(screen.getByRole('combobox')).toHaveTextContent('MB/s')
+ const input = screen.getByRole('spinbutton')
+ expect(input).toHaveAttribute(
+ 'placeholder',
+ inherit ? 'Use standard' : 'Unlimited'
+ )
+ await user.type(input, '2.5')
+ expect(onChange).toHaveBeenLastCalledWith(2_500_000)
+ }
+ )
+
+ it('keeps the magnitude and actual limit when the unit system changes', async () => {
+ const onChange = vi.fn()
+ render(<Limit initialValue={1_048_576} onChange={onChange} />)
+ await chooseUnit(userEvent.setup(), 'MB/s')
+ act(() => setByteUnitSystem('binary'))
+ expect(screen.getByRole('spinbutton')).toHaveValue(1)
+ expect(screen.getByRole('combobox')).toHaveTextContent('MiB/s')
+ act(() => setByteUnitSystem('decimal'))
+ expect(screen.getByRole('spinbutton')).toHaveValue(1.048576)
+ expect(onChange).not.toHaveBeenCalled()
+ })
+
+ it('steps in the selected unit without changing units at a magnitude boundary', async () => {
+ const onChange = vi.fn()
+ render(<Limit initialValue={999_000_000} onChange={onChange} />)
+ await chooseUnit(userEvent.setup(), 'MB/s')
+ const input = screen.getByRole('spinbutton')
+ fireEvent.keyDown(input, { key: 'ArrowUp' })
+ expect(input).toHaveValue(1000)
+ expect(screen.getByRole('combobox')).toHaveTextContent('MB/s')
+ expect(onChange).toHaveBeenLastCalledWith(1_000_000_000)
+ fireEvent.keyDown(input, { key: 'ArrowDown' })
+ expect(onChange).toHaveBeenLastCalledWith(999_000_000)
+ })
+
+ it('does not turn tiny nonzero inputs into unlimited', async () => {
+ const onChange = vi.fn()
+ render(<Limit onChange={onChange} />)
+ await chooseUnit(userEvent.setup(), 'MB/s')
+ const input = screen.getByRole('spinbutton')
+ fireEvent.change(input, { target: { value: '0.0000001' } })
+ expect(onChange).toHaveBeenLastCalledWith(1)
+ fireEvent.change(input, { target: { value: '-0.0000001' } })
+ expect(onChange).toHaveBeenLastCalledWith(-1)
+ })
+})
diff --git a/src/renderer/routes/settings/cards/compact-limit-input.tsx b/src/renderer/routes/settings/cards/compact-limit-input.tsx
index b899e8d4..fe04bbf2 100644
--- a/src/renderer/routes/settings/cards/compact-limit-input.tsx
+++ b/src/renderer/routes/settings/cards/compact-limit-input.tsx
@@ -5,14 +5,22 @@ import {
InputGroup,
InputGroupAddon,
InputGroupInput,
- InputGroupText,
} from '@renderer/components/ui/input-group'
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@renderer/components/ui/select'
import {
Tooltip,
TooltipContent,
TooltipProvider,
TooltipTrigger,
} from '@renderer/components/ui/tooltip'
+import { useByteFormat } from '@renderer/hooks/use-byte-format'
+import type { SpeedLimitUnit } from '@shared/schemas/speed-limit-units'
import { type ComponentProps, forwardRef, useState } from 'react'
type ZeroAction = 'unlimited' | 'inherit'
@@ -23,7 +31,9 @@ type CompactLimitInputProps = Omit<
> & {
value: number
onValueChange: (value: number) => void
- unit: string
+ magnitude: SpeedLimitUnit
+ onMagnitudeChange: (value: SpeedLimitUnit) => void
+ unitLabel: string
zeroLabel: string
resetLabel: string
zeroAction?: ZeroAction
@@ -36,7 +46,9 @@ export const CompactLimitInput = forwardRef<
{
value,
onValueChange,
- unit,
+ magnitude,
+ onMagnitudeChange,
+ unitLabel,
zeroLabel,
resetLabel,
zeroAction = 'unlimited',
@@ -46,15 +58,41 @@ export const CompactLimitInput = forwardRef<
},
ref
) {
- // Preserve partial decimals while editing; the parent rounds to whole bytes.
- const [draft, setDraft] = useState<{ text: string; unit: string } | null>(
- null
+ const { unitSystem, formatByteUnit } = useByteFormat()
+ const kiloByte = unitSystem === 'binary' ? 1024 : 1000
+ const scale = magnitude === 'mega' ? kiloByte ** 2 : kiloByte
+ const units = {
+ kilo: formatByteUnit(unitSystem === 'binary' ? 'KiB' : 'KB', true),
+ mega: formatByteUnit(unitSystem === 'binary' ? 'MiB' : 'MB', true),
+ }
+ const unit = units[magnitude]
+ // Byte-level display precision avoids long binary rounding tails (1.1 MiB/s
+ // rounds to whole bytes). This formatted value is never committed on blur.
+ const displayValue = Number(
+ (value / scale).toFixed(magnitude === 'mega' ? 6 : 3)
)
+ // Keep bytes as the source of truth: selecting a unit never writes a value.
+ // Preserve partial decimals until blur, but discard drafts after external edits.
+ const [draft, setDraft] = useState<{
+ text: string
+ scale: number
+ bytes: number
+ } | null>(null)
+ const toBytes = (amount: number) => {
+ const bytes = Math.round(amount * scale)
+ // A positive sub-byte limit must not silently become unlimited. Keep tiny
+ // negatives invalid too, instead of rounding them into the zero sentinel.
+ return amount > 0
+ ? Math.max(1, bytes)
+ : amount < 0
+ ? Math.min(-1, bytes)
+ : bytes
+ }
const zero = value === 0
const ZeroActionIcon = zeroAction === 'inherit' ? ResetIcon : UnlimitedIcon
return (
- <ButtonGroup className="w-40 shrink-0">
+ <ButtonGroup className="w-42 shrink-0">
{!zero && (
<TooltipProvider>
<Tooltip>
@@ -89,22 +127,25 @@ export const CompactLimitInput = forwardRef<
inputMode="decimal"
autoComplete="off"
aria-valuemin={0}
- aria-valuenow={Number.isFinite(value) ? value : undefined}
- aria-valuetext={zero ? zeroLabel : `${value} ${unit}`}
+ aria-valuenow={
+ Number.isFinite(displayValue) ? displayValue : undefined
+ }
+ aria-valuetext={zero ? zeroLabel : `${displayValue} ${unit}`}
className="h-8 min-w-0 px-2 text-end tabular-nums placeholder:text-end placeholder:text-xs [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"
value={
- draft?.unit === unit
+ draft?.scale === scale && Object.is(draft.bytes, value)
? draft.text
: zero || !Number.isFinite(value)
? ''
- : value
+ : displayValue
}
placeholder={zeroLabel}
onChange={(event) => {
- setDraft({ text: event.target.value, unit })
- onValueChange(
+ const bytes = toBytes(
event.target.value === '' ? 0 : event.target.valueAsNumber
)
+ setDraft({ text: event.target.value, scale, bytes })
+ onValueChange(bytes)
}}
onBlur={(event) => {
setDraft(null)
@@ -121,14 +162,36 @@ export const CompactLimitInput = forwardRef<
event.preventDefault()
setDraft(null)
const delta = event.key === 'ArrowUp' ? 1 : -1
- onValueChange(Math.max(0, value + delta))
+ onValueChange(toBytes(Math.max(0, value / scale + delta)))
}}
/>
- {!zero && (
- <InputGroupAddon align="inline-end" className="pe-2">
- <InputGroupText className="text-[11px]">{unit}</InputGroupText>
- </InputGroupAddon>
- )}
+ <InputGroupAddon
+ align="inline-end"
+ className="shrink-0 py-0 pe-0 has-[>button]:me-0"
+ >
+ <Select
+ value={magnitude}
+ items={units}
+ disabled={props.disabled}
+ onValueChange={(next) => {
+ if (next !== 'kilo' && next !== 'mega') return
+ setDraft(null)
+ onMagnitudeChange(next)
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label={unitLabel}
+ className="h-7 w-13 shrink-0 justify-end gap-0.5 border-0 px-0.5 text-[11px] shadow-none [&_svg]:size-3"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent position="popper" align="end">
+ <SelectItem value="kilo">{units.kilo}</SelectItem>
+ <SelectItem value="mega">{units.mega}</SelectItem>
+ </SelectContent>
+ </Select>
+ </InputGroupAddon>
</InputGroup>
</ButtonGroup>
)
diff --git a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
index d285b5d5..30cd2129 100644
--- a/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
+++ b/src/renderer/routes/settings/cards/downloads-dialog.test.tsx
@@ -752,6 +752,89 @@ describe('<DownloadsDialog>', () => {
)
})
+ it('keeps each limit unit independent and saves no limit patch for unit-only edits', async () => {
+ render(
+ <DownloadsDialog
+ open
+ onClose={vi.fn()}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ const user = userEvent.setup()
+ const units = screen.getAllByRole('combobox', { name: /^unit for/i })
+ await waitFor(() => expect(units[0]).toBeEnabled())
+ expect(units).toHaveLength(4)
+ await user.click(units[0])
+ await user.click(await screen.findByRole('option', { name: 'MB/s' }))
+ expect(units[0]).toHaveTextContent('MB/s')
+ for (const unit of units.slice(1)) expect(unit).toHaveTextContent('KB/s')
+ for (const unit of units.slice(1)) {
+ await user.click(unit)
+ await user.click(await screen.findByRole('option', { name: 'MB/s' }))
+ }
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveDownloadsSettings,
+ expect.objectContaining({
+ settings: {
+ app: {
+ speedLimitUnits: {
+ baseUpload: 'mega',
+ baseDownload: 'mega',
+ altUpload: 'mega',
+ altDownload: 'mega',
+ },
+ },
+ },
+ })
+ )
+ })
+
+ it.each(['decimal', 'binary'] as const)(
+ 'saves fractional mega-unit input as exact bytes in the %s system',
+ async (system) => {
+ setByteUnitSystem(system)
+ const onClose = vi.fn()
+ render(
+ <DownloadsDialog
+ open
+ onClose={onClose}
+ labelKey="settings.cards.downloads.title"
+ descKey="settings.cards.downloads.desc"
+ />
+ )
+ const input = screen.getByLabelText(/download — standard limits/i)
+ await waitFor(() => expect(input).toBeEnabled())
+ const user = userEvent.setup()
+ await user.click(
+ screen.getByRole('combobox', {
+ name: 'Unit for Download (Standard limits)',
+ })
+ )
+ await user.click(
+ await screen.findByRole('option', {
+ name: system === 'binary' ? 'MiB/s' : 'MB/s',
+ })
+ )
+ expect(input).toHaveValue(null)
+ await user.type(input, '1.1')
+ await user.click(screen.getByRole('button', { name: /save/i }))
+ expect(transport.invoke).toHaveBeenCalledWith(
+ Commands.SaveDownloadsSettings,
+ expect.objectContaining({
+ settings: {
+ app: { speedLimitUnits: { baseDownload: 'mega' } },
+ speedLimit: {
+ base: { download: system === 'binary' ? 1_153_434 : 1_100_000 },
+ },
+ },
+ })
+ )
+ expect(onClose).toHaveBeenCalled()
+ }
+ )
+
it.each(['decimal', 'binary'] as const)(
'accepts fractional %s limits typed one character at a time',
async (unitSystem) => {
@@ -834,7 +917,7 @@ describe('<DownloadsDialog>', () => {
const standardGroup = setUnlimited.closest('[data-slot="button-group"]')
expect(standardGroup).toContainElement(baseDown)
- expect(standardGroup).toHaveClass('w-40')
+ expect(standardGroup).toHaveClass('w-42')
expect(useStandard).toBeDefined()
await user.click(setUnlimited)
diff --git a/src/renderer/routes/settings/cards/downloads-form.ts b/src/renderer/routes/settings/cards/downloads-form.ts
index a435e5b1..0b1bbe08 100644
--- a/src/renderer/routes/settings/cards/downloads-form.ts
+++ b/src/renderer/routes/settings/cards/downloads-form.ts
@@ -55,6 +55,7 @@ export const DOWNLOADS_DEFAULTS: DownloadsFields = {
defaultSaveDir: DEFAULT_APP_SETTINGS.defaultSaveDir,
autofillClipboardLinks: DEFAULT_APP_SETTINGS.autofillClipboardLinks,
fileDeletionMode: DEFAULT_APP_SETTINGS.fileDeletionMode,
+ speedLimitUnits: DEFAULT_APP_SETTINGS.speedLimitUnits,
},
engine: ENGINE_DEFAULTS,
// Source of truth: src/shared/schemas/speed-limit.ts (DEFAULT_SPEED_LIMIT_SETTINGS).
diff --git a/src/renderer/routes/settings/cards/speed-limit-section.tsx b/src/renderer/routes/settings/cards/speed-limit-section.tsx
index 96aa0584..a4791506 100644
--- a/src/renderer/routes/settings/cards/speed-limit-section.tsx
+++ b/src/renderer/routes/settings/cards/speed-limit-section.tsx
@@ -17,7 +17,6 @@ import {
ToggleGroup,
ToggleGroupItem,
} from '@renderer/components/ui/toggle-group'
-import { useByteFormat } from '@renderer/hooks/use-byte-format'
import { transport } from '@renderer/lib/transport'
import { Queries } from '@shared/protocol/queries'
@@ -33,8 +32,14 @@ const TIME_24_PATTERN = '(?:[01]\\d|2[0-3]):[0-5]\\d'
const TURTLE_STATES = ['off', 'on', 'auto'] as const
const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] as const
-
-type KbLimitName =
+const LIMIT_UNIT_FIELDS = {
+ 'speedLimit.base.upload': 'app.speedLimitUnits.baseUpload',
+ 'speedLimit.base.download': 'app.speedLimitUnits.baseDownload',
+ 'speedLimit.alt.upload': 'app.speedLimitUnits.altUpload',
+ 'speedLimit.alt.download': 'app.speedLimitUnits.altDownload',
+} as const
+
+type LimitName =
| 'speedLimit.base.download'
| 'speedLimit.base.upload'
| 'speedLimit.alt.download'
@@ -118,17 +123,14 @@ export function SpeedLimitSection({
}: {
form: UseFormReturn<DownloadsFields>
}) {
- const { unitSystem, formatByteUnit } = useByteFormat()
- const kiloByte = unitSystem === 'binary' ? 1024 : 1000
-
const { t } = useTranslation()
const settings = form.watch('speedLimit')
const turtle = settings.turtle
const scheduleEnabled = settings.auto.schedule.enabled
const adaptiveEnabled = settings.auto.adaptive.enabled
- const kbLimitRow = (
- name: KbLimitName,
+ const limitRow = (
+ name: LimitName,
labelKey: string,
zeroAction: 'unlimited' | 'inherit'
) => (
@@ -157,14 +159,23 @@ export function SpeedLimitSection({
name={field.name}
ref={field.ref}
onBlur={field.onBlur}
- value={(field.value as number) / kiloByte}
- onValueChange={(value) =>
- field.onChange(Math.round(value * kiloByte))
+ value={field.value as number}
+ onValueChange={field.onChange}
+ magnitude={form.watch(LIMIT_UNIT_FIELDS[name])}
+ onMagnitudeChange={(value) =>
+ form.setValue(LIMIT_UNIT_FIELDS[name], value, {
+ shouldDirty: true,
+ shouldTouch: true,
+ shouldValidate: true,
+ })
}
- unit={formatByteUnit(
- unitSystem === 'binary' ? 'KiB' : 'KB',
- true
- )}
+ unitLabel={t('settings.downloads.speedLimit.unitFor', {
+ field: `${t(labelKey)} (${t(
+ name.includes('.base.')
+ ? 'settings.downloads.speedLimit.baseSection'
+ : 'settings.downloads.speedLimit.altSection'
+ )})`,
+ })}
zeroAction={zeroAction}
zeroLabel={t(
zeroAction === 'inherit'
@@ -307,12 +318,12 @@ export function SpeedLimitSection({
<Separator className="my-2" />
<SectionIntro title={t('settings.downloads.speedLimit.baseSection')} />
- {kbLimitRow(
+ {limitRow(
'speedLimit.base.upload',
'settings.downloads.speedLimit.baseUpload',
'unlimited'
)}
- {kbLimitRow(
+ {limitRow(
'speedLimit.base.download',
'settings.downloads.speedLimit.baseDownload',
'unlimited'
@@ -321,12 +332,12 @@ export function SpeedLimitSection({
<Separator className="my-2" />
<SectionIntro title={t('settings.downloads.speedLimit.altSection')} />
- {kbLimitRow(
+ {limitRow(
'speedLimit.alt.upload',
'settings.downloads.speedLimit.altUpload',
'inherit'
)}
- {kbLimitRow(
+ {limitRow(
'speedLimit.alt.download',
'settings.downloads.speedLimit.altDownload',
'inherit'
diff --git a/src/shared/locales/ar.json b/src/shared/locales/ar.json
index 15ff16be..4c4a4bc8 100644
--- a/src/shared/locales/ar.json
+++ b/src/shared/locales/ar.json
@@ -2183,6 +2183,7 @@
"bandwidthUsed": "يمكن لـ Motrix استخدام {{motrix}}% كحد أقصى.",
"baseDownload": "تنزيل",
"baseDownloadDesc": "أقصى سرعة تنزيل للاستخدام اليومي.",
+ "unitFor": "وحدة {{field}}",
"baseSection": "الحدود القياسية",
"baseSectionDesc": "تُستخدم للتنزيلات اليومية وتبقى سارية في كل الأوضاع.",
"baseUpload": "الرفع",
diff --git a/src/shared/locales/bg.json b/src/shared/locales/bg.json
index a9f0fea0..30b4bf7c 100644
--- a/src/shared/locales/bg.json
+++ b/src/shared/locales/bg.json
@@ -2107,6 +2107,7 @@
"bandwidthUsed": "Motrix може да използва до {{motrix}}%.",
"baseDownload": "Изтегляне",
"baseDownloadDesc": "Максималната скорост на изтегляне за ежедневна употреба.",
+ "unitFor": "Единица за {{field}}",
"baseSection": "Стандартни ограничения",
"baseSectionDesc": "Използват се за ежедневни изтегляния и се спазват във всеки режим.",
"baseUpload": "Качване",
diff --git a/src/shared/locales/ca.json b/src/shared/locales/ca.json
index 78eefcf4..28030a2a 100644
--- a/src/shared/locales/ca.json
+++ b/src/shared/locales/ca.json
@@ -2126,6 +2126,7 @@
"bandwidthUsed": "El Motrix pot utilitzar fins al {{motrix}}%.",
"baseDownload": "Baixada",
"baseDownloadDesc": "Velocitat màxima de baixada per a l'ús habitual.",
+ "unitFor": "Unitat de {{field}}",
"baseSection": "Límits estàndard",
"baseSectionDesc": "S'utilitzen per a les baixades habituals i es respecten en tots els modes.",
"baseUpload": "Pujada",
diff --git a/src/shared/locales/de.json b/src/shared/locales/de.json
index 7346a509..b333d28d 100644
--- a/src/shared/locales/de.json
+++ b/src/shared/locales/de.json
@@ -1587,6 +1587,7 @@
"turtle_off": "Standard",
"turtle_on": "Langsam",
"turtle_auto": "Automatisch",
+ "unitFor": "Einheit für {{field}}",
"baseSection": "Standardlimits",
"baseSectionDesc": "Für alltägliche Downloads; gelten in jedem Modus.",
"baseDownload": "Download",
diff --git a/src/shared/locales/el.json b/src/shared/locales/el.json
index 0ea0ec09..9fdf44f3 100644
--- a/src/shared/locales/el.json
+++ b/src/shared/locales/el.json
@@ -2107,6 +2107,7 @@
"bandwidthUsed": "Το Motrix μπορεί να χρησιμοποιήσει έως το {{motrix}}%.",
"baseDownload": "Λήψη",
"baseDownloadDesc": "Η μέγιστη ταχύτητα λήψης για καθημερινή χρήση.",
+ "unitFor": "Μονάδα για {{field}}",
"baseSection": "Κανονικά όρια",
"baseSectionDesc": "Χρησιμοποιούνται για καθημερινές λήψεις και τηρούνται σε όλες τις λειτουργίες.",
"baseUpload": "Αποστολή",
diff --git a/src/shared/locales/en-US.json b/src/shared/locales/en-US.json
index b122f4bb..bdb900bb 100644
--- a/src/shared/locales/en-US.json
+++ b/src/shared/locales/en-US.json
@@ -1587,6 +1587,7 @@
"turtle_off": "Standard",
"turtle_on": "Low speed",
"turtle_auto": "Automatic",
+ "unitFor": "Unit for {{field}}",
"baseSection": "Standard limits",
"baseSectionDesc": "Used for everyday downloads and respected in every mode.",
"baseDownload": "Download",
diff --git a/src/shared/locales/es.json b/src/shared/locales/es.json
index 42e6e967..6d283c12 100644
--- a/src/shared/locales/es.json
+++ b/src/shared/locales/es.json
@@ -1601,6 +1601,7 @@
"turtle_off": "Estándar",
"turtle_on": "Baja velocidad",
"turtle_auto": "Automático",
+ "unitFor": "Unidad de {{field}}",
"baseSection": "Límites estándar",
"baseSectionDesc": "Se usan en las descargas habituales y se respetan en todos los modos.",
"baseDownload": "Descarga",
diff --git a/src/shared/locales/fa.json b/src/shared/locales/fa.json
index 2ee47cb5..e8731b2d 100644
--- a/src/shared/locales/fa.json
+++ b/src/shared/locales/fa.json
@@ -2107,6 +2107,7 @@
"bandwidthUsed": "Motrix می‌تواند حداکثر از {{motrix}}٪ استفاده کند.",
"baseDownload": "دانلود",
"baseDownloadDesc": "حداکثر سرعت دانلود روزمره.",
+ "unitFor": "واحد {{field}}",
"baseSection": "محدودیت‌های استاندارد",
"baseSectionDesc": "برای دانلودهای روزمره استفاده می‌شوند و در همهٔ حالت‌ها رعایت می‌شوند.",
"baseUpload": "بارگذاری",
diff --git a/src/shared/locales/fr.json b/src/shared/locales/fr.json
index d2745d70..3f5e71e6 100644
--- a/src/shared/locales/fr.json
+++ b/src/shared/locales/fr.json
@@ -2126,6 +2126,7 @@
"bandwidthUsed": "Motrix peut utiliser jusqu’à {{motrix}} %.",
"baseDownload": "Réception",
"baseDownloadDesc": "Débit maximal de réception au quotidien.",
+ "unitFor": "Unité pour {{field}}",
"baseSection": "Limites standard",
"baseSectionDesc": "Utilisées au quotidien et respectées dans tous les modes.",
"baseUpload": "Envoi",
diff --git a/src/shared/locales/hu.json b/src/shared/locales/hu.json
index 9ea51b1d..637eb898 100644
--- a/src/shared/locales/hu.json
+++ b/src/shared/locales/hu.json
@@ -1587,6 +1587,7 @@
"turtle_off": "Normál",
"turtle_on": "Alacsony sebesség",
"turtle_auto": "Automatikus",
+ "unitFor": "{{field}} mértékegysége",
"baseSection": "Normál korlátok",
"baseSectionDesc": "A mindennapi letöltésekhez használatosak, és minden mód figyelembe veszi őket.",
"baseDownload": "Letöltés",
diff --git a/src/shared/locales/id.json b/src/shared/locales/id.json
index 36a8987c..94e332b4 100644
--- a/src/shared/locales/id.json
+++ b/src/shared/locales/id.json
@@ -1573,6 +1573,7 @@
"turtle_off": "Standar",
"turtle_on": "Kecepatan rendah",
"turtle_auto": "Otomatis",
+ "unitFor": "Satuan untuk {{field}}",
"baseSection": "Batas standar",
"baseSectionDesc": "Digunakan untuk unduhan sehari-hari dan dipatuhi dalam semua mode.",
"baseDownload": "Unduh",
diff --git a/src/shared/locales/it.json b/src/shared/locales/it.json
index a9751941..779ffb57 100644
--- a/src/shared/locales/it.json
+++ b/src/shared/locales/it.json
@@ -1601,6 +1601,7 @@
"turtle_off": "Standard",
"turtle_on": "Bassa velocità",
"turtle_auto": "Automatica",
+ "unitFor": "Unità per {{field}}",
"baseSection": "Limiti standard",
"baseSectionDesc": "Usati per i download quotidiani e rispettati in ogni modalità.",
"baseDownload": "Download",
diff --git a/src/shared/locales/ja.json b/src/shared/locales/ja.json
index 14511193..6f47e1be 100644
--- a/src/shared/locales/ja.json
+++ b/src/shared/locales/ja.json
@@ -1573,6 +1573,7 @@
"turtle_off": "標準",
"turtle_on": "低速",
"turtle_auto": "自動",
+ "unitFor": "{{field}}の単位",
"baseSection": "標準の制限",
"baseSectionDesc": "通常のダウンロードに使用し、どのモードでもこの上限を守ります。",
"baseDownload": "ダウンロード",
diff --git a/src/shared/locales/ko.json b/src/shared/locales/ko.json
index e31906bb..c5f990cc 100644
--- a/src/shared/locales/ko.json
+++ b/src/shared/locales/ko.json
@@ -1573,6 +1573,7 @@
"turtle_off": "표준",
"turtle_on": "저속",
"turtle_auto": "자동",
+ "unitFor": "{{field}} 단위",
"baseSection": "표준 제한",
"baseSectionDesc": "일반적인 다운로드에 사용하며 모든 모드에서 이 제한을 준수합니다.",
"baseDownload": "다운로드",
diff --git a/src/shared/locales/nb.json b/src/shared/locales/nb.json
index bc204365..4a38c3c1 100644
--- a/src/shared/locales/nb.json
+++ b/src/shared/locales/nb.json
@@ -2107,6 +2107,7 @@
"bandwidthUsed": "Motrix kan bruke opptil {{motrix}}%.",
"baseDownload": "Nedlasting",
"baseDownloadDesc": "Maksimal nedlastingshastighet til daglig bruk.",
+ "unitFor": "Enhet for {{field}}",
"baseSection": "Standardgrenser",
"baseSectionDesc": "Brukes til daglige nedlastinger og overholdes i alle moduser.",
"baseUpload": "Opplasting",
diff --git a/src/shared/locales/nl.json b/src/shared/locales/nl.json
index 6964b0cc..fab03e71 100644
--- a/src/shared/locales/nl.json
+++ b/src/shared/locales/nl.json
@@ -2107,6 +2107,7 @@
"bandwidthUsed": "Motrix kan maximaal {{motrix}}% gebruiken.",
"baseDownload": "Download",
"baseDownloadDesc": "De maximale downloadsnelheid voor dagelijks gebruik.",
+ "unitFor": "Eenheid voor {{field}}",
"baseSection": "Standaardlimieten",
"baseSectionDesc": "Voor dagelijkse downloads; worden in elke modus gerespecteerd.",
"baseUpload": "Upload",
diff --git a/src/shared/locales/pl.json b/src/shared/locales/pl.json
index 4eda3e7c..b3215483 100644
--- a/src/shared/locales/pl.json
+++ b/src/shared/locales/pl.json
@@ -1615,6 +1615,7 @@
"turtle_off": "Standardowy",
"turtle_on": "Niska prędkość",
"turtle_auto": "Automatyczny",
+ "unitFor": "Jednostka dla {{field}}",
"baseSection": "Standardowe limity",
"baseSectionDesc": "Używane do codziennego pobierania i przestrzegane w każdym trybie.",
"baseDownload": "Pobieranie",
diff --git a/src/shared/locales/pt-BR.json b/src/shared/locales/pt-BR.json
index 70243499..5bf728db 100644
--- a/src/shared/locales/pt-BR.json
+++ b/src/shared/locales/pt-BR.json
@@ -1601,6 +1601,7 @@
"turtle_off": "Padrão",
"turtle_on": "Baixa velocidade",
"turtle_auto": "Automático",
+ "unitFor": "Unidade de {{field}}",
"baseSection": "Limites padrão",
"baseSectionDesc": "Usados nos downloads do dia a dia e respeitados em todos os modos.",
"baseDownload": "Download",
diff --git a/src/shared/locales/ro.json b/src/shared/locales/ro.json
index c24dcdd3..8008978d 100644
--- a/src/shared/locales/ro.json
+++ b/src/shared/locales/ro.json
@@ -2126,6 +2126,7 @@
"bandwidthUsed": "Motrix poate folosi până la {{motrix}}%.",
"baseDownload": "Descărcare",
"baseDownloadDesc": "Viteza maximă obișnuită de descărcare.",
+ "unitFor": "Unitate pentru {{field}}",
"baseSection": "Limite standard",
"baseSectionDesc": "Folosite pentru descărcările obișnuite și respectate în toate modurile.",
"baseUpload": "Încărcare",
diff --git a/src/shared/locales/ru.json b/src/shared/locales/ru.json
index 1ac7b667..81a09c71 100644
--- a/src/shared/locales/ru.json
+++ b/src/shared/locales/ru.json
@@ -1615,6 +1615,7 @@
"turtle_off": "Стандартный",
"turtle_on": "Низкая скорость",
"turtle_auto": "Автоматически",
+ "unitFor": "Единица для {{field}}",
"baseSection": "Стандартные ограничения",
"baseSectionDesc": "Используются для повседневных загрузок и соблюдаются во всех режимах.",
"baseDownload": "Загрузка",
diff --git a/src/shared/locales/th.json b/src/shared/locales/th.json
index badc2f7b..57cb11eb 100644
--- a/src/shared/locales/th.json
+++ b/src/shared/locales/th.json
@@ -2088,6 +2088,7 @@
"bandwidthUsed": "Motrix ใช้ได้สูงสุด {{motrix}}%",
"baseDownload": "ดาวน์โหลด",
"baseDownloadDesc": "ความเร็วดาวน์โหลดสูงสุดสำหรับการใช้งานทั่วไป",
+ "unitFor": "หน่วยของ {{field}}",
"baseSection": "ขีดจำกัดมาตรฐาน",
"baseSectionDesc": "ใช้สำหรับการดาวน์โหลดทั่วไปและมีผลในทุกโหมด",
"baseUpload": "อัปโหลด",
diff --git a/src/shared/locales/tr.json b/src/shared/locales/tr.json
index 8a7d12b5..5e5f6c4d 100644
--- a/src/shared/locales/tr.json
+++ b/src/shared/locales/tr.json
@@ -1587,6 +1587,7 @@
"turtle_off": "Standart",
"turtle_on": "Düşük hız",
"turtle_auto": "Otomatik",
+ "unitFor": "{{field}} birimi",
"baseSection": "Standart sınırlar",
"baseSectionDesc": "Günlük indirmelerde kullanılır ve her modda geçerlidir.",
"baseDownload": "İndirme",
diff --git a/src/shared/locales/uk.json b/src/shared/locales/uk.json
index 2693b48e..555299ea 100644
--- a/src/shared/locales/uk.json
+++ b/src/shared/locales/uk.json
@@ -2145,6 +2145,7 @@
"bandwidthUsed": "Motrix може використовувати до {{motrix}}%.",
"baseDownload": "Завантаження",
"baseDownloadDesc": "Максимальна швидкість повсякденного завантаження.",
+ "unitFor": "Одиниця для {{field}}",
"baseSection": "Стандартні обмеження",
"baseSectionDesc": "Використовуються для повсякденних завантажень і діють у всіх режимах.",
"baseUpload": "Вивантаження",
diff --git a/src/shared/locales/vi.json b/src/shared/locales/vi.json
index bdf0d457..80698632 100644
--- a/src/shared/locales/vi.json
+++ b/src/shared/locales/vi.json
@@ -1573,6 +1573,7 @@
"turtle_off": "Tiêu chuẩn",
"turtle_on": "Tốc độ thấp",
"turtle_auto": "Tự động",
+ "unitFor": "Đơn vị cho {{field}}",
"baseSection": "Giới hạn tiêu chuẩn",
"baseSectionDesc": "Dùng cho các lượt tải xuống hằng ngày và được tuân thủ trong mọi chế độ.",
"baseDownload": "Tải xuống",
diff --git a/src/shared/locales/zh-CN.json b/src/shared/locales/zh-CN.json
index 71d7d860..cd4addd3 100644
--- a/src/shared/locales/zh-CN.json
+++ b/src/shared/locales/zh-CN.json
@@ -1573,6 +1573,7 @@
"turtle_off": "常规",
"turtle_on": "低速",
"turtle_auto": "自动",
+ "unitFor": "{{field}}的单位",
"baseSection": "常规限速",
"baseSectionDesc": "日常下载使用;所有模式都会遵循这里的上限。",
"baseDownload": "下载",
diff --git a/src/shared/locales/zh-TW.json b/src/shared/locales/zh-TW.json
index 6eb1522d..2fe22cba 100644
--- a/src/shared/locales/zh-TW.json
+++ b/src/shared/locales/zh-TW.json
@@ -1573,6 +1573,7 @@
"turtle_off": "標準",
"turtle_on": "低速",
"turtle_auto": "自動",
+ "unitFor": "{{field}}的單位",
"baseSection": "一般限速",
"baseSectionDesc": "用於日常下載,且在每個模式下都會遵守。",
"baseDownload": "下載",
diff --git a/src/shared/schemas/app-settings.test.ts b/src/shared/schemas/app-settings.test.ts
index aa92bf1c..c1300f5c 100644
--- a/src/shared/schemas/app-settings.test.ts
+++ b/src/shared/schemas/app-settings.test.ts
@@ -6,6 +6,27 @@ import {
} from './app-settings'
describe('appSettingsSchema', () => {
+ it('recovers missing or damaged speed limit units without losing valid choices', () => {
+ expect(appSettingsSchema.parse({}).speedLimitUnits).toEqual({
+ baseUpload: 'kilo',
+ baseDownload: 'kilo',
+ altUpload: 'kilo',
+ altDownload: 'kilo',
+ })
+ expect(
+ appSettingsSchema.parse({
+ speedLimitUnits: { baseUpload: 'mega', baseDownload: 'GB' },
+ }).speedLimitUnits
+ ).toEqual({
+ baseUpload: 'mega',
+ baseDownload: 'kilo',
+ altUpload: 'kilo',
+ altDownload: 'kilo',
+ })
+ expect(
+ appSettingsSchema.parse({ speedLimitUnits: null }).speedLimitUnits
+ ).toEqual(DEFAULT_APP_SETTINGS.speedLimitUnits)
+ })
it('preserves system and explicit language preferences on load and write', () => {
for (const language of ['system', 'fr', 'en-US', 'zh-CN', 'zh-TW']) {
expect(appSettingsSchema.parse({ language }).language).toBe(language)
diff --git a/src/shared/schemas/app-settings.ts b/src/shared/schemas/app-settings.ts
index 28f2939a..538f61ef 100644
--- a/src/shared/schemas/app-settings.ts
+++ b/src/shared/schemas/app-settings.ts
@@ -10,6 +10,10 @@ import { DirectoryPreferencesSchema } from './directory-preferences'
import { languagePreferenceSchema } from './locale'
import { settingsInputObject } from './settings-input'
import { sidebarColorSchema } from './sidebar-color'
+import {
+ speedLimitUnitsInputSchema,
+ speedLimitUnitsSchema,
+} from './speed-limit-units'
import { DEFAULT_TRAY_ICON_COLOR, trayIconColorSchema } from './tray-icon-color'
import { windowMinimumDimensionSchema } from './window-bounds'
@@ -39,6 +43,7 @@ export const appSettingsSchema = z.object({
reduceMotion: z.boolean().catch(false),
language: languagePreferenceSchema.catch(DEFAULT_LOCALE),
byteUnitSystem: byteUnitSystemSchema.catch(DEFAULT_BYTE_UNIT_PREFERENCE),
+ speedLimitUnits: speedLimitUnitsSchema.catch(speedLimitUnitsSchema.parse({})),
// Empty string is a sentinel: SettingsManager (main/server) seeds the
// absolute platform download directory on first load. The renderer never
// observes '' because settings are loaded before the UI mounts.
@@ -81,6 +86,7 @@ export const DEFAULT_APP_SETTINGS: MotrixAppSettings = appSettingsSchema.parse(
export const appSettingsInputSchema = settingsInputObject(
appSettingsSchema
).extend({
+ speedLimitUnits: speedLimitUnitsInputSchema,
defaultSaveDir: z
.string()
.refine((value) => value.trim().length > 0 && !value.includes('\0'), {
diff --git a/src/shared/schemas/downloads-settings.ts b/src/shared/schemas/downloads-settings.ts
index 2cfb0ea6..a85ea5ec 100644
--- a/src/shared/schemas/downloads-settings.ts
+++ b/src/shared/schemas/downloads-settings.ts
@@ -18,6 +18,7 @@ export const downloadsSettingsSchema = z.object({
defaultSaveDir: true,
autofillClipboardLinks: true,
fileDeletionMode: true,
+ speedLimitUnits: true,
}),
engine: engineSettingsInputSchema.pick({
performanceProfile: true,
@@ -77,6 +78,10 @@ export const downloadsSettingsPatchSchema = z
app: downloadsSettingsSchema.shape.app
.partial()
.extend({
+ speedLimitUnits: appSettingsInputSchema.shape.speedLimitUnits
+ .partial()
+ .strict()
+ .optional(),
defaultSaveDir: z
.string()
.min(1)
diff --git a/src/shared/schemas/speed-limit-units.ts b/src/shared/schemas/speed-limit-units.ts
new file mode 100644
index 00000000..9493311b
--- /dev/null
+++ b/src/shared/schemas/speed-limit-units.ts
@@ -0,0 +1,17 @@
+import { z } from 'zod'
+import { settingsInputObject } from './settings-input'
+
+export const speedLimitUnitSchema = z.enum(['kilo', 'mega'])
+export type SpeedLimitUnit = z.infer<typeof speedLimitUnitSchema>
+
+// Store magnitude separately from byte rates and the global decimal/binary family.
+export const speedLimitUnitsSchema = z.object({
+ baseUpload: speedLimitUnitSchema.catch('kilo'),
+ baseDownload: speedLimitUnitSchema.catch('kilo'),
+ altUpload: speedLimitUnitSchema.catch('kilo'),
+ altDownload: speedLimitUnitSchema.catch('kilo'),
+})
+export type SpeedLimitUnits = z.infer<typeof speedLimitUnitsSchema>
+export const speedLimitUnitsInputSchema = settingsInputObject(
+ speedLimitUnitsSchema
+)
diff --git a/src/shared/types/settings.ts b/src/shared/types/settings.ts
index 2825bf00..b7071567 100644
--- a/src/shared/types/settings.ts
+++ b/src/shared/types/settings.ts
@@ -4,6 +4,7 @@ import type {
} from '@shared/schemas/app-settings'
import type { ByteUnitPreference } from '@shared/schemas/byte-unit-system'
import type { SidebarColor } from '@shared/schemas/sidebar-color'
+import type { SpeedLimitUnits } from '@shared/schemas/speed-limit-units'
import type { TrayIconColor } from '@shared/schemas/tray-icon-color'
import type { RunMode } from '../constants'
import type { EnginePerformanceProfile } from '../constants/engine-performance-profiles'
@@ -231,6 +232,7 @@ export interface MotrixAppSettings {
sidebarColor: SidebarColor
reduceMotion: boolean
byteUnitSystem: ByteUnitPreference
+ speedLimitUnits: SpeedLimitUnits
language: LanguagePreference
directoryPreferences: DirectoryPreferences
defaultSaveDir: string