'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 { 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 { useEffect, useMemo, useState } from 'react'; interface EditableSettings { maxEventsPerSec: number; maxPayloadSizeKb: number; batchFlushThreshold: number; batchFlushIntervalMs: number; fileRotationMb: number; enableIdempotency: boolean; autoPruneDays: number; } interface PublicSettings extends EditableSettings { serverPort: number; webPort: number; updatedAt: string; } const DEFAULT_SETTINGS: EditableSettings = { maxEventsPerSec: 100, maxPayloadSizeKb: 100, batchFlushThreshold: 500, batchFlushIntervalMs: 2000, fileRotationMb: 100, enableIdempotency: true, autoPruneDays: 30, }; const TABS = [ { id: 'general', label: 'General' }, { id: 'connections', label: 'Connections' }, { id: 'storage', label: 'Storage' }, { id: 'security', label: 'Security' }, ]; type TabId = (typeof TABS)[number]['id']; export function SettingsWorkspace() { const { success, error } = useToast(); const [settings, setSettings] = useState(() => getCached('vcon:settings', DEFAULT_SETTINGS) ); const [savedSettings, setSavedSettings] = useState(() => getCached('vcon:settings', DEFAULT_SETTINGS) ); const [activeTab, setActiveTab] = useState('general'); const [jwtSecret, setJwtSecret] = useState(''); const [storagePath, setStoragePath] = useState(() => getCached('vcon:storage-path', '') ); const [baseUrl, setBaseUrl] = useState(''); const [webSocketUrl, setWebSocketUrl] = useState(''); const [serverPort, setServerPort] = useState(() => getCached('vcon:server-port', 4000) ); const [loading, setLoading] = useState( () => !getCached('vcon:settings-loaded', false) ); const [saving, setSaving] = useState(false); useEffect(() => { setBaseUrl(window.location.origin); const isLocalDev = window.location.port === '3000'; const socketProtocol = window.location.protocol === 'https:' ? 'wss' : 'ws'; const socketHost = isLocalDev ? `${window.location.hostname}:4000` : window.location.host; setWebSocketUrl(`${socketProtocol}://${socketHost}`); Promise.all([ fetch('/api/settings').then(async (response) => { if (!response.ok) throw new Error('Unable to load settings'); return response.json(); }), fetch('/api/storage').then(async (response) => { if (!response.ok) throw new Error('Unable to load storage information'); return response.json(); }), ]) .then(([settingsData, storageData]) => { const loaded: EditableSettings = { maxEventsPerSec: Number( settingsData.settings.maxEventsPerSec ?? DEFAULT_SETTINGS.maxEventsPerSec ), maxPayloadSizeKb: Number( settingsData.settings.maxPayloadSizeKb ?? DEFAULT_SETTINGS.maxPayloadSizeKb ), batchFlushThreshold: Number( settingsData.settings.batchFlushThreshold ?? DEFAULT_SETTINGS.batchFlushThreshold ), batchFlushIntervalMs: Number( settingsData.settings.batchFlushIntervalMs ?? DEFAULT_SETTINGS.batchFlushIntervalMs ), fileRotationMb: Number( settingsData.settings.fileRotationMb ?? DEFAULT_SETTINGS.fileRotationMb ), enableIdempotency: Boolean( settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency ), autoPruneDays: Number( settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays ), }; setSettings(setCached('vcon:settings', loaded)); setSavedSettings(loaded); setServerPort( setCached( 'vcon:server-port', Number((settingsData.settings as PublicSettings).serverPort ?? 4000) ) ); setStoragePath( setCached( 'vcon:storage-path', String(storageData.stats?.storageDirectory ?? '') ) ); setCached('vcon:settings-loaded', true); }) .catch(() => { error('Settings load failed', 'Using default runtime settings.'); }) .finally(() => setLoading(false)); }, [error]); const isDirty = useMemo( () => jwtSecret.trim().length > 0 || JSON.stringify(settings) !== JSON.stringify(savedSettings), [jwtSecret, savedSettings, settings] ); const updateNumber = (key: keyof EditableSettings, value: string) => { setSettings((current) => ({ ...current, [key]: Number(value) || 0 })); }; const saveSettings = async (event: React.FormEvent) => { event.preventDefault(); const normalized: EditableSettings = { maxEventsPerSec: Math.max( 1, Math.min( 10000, settings.maxEventsPerSec || DEFAULT_SETTINGS.maxEventsPerSec ) ), maxPayloadSizeKb: Math.max( 1, Math.min( 5120, settings.maxPayloadSizeKb || DEFAULT_SETTINGS.maxPayloadSizeKb ) ), batchFlushThreshold: Math.max( 1, settings.batchFlushThreshold || DEFAULT_SETTINGS.batchFlushThreshold ), batchFlushIntervalMs: Math.max( 100, settings.batchFlushIntervalMs || DEFAULT_SETTINGS.batchFlushIntervalMs ), fileRotationMb: Math.max( 1, settings.fileRotationMb || DEFAULT_SETTINGS.fileRotationMb ), enableIdempotency: settings.enableIdempotency, autoPruneDays: Math.max( 1, Math.min(365, settings.autoPruneDays || DEFAULT_SETTINGS.autoPruneDays) ), }; setSaving(true); try { const response = await fetch('/api/settings', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ ...normalized, ...(jwtSecret.trim() ? { jwtSecret: jwtSecret.trim() } : {}), }), }); const data = await response.json(); if (!response.ok) throw new Error(data.error || 'Settings update failed'); setSettings(setCached('vcon:settings', normalized)); setSavedSettings(normalized); setJwtSecret(''); success('Settings saved', 'Runtime settings updated.'); } catch (saveError) { error( 'Save failed', saveError instanceof Error ? saveError.message : 'Unable to save settings' ); } finally { setSaving(false); } }; const discardChanges = () => { setSettings(savedSettings); setJwtSecret(''); }; return (
setActiveTab(tab as TabId)} />
{activeTab === 'general' && ( <> updateNumber('maxEventsPerSec', event.target.value) } /> setSettings((current) => ({ ...current, enableIdempotency, })) } /> )} {activeTab === 'connections' && ( <> updateNumber('batchFlushThreshold', event.target.value) } /> updateNumber('batchFlushIntervalMs', event.target.value) } className="font-mono" /> )} {activeTab === 'storage' && ( <> updateNumber('fileRotationMb', event.target.value) } className="font-mono" /> updateNumber('autoPruneDays', event.target.value) } className="font-mono" /> )} {activeTab === 'security' && ( setJwtSecret(event.target.value)} placeholder="New secret..." /> updateNumber('maxPayloadSizeKb', event.target.value) } className="font-mono" /> )} {loading ? 'Loading' : isDirty ? 'Unsaved changes' : 'Saved'} } >
); }