🐛 fix(system-settings): resolve save detection and number input NaN issues

System settings forms that used flat dotted API keys (e.g.
`performance_setting.monitor_cpu_threshold`) with React Hook Form were
broken: RHF stores dotted paths as nested objects on update, while dirty
checks and submit comparisons still read flat keys from defaults. Users
could edit values but always saw "No changes to save".

Refactor affected sections to use nested Zod schemas and default values
for RHF, with explicit helpers to convert between nested form state and
flat API keys. Track a normalized baseline in refs for accurate change
detection and post-save resets.

Add `safeNumberFieldProps` to prevent native `<input type="number">`
from writing NaN into form state when cleared. NaN caused Zod validation
to fail silently and made the save button appear unresponsive. The
helper ignores non-finite updates so controlled inputs snap back to the
last valid value, matching legacy Semi InputNumber behavior.

Sections refactored for dotted-key handling:
- maintenance/performance-section
- models/grok-settings-card
- auth/passkey-section
- auth/oauth-section
- auth/section-registry (pass attachment_preference raw; normalize in section)

Sections migrated to safeNumberFieldProps:
- maintenance/performance-section
- models/grok-settings-card
- integrations/monitoring-settings-section
- integrations/payment-settings-section
- integrations/creem-product-dialog
- general/pricing-section (USD exchange rate)
- general/system-behavior-section
- content/dashboard-section

Optional numeric fields (e.g. custom currency exchange rate) keep their
existing empty-to-undefined semantics and are intentionally unchanged.
This commit is contained in:
t0ng7u
2026-05-26 15:43:56 +08:00
parent 5bc4c74813
commit 65f8afe922
16 changed files with 794 additions and 391 deletions
@@ -16,7 +16,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import * as z from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
@@ -44,6 +44,7 @@ import {
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@@ -66,31 +67,102 @@ import {
} from '../components/settings-form-layout'
import { SettingsPageFormActions } from '../components/settings-page-context'
import { SettingsSection } from '../components/settings-section'
import { useResetForm } from '../hooks/use-reset-form'
import { useUpdateOption } from '../hooks/use-update-option'
import { safeNumberFieldProps } from '../utils/numeric-field'
/**
* IMPORTANT: react-hook-form 7 interprets dotted `name` strings as nested
* paths. If we declare the schema with literal flat keys like
* `'performance_setting.disk_cache_enabled'`, the form state diverges from
* what zod validates and saves silently turn into no-ops. So we model the
* form internally with proper nested objects and only flatten back to the
* server-side key format right before persisting.
*/
const perfSchema = z.object({
'performance_setting.disk_cache_enabled': z.boolean(),
'performance_setting.disk_cache_threshold_mb': z.coerce.number().min(1),
'performance_setting.disk_cache_max_size_mb': z.coerce.number().min(100),
'performance_setting.disk_cache_path': z.string().optional(),
'performance_setting.monitor_enabled': z.boolean(),
'performance_setting.monitor_cpu_threshold': z.coerce.number().min(0),
'performance_setting.monitor_memory_threshold': z.coerce
.number()
.min(0)
.max(100),
'performance_setting.monitor_disk_threshold': z.coerce
.number()
.min(0)
.max(100),
'perf_metrics_setting.enabled': z.boolean(),
'perf_metrics_setting.flush_interval': z.coerce.number().min(1),
'perf_metrics_setting.bucket_time': z.enum(['minute', '5min', 'hour']),
'perf_metrics_setting.retention_days': z.coerce.number().min(0),
performance_setting: z.object({
disk_cache_enabled: z.boolean(),
disk_cache_threshold_mb: z.coerce.number().min(1),
disk_cache_max_size_mb: z.coerce.number().min(100),
disk_cache_path: z.string(),
monitor_enabled: z.boolean(),
monitor_cpu_threshold: z.coerce.number().min(0),
monitor_memory_threshold: z.coerce.number().min(0).max(100),
monitor_disk_threshold: z.coerce.number().min(0).max(100),
}),
perf_metrics_setting: z.object({
enabled: z.boolean(),
flush_interval: z.coerce.number().min(1),
bucket_time: z.enum(['minute', '5min', 'hour']),
retention_days: z.coerce.number().min(0),
}),
})
type PerfFormValues = z.infer<typeof perfSchema>
type PerfFormInput = z.input<typeof perfSchema>
type PerfFormValues = z.output<typeof perfSchema>
type FlatPerfDefaults = {
'performance_setting.disk_cache_enabled': boolean
'performance_setting.disk_cache_threshold_mb': number
'performance_setting.disk_cache_max_size_mb': number
'performance_setting.disk_cache_path': string
'performance_setting.monitor_enabled': boolean
'performance_setting.monitor_cpu_threshold': number
'performance_setting.monitor_memory_threshold': number
'performance_setting.monitor_disk_threshold': number
'perf_metrics_setting.enabled': boolean
'perf_metrics_setting.flush_interval': number
'perf_metrics_setting.bucket_time': 'minute' | '5min' | 'hour'
'perf_metrics_setting.retention_days': number
}
const buildFormDefaults = (defaults: FlatPerfDefaults): PerfFormInput => ({
performance_setting: {
disk_cache_enabled: defaults['performance_setting.disk_cache_enabled'],
disk_cache_threshold_mb:
defaults['performance_setting.disk_cache_threshold_mb'],
disk_cache_max_size_mb:
defaults['performance_setting.disk_cache_max_size_mb'],
disk_cache_path: defaults['performance_setting.disk_cache_path'] ?? '',
monitor_enabled: defaults['performance_setting.monitor_enabled'],
monitor_cpu_threshold:
defaults['performance_setting.monitor_cpu_threshold'],
monitor_memory_threshold:
defaults['performance_setting.monitor_memory_threshold'],
monitor_disk_threshold:
defaults['performance_setting.monitor_disk_threshold'],
},
perf_metrics_setting: {
enabled: defaults['perf_metrics_setting.enabled'],
flush_interval: defaults['perf_metrics_setting.flush_interval'],
bucket_time: defaults['perf_metrics_setting.bucket_time'],
retention_days: defaults['perf_metrics_setting.retention_days'],
},
})
const normalizeFormValues = (values: PerfFormValues): FlatPerfDefaults => ({
'performance_setting.disk_cache_enabled':
values.performance_setting.disk_cache_enabled,
'performance_setting.disk_cache_threshold_mb':
values.performance_setting.disk_cache_threshold_mb,
'performance_setting.disk_cache_max_size_mb':
values.performance_setting.disk_cache_max_size_mb,
'performance_setting.disk_cache_path':
values.performance_setting.disk_cache_path ?? '',
'performance_setting.monitor_enabled':
values.performance_setting.monitor_enabled,
'performance_setting.monitor_cpu_threshold':
values.performance_setting.monitor_cpu_threshold,
'performance_setting.monitor_memory_threshold':
values.performance_setting.monitor_memory_threshold,
'performance_setting.monitor_disk_threshold':
values.performance_setting.monitor_disk_threshold,
'perf_metrics_setting.enabled': values.perf_metrics_setting.enabled,
'perf_metrics_setting.flush_interval':
values.perf_metrics_setting.flush_interval,
'perf_metrics_setting.bucket_time': values.perf_metrics_setting.bucket_time,
'perf_metrics_setting.retention_days':
values.perf_metrics_setting.retention_days,
})
function formatBytes(bytes: number, decimals = 2): string {
if (!bytes || isNaN(bytes)) return '0 Bytes'
@@ -104,7 +176,7 @@ function formatBytes(bytes: number, decimals = 2): string {
}
interface Props {
defaultValues: PerfFormValues
defaultValues: FlatPerfDefaults
}
type LogInfo = {
@@ -158,14 +230,28 @@ export function PerformanceSection(props: Props) {
const [logCleanupValue, setLogCleanupValue] = useState(10)
const [logCleanupLoading, setLogCleanupLoading] = useState(false)
const form = useForm<PerfFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(perfSchema) as any,
defaultValues: props.defaultValues,
const formDefaults = useMemo(
() => buildFormDefaults(props.defaultValues),
[props.defaultValues]
)
const form = useForm<PerfFormInput, unknown, PerfFormValues>({
resolver: zodResolver(perfSchema),
defaultValues: formDefaults,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
useResetForm(form as any, props.defaultValues)
const baselineRef = useRef<FlatPerfDefaults>(props.defaultValues)
const baselineSerializedRef = useRef<string>(
JSON.stringify(props.defaultValues)
)
useEffect(() => {
const serialized = JSON.stringify(props.defaultValues)
if (serialized === baselineSerializedRef.current) return
baselineRef.current = props.defaultValues
baselineSerializedRef.current = serialized
form.reset(buildFormDefaults(props.defaultValues))
}, [props.defaultValues, form])
const fetchStats = useCallback(async () => {
try {
@@ -190,23 +276,27 @@ export function PerformanceSection(props: Props) {
fetchLogInfo()
}, [fetchStats, fetchLogInfo])
const onSubmit = async (data: PerfFormValues) => {
const entries = Object.entries(data) as [string, unknown][]
const updates = entries.filter(
([key, value]) =>
value !== (props.defaultValues[key as keyof PerfFormValues] as unknown)
)
if (updates.length === 0) {
const onSubmit = async (values: PerfFormValues) => {
const normalized = normalizeFormValues(values)
const changedKeys = (
Object.keys(normalized) as Array<keyof FlatPerfDefaults>
).filter((key) => normalized[key] !== baselineRef.current[key])
if (changedKeys.length === 0) {
toast.info(t('No changes to save'))
return
}
for (const [key, value] of updates) {
for (const key of changedKeys) {
await updateOption.mutateAsync({
key,
value: value as string | number | boolean,
value: normalized[key],
})
}
toast.success(t('Saved successfully'))
baselineRef.current = normalized
baselineSerializedRef.current = JSON.stringify(normalized)
form.reset(buildFormDefaults(normalized))
fetchStats()
}
@@ -278,9 +368,13 @@ export function PerformanceSection(props: Props) {
const diskEnabled = form.watch('performance_setting.disk_cache_enabled')
const monitorEnabled = form.watch('performance_setting.monitor_enabled')
const perfMetricsEnabled = form.watch('perf_metrics_setting.enabled')
const maxCacheSizeMb = form.watch(
const maxCacheSizeRaw = form.watch(
'performance_setting.disk_cache_max_size_mb'
)
const maxCacheSizeMb =
typeof maxCacheSizeRaw === 'number'
? maxCacheSizeRaw
: Number(maxCacheSizeRaw) || 0
const lowDiskSpace =
diskEnabled &&
@@ -342,11 +436,18 @@ export function PerformanceSection(props: Props) {
<FormItem>
<FormLabel>{t('Disk Cache Threshold (MB)')}</FormLabel>
<FormControl>
<Input type='number' {...field} disabled={!diskEnabled} />
<Input
type='number'
min={1}
step={1}
{...safeNumberFieldProps(field)}
disabled={!diskEnabled}
/>
</FormControl>
<FormDescription>
{t('Use disk cache when request body exceeds this size')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>
@@ -357,7 +458,13 @@ export function PerformanceSection(props: Props) {
<FormItem>
<FormLabel>{t('Max Disk Cache Size (MB)')}</FormLabel>
<FormControl>
<Input type='number' {...field} disabled={!diskEnabled} />
<Input
type='number'
min={100}
step={1}
{...safeNumberFieldProps(field)}
disabled={!diskEnabled}
/>
</FormControl>
{stats?.disk_space_info &&
stats.disk_space_info.total > 0 && (
@@ -368,6 +475,7 @@ export function PerformanceSection(props: Props) {
})}
</FormDescription>
)}
<FormMessage />
</FormItem>
)}
/>
@@ -393,11 +501,15 @@ export function PerformanceSection(props: Props) {
placeholder={t(
'Leave empty to use system temp directory'
)}
{...field}
value={field.value ?? ''}
onChange={(event) => field.onChange(event.target.value)}
name={field.name}
onBlur={field.onBlur}
ref={field.ref}
disabled={!diskEnabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -444,10 +556,13 @@ export function PerformanceSection(props: Props) {
<FormControl>
<Input
type='number'
{...field}
min={0}
step={1}
{...safeNumberFieldProps(field)}
disabled={!monitorEnabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -460,10 +575,14 @@ export function PerformanceSection(props: Props) {
<FormControl>
<Input
type='number'
{...field}
min={0}
max={100}
step={1}
{...safeNumberFieldProps(field)}
disabled={!monitorEnabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -476,10 +595,14 @@ export function PerformanceSection(props: Props) {
<FormControl>
<Input
type='number'
{...field}
min={0}
max={100}
step={1}
{...safeNumberFieldProps(field)}
disabled={!monitorEnabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -526,10 +649,12 @@ export function PerformanceSection(props: Props) {
<Input
type='number'
min={1}
{...field}
step={1}
{...safeNumberFieldProps(field)}
disabled={!perfMetricsEnabled}
/>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
@@ -562,6 +687,7 @@ export function PerformanceSection(props: Props) {
</SelectGroup>
</SelectContent>
</Select>
<FormMessage />
</FormItem>
)}
/>
@@ -575,13 +701,15 @@ export function PerformanceSection(props: Props) {
<Input
type='number'
min={0}
{...field}
step={1}
{...safeNumberFieldProps(field)}
disabled={!perfMetricsEnabled}
/>
</FormControl>
<FormDescription>
{t('0 means data is kept permanently')}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>