🐛 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,10 +16,12 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useMemo, useRef } from 'react'
import * as z from 'zod'
import { useForm } from 'react-hook-form'
import { zodResolver } from '@hookform/resolvers/zod'
import { useTranslation } from 'react-i18next'
import { toast } from 'sonner'
import {
Form,
FormControl,
@@ -27,6 +29,7 @@ import {
FormField,
FormItem,
FormLabel,
FormMessage,
} from '@/components/ui/form'
import { Input } from '@/components/ui/input'
import { Switch } from '@/components/ui/switch'
@@ -37,48 +40,97 @@ 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'
const XAI_VIOLATION_FEE_DOC_URL =
'https://docs.x.ai/docs/models#usage-guidelines-violation-fee'
/**
* The schema uses a nested object so the dotted FormField `name` props line
* up with react-hook-form's path semantics. Using flat keys like
* `'grok.violation_deduction_enabled'` causes RHF to silently maintain two
* parallel value trees and saves never see the user input.
*/
const grokSchema = z.object({
'grok.violation_deduction_enabled': z.boolean(),
'grok.violation_deduction_amount': z.coerce.number().min(0),
grok: z.object({
violation_deduction_enabled: z.boolean(),
violation_deduction_amount: z.coerce.number().min(0),
}),
})
type GrokFormValues = z.infer<typeof grokSchema>
type GrokFormInput = z.input<typeof grokSchema>
type GrokFormValues = z.output<typeof grokSchema>
type FlatGrokDefaults = {
'grok.violation_deduction_enabled': boolean
'grok.violation_deduction_amount': number
}
const buildFormDefaults = (defaults: FlatGrokDefaults): GrokFormInput => ({
grok: {
violation_deduction_enabled: defaults['grok.violation_deduction_enabled'],
violation_deduction_amount: defaults['grok.violation_deduction_amount'],
},
})
const normalizeFormValues = (values: GrokFormValues): FlatGrokDefaults => ({
'grok.violation_deduction_enabled': values.grok.violation_deduction_enabled,
'grok.violation_deduction_amount': values.grok.violation_deduction_amount,
})
interface Props {
defaultValues: GrokFormValues
defaultValues: FlatGrokDefaults
}
export function GrokSettingsCard(props: Props) {
const { t } = useTranslation()
const updateOption = useUpdateOption()
const form = useForm<GrokFormValues>({
// eslint-disable-next-line @typescript-eslint/no-explicit-any
resolver: zodResolver(grokSchema) as any,
defaultValues: props.defaultValues,
const formDefaults = useMemo(
() => buildFormDefaults(props.defaultValues),
[props.defaultValues]
)
const form = useForm<GrokFormInput, unknown, GrokFormValues>({
resolver: zodResolver(grokSchema),
defaultValues: formDefaults,
})
// eslint-disable-next-line @typescript-eslint/no-explicit-any
useResetForm(form as any, props.defaultValues)
const baselineRef = useRef<FlatGrokDefaults>(props.defaultValues)
const baselineSerializedRef = useRef<string>(
JSON.stringify(props.defaultValues)
)
const onSubmit = async (data: GrokFormValues) => {
const entries = Object.entries(data) as [string, unknown][]
const updates = entries.filter(
([key, value]) =>
value !== (props.defaultValues[key as keyof GrokFormValues] as unknown)
)
for (const [key, value] of updates) {
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 onSubmit = async (values: GrokFormValues) => {
const normalized = normalizeFormValues(values)
const changedKeys = (
Object.keys(normalized) as Array<keyof FlatGrokDefaults>
).filter((key) => normalized[key] !== baselineRef.current[key])
if (changedKeys.length === 0) {
toast.info(t('No changes to save'))
return
}
for (const key of changedKeys) {
await updateOption.mutateAsync({
key,
value: value as string | number | boolean,
value: normalized[key],
})
}
baselineRef.current = normalized
baselineSerializedRef.current = JSON.stringify(normalized)
form.reset(buildFormDefaults(normalized))
}
const enabled = form.watch('grok.violation_deduction_enabled')
@@ -133,7 +185,7 @@ export function GrokSettingsCard(props: Props) {
type='number'
step={0.01}
min={0}
{...field}
{...safeNumberFieldProps(field)}
disabled={!enabled}
/>
</FormControl>
@@ -142,6 +194,7 @@ export function GrokSettingsCard(props: Props) {
'Base amount. Actual deduction = base amount × system group rate.'
)}
</FormDescription>
<FormMessage />
</FormItem>
)}
/>