'use client'; import { PageShell } from '@/components/layout/PageShell'; import { Button } from '@/components/ui/Button'; import { FormSwitch } from '@/components/ui/Form'; import { Input } from '@/components/ui/Input'; import { Modal } from '@/components/ui/Modal'; import { SettingsField, SettingsFooter, SettingsGroup, SettingsPanel, SettingsTabs, } from '@/components/ui/SettingsLayout'; import { StatStrip } from '@/components/ui/StatStrip'; import { useToast } from '@/components/ui/Toast'; import { getCached, setCached } from '@/lib/vconCache'; import { DEFAULT_EDITABLE_SETTINGS, describeSettingsBridgeSync, type EditableSettings, mapBridgeStatusToSocketUiState, normalizeEditableSettings, NUMERIC_SETTING_KEYS, type NumericSettingDrafts, type NumericSettingKey, resolvePublicEndpoints, SETTINGS_LIMITS, settingsToNumericDrafts, type SettingsValidationErrors, type SocketHealthUiState, validateEditableSettingsDraft, validateSingleNumericSetting, } from '@/lib/vconUiHelpers'; import { useCallback, useEffect, useMemo, useState } from 'react'; interface PublicSettings extends EditableSettings { serverPort: number; webPort: number; updatedAt: string; } const TABS = [ { id: 'general', label: 'General' }, { id: 'connections', label: 'Connections' }, { id: 'storage', label: 'Storage' }, { id: 'security', label: 'Security' }, ]; type TabId = (typeof TABS)[number]['id']; const FIELD_TO_TAB: Record = { maxEventsPerSec: 'general', batchFlushThreshold: 'connections', batchFlushIntervalMs: 'connections', fileRotationMb: 'storage', autoPruneDays: 'storage', maxPayloadSizeKb: 'security', }; export function SettingsWorkspace() { const { success, warning, error } = useToast(); const [savedSettings, setSavedSettings] = useState(() => getCached('vcon:settings', DEFAULT_EDITABLE_SETTINGS) ); const [numericDrafts, setNumericDrafts] = useState(() => settingsToNumericDrafts( getCached('vcon:settings', DEFAULT_EDITABLE_SETTINGS) ) ); const [enableIdempotency, setEnableIdempotency] = useState( () => getCached('vcon:settings', DEFAULT_EDITABLE_SETTINGS) .enableIdempotency ); const [fieldErrors, setFieldErrors] = useState({}); const [activeTab, setActiveTab] = useState('general'); const [jwtSecret, setJwtSecret] = useState(''); const [jwtError, setJwtError] = useState(''); const [confirmRotateOpen, setConfirmRotateOpen] = useState(false); const [storagePath, setStoragePath] = useState(() => getCached('vcon:storage-path', '') ); const [baseUrl, setBaseUrl] = useState(''); const [socketStatus, setSocketStatus] = useState('idle'); const [bridgeError, setBridgeError] = useState(''); const [activeSockets, setActiveSockets] = useState(0); const [serverPort, setServerPort] = useState(() => getCached('vcon:server-port', 4000) ); const [loading, setLoading] = useState( () => !getCached('vcon:settings-loaded', false) ); const [saving, setSaving] = useState(false); const webSocketUrl = useMemo(() => { if (!baseUrl || typeof window === 'undefined') return ''; return resolvePublicEndpoints(window.location, serverPort).webSocketUrl; }, [baseUrl, serverPort]); const probeSocketServer = useCallback(async () => { setSocketStatus('checking'); try { const response = await fetch('/api/metrics', { cache: 'no-store', signal: AbortSignal.timeout(3000), }); if (response.status === 401) { window.location.assign('/vcon/login'); return; } if (!response.ok) { setSocketStatus('offline'); setBridgeError(`Metrics probe returned HTTP ${response.status}`); return; } const metricsData = await response.json(); const runtimePort = Number(metricsData?.runtime?.serverPort); if (Number.isFinite(runtimePort) && runtimePort > 0) { setServerPort(setCached('vcon:server-port', runtimePort)); } setActiveSockets(Number(metricsData?.activeSockets) || 0); const nextState = mapBridgeStatusToSocketUiState( metricsData?.runtime?.ingestionBridgeStatus ); setSocketStatus(nextState); setBridgeError(String(metricsData?.runtime?.ingestionBridgeError || '')); } catch { setSocketStatus('offline'); setBridgeError('Unable to reach /api/metrics bridge probe'); } }, []); useEffect(() => { setBaseUrl(window.location.origin); Promise.all([ fetch('/api/settings', { cache: 'no-store' }).then(async (response) => { if (response.status === 401) { window.location.assign('/vcon/login'); return null; } if (!response.ok) throw new Error('Unable to load settings'); return response.json(); }), fetch('/api/storage', { cache: 'no-store' }).then(async (response) => { if (response.status === 401) { window.location.assign('/vcon/login'); return null; } if (!response.ok) throw new Error('Unable to load storage information'); return response.json(); }), fetch('/api/metrics', { cache: 'no-store' }) .then(async (response) => { if (response.status === 401) { window.location.assign('/vcon/login'); return null; } return response.ok ? response.json() : null; }) .catch(() => null), ]) .then(([settingsData, storageData, metricsData]) => { if (!settingsData || !storageData) return; const runtimePort = Number(metricsData?.runtime?.serverPort); const settingsPort = Number( (settingsData.settings as PublicSettings).serverPort ?? 4000 ); const loadedPort = Number.isFinite(runtimePort) && runtimePort > 0 ? runtimePort : settingsPort; const loaded: EditableSettings = { maxEventsPerSec: Number( settingsData.settings.maxEventsPerSec ?? DEFAULT_EDITABLE_SETTINGS.maxEventsPerSec ), maxPayloadSizeKb: Number( settingsData.settings.maxPayloadSizeKb ?? DEFAULT_EDITABLE_SETTINGS.maxPayloadSizeKb ), batchFlushThreshold: Number( settingsData.settings.batchFlushThreshold ?? DEFAULT_EDITABLE_SETTINGS.batchFlushThreshold ), batchFlushIntervalMs: Number( settingsData.settings.batchFlushIntervalMs ?? DEFAULT_EDITABLE_SETTINGS.batchFlushIntervalMs ), fileRotationMb: Number( settingsData.settings.fileRotationMb ?? DEFAULT_EDITABLE_SETTINGS.fileRotationMb ), enableIdempotency: Boolean( settingsData.settings.enableIdempotency ?? DEFAULT_EDITABLE_SETTINGS.enableIdempotency ), autoPruneDays: Number( settingsData.settings.autoPruneDays ?? DEFAULT_EDITABLE_SETTINGS.autoPruneDays ), }; const cachedLoaded = setCached('vcon:settings', loaded); setSavedSettings(cachedLoaded); setNumericDrafts(settingsToNumericDrafts(cachedLoaded)); setEnableIdempotency(cachedLoaded.enableIdempotency); setFieldErrors({}); setServerPort(setCached('vcon:server-port', loadedPort)); setStoragePath( setCached( 'vcon:storage-path', String(storageData.stats?.storageDirectory ?? '') ) ); if (metricsData) { setActiveSockets(Number(metricsData.activeSockets) || 0); setSocketStatus( mapBridgeStatusToSocketUiState( metricsData.runtime?.ingestionBridgeStatus ) ); setBridgeError(String(metricsData.runtime?.ingestionBridgeError || '')); } setCached('vcon:settings-loaded', true); }) .catch(() => { error('Settings load failed', 'Using last cached runtime settings.'); }) .finally(() => setLoading(false)); }, [error]); const isDirty = useMemo( () => jwtSecret.trim().length > 0 || enableIdempotency !== savedSettings.enableIdempotency || NUMERIC_SETTING_KEYS.some( (key) => numericDrafts[key].trim() !== String(savedSettings[key]) ), [enableIdempotency, jwtSecret, numericDrafts, savedSettings] ); const updateNumberDraft = (key: NumericSettingKey, value: string) => { setNumericDrafts((current) => ({ ...current, [key]: value, })); const check = validateSingleNumericSetting(key, value); setFieldErrors((current) => { if (check.valid) { if (!current[key]) return current; const next = { ...current }; delete next[key]; return next; } return { ...current, [key]: check.error }; }); }; const executeSave = async (validated: EditableSettings) => { const trimmedSecret = jwtSecret.trim(); setConfirmRotateOpen(false); setSaving(true); try { const response = await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...validated, ...(trimmedSecret ? { jwtSecret: trimmedSecret } : {}), }), }); if (response.status === 401) { window.location.assign('/vcon/login'); return; } const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Settings update failed'); const synced = normalizeEditableSettings(data.settings ?? validated); setCached('vcon:settings', synced); setSavedSettings(synced); setNumericDrafts(settingsToNumericDrafts(synced)); setEnableIdempotency(synced.enableIdempotency); setFieldErrors({}); setJwtSecret(''); setJwtError(''); const bridgeSummary = describeSettingsBridgeSync(data.bridgeSync); if (bridgeSummary.level === 'error') { setSocketStatus('auth_error'); setBridgeError(bridgeSummary.message || ''); error(bridgeSummary.title, bridgeSummary.message); } else if (bridgeSummary.level === 'warning') { setSocketStatus('offline'); setBridgeError(bridgeSummary.message || ''); warning(bridgeSummary.title, bridgeSummary.message); } else { if (Boolean(data.bridgeSync?.ok ?? data.bridgeSync?.synced)) { setSocketStatus('online'); setBridgeError(''); } success( 'Settings saved', trimmedSecret ? 'Runtime settings saved and client JWT credentials rotated.' : 'Runtime settings updated across Web & Ingestion.' ); } } catch (saveError) { error( 'Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings' ); } finally { setSaving(false); } }; const handleFormSubmit = async (event: React.FormEvent) => { event.preventDefault(); const validation = validateEditableSettingsDraft( numericDrafts, enableIdempotency ); if (!validation.valid || !validation.values) { setFieldErrors(validation.errors); if (validation.firstInvalidKey) { setActiveTab(FIELD_TO_TAB[validation.firstInvalidKey]); } const firstMessage = (validation.firstInvalidKey && validation.errors[validation.firstInvalidKey]) || 'Review highlighted numeric settings before saving.'; error('Invalid setting value', firstMessage); return; } setFieldErrors({}); const trimmedSecret = jwtSecret.trim(); if (trimmedSecret.length > 0 && trimmedSecret.length < 32) { const message = 'JWT secret must be at least 32 characters.'; setJwtError(message); setActiveTab('security'); error('Invalid JWT secret', message); return; } setJwtError(''); if (trimmedSecret.length >= 32) { setConfirmRotateOpen(true); return; } await executeSave(validation.values); }; const handleConfirmedRotateSave = async () => { const validation = validateEditableSettingsDraft( numericDrafts, enableIdempotency ); if (!validation.valid || !validation.values) { setConfirmRotateOpen(false); setFieldErrors(validation.errors); if (validation.firstInvalidKey) { setActiveTab(FIELD_TO_TAB[validation.firstInvalidKey]); } return; } await executeSave(validation.values); }; const discardChanges = () => { setNumericDrafts(settingsToNumericDrafts(savedSettings)); setEnableIdempotency(savedSettings.enableIdempotency); setFieldErrors({}); setJwtSecret(''); setJwtError(''); }; const rateLimitStat = numericDrafts.maxEventsPerSec.trim() || '—'; const flushThresholdStat = numericDrafts.batchFlushThreshold.trim() || '—'; const flushIntervalStat = numericDrafts.batchFlushIntervalMs.trim() || '—'; const rotationStat = numericDrafts.fileRotationMb.trim() || '—'; const pruneStat = numericDrafts.autoPruneDays.trim() === '0' ? 'Keep all' : numericDrafts.autoPruneDays.trim() ? `${numericDrafts.autoPruneDays.trim()}d` : '—'; return (
setActiveTab(tab as TabId)} />
{activeTab === 'general' && ( <> updateNumberDraft('maxEventsPerSec', event.target.value) } /> )} {activeTab === 'connections' && ( <>
Read-only runtime port managed via PORT_SOCKET environment variable.
updateNumberDraft('batchFlushThreshold', event.target.value) } /> updateNumberDraft('batchFlushIntervalMs', event.target.value) } className="font-mono" /> )} {activeTab === 'storage' && ( <> updateNumberDraft('fileRotationMb', event.target.value) } className="font-mono" /> updateNumberDraft('autoPruneDays', event.target.value) } className="font-mono" /> )} {activeTab === 'security' && ( { const val = event.target.value; setJwtSecret(val); if (!val.trim() || val.trim().length >= 32) { setJwtError(''); } }} placeholder="Minimum 32 characters to rotate..." /> updateNumberDraft('maxPayloadSizeKb', event.target.value) } className="font-mono" /> )} {loading ? 'Loading' : isDirty ? 'Unsaved changes' : 'Saved'} } >
!saving && setConfirmRotateOpen(false)} title="Confirm JWT secret rotation" maxWidth="xs" footer={ <> } >

Rotating the signing JWT secret will immediately re-sign registered client tokens and invalidate all older SDK JWT tokens and active WebSocket sessions. Continue?

); }