Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(unifi): UniFi panel in settings
Pouzorbfb54f3b3565
diff --git a/frontend/src/components/modals/SettingsModal.tsx b/frontend/src/components/modals/SettingsModal.tsxindex 55ccbe9..55ce597 100644--- a/frontend/src/components/modals/SettingsModal.tsx+++ b/frontend/src/components/modals/SettingsModal.tsx@@ -6,9 +6,12 @@ import {proxmoxApi,zigbeeApi,zwaveApi,+ unifiApi,type ProxmoxConfigData,type ZigbeeConfigData,type ZwaveConfigData,+ type UnifiConfigData,+ type UnifiImportModes,} from '@/api/client'import { useCanvasStore } from '@/stores/canvasStore'import { useWalkthroughStore } from '@/stores/walkthroughStore'@@ -113,6 +116,13 @@ function MeshAutoSync({)}+/** The controller's three inventories, described where the user ticks them. */+const UNIFI_SOURCES: { key: keyof UnifiImportModes; label: string; hint: string }[] = [+ { key: 'infrastructure', label: 'Infrastructure', hint: 'stat/device — adopted APs, switches, gateways.' },+ { key: 'known_clients', label: 'Known clients', hint: 'list/user — every client ever recorded. No IP, and long on a busy site.' },+ { key: 'active_clients', label: 'Active clients', hint: 'stat/sta — connected right now, with IP and switch port.' },+]+export function SettingsModal({ open, onClose }: SettingsModalProps) {const [interval, setIntervalValue] = useState(60)const [serviceCheckEnabled, setServiceCheckEnabled] = useState(false)@@ -130,8 +140,18 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {const [zwSyncEnabled, setZwSyncEnabled] = useState(false)const [zwInterval, setZwInterval] = useState(3600)const [zwSyncing, setZwSyncing] = useState(false)+ const [unConfig, setUnConfig] = useState<UnifiConfigData | null>(null)+ const [unSyncEnabled, setUnSyncEnabled] = useState(false)+ const [unInterval, setUnInterval] = useState(3600)+ const [unModes, setUnModes] = useState<UnifiImportModes>({+ infrastructure: true,+ known_clients: false,+ active_clients: false,+ })+ const [unSyncing, setUnSyncing] = useState(false)const [alignment, setAlignment] = useState<AlignmentSettings>(readAlignmentSettings)const [autosave, setAutosave] = useState<AutosaveSettings>(readAutosaveSettings)+ const anyUnifiSource = unModes.infrastructure || unModes.known_clients || unModes.active_clientsconst hideIp = useCanvasStore((s) => s.hideIp)const setHideIp = useCanvasStore((s) => s.setHideIp)@@ -165,6 +185,14 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {setZwInterval(res.data.sync_interval)}).catch(() => {/* zwave not configured */})+ unifiApi.getConfig()+ .then((res) => {+ setUnConfig(res.data)+ setUnSyncEnabled(res.data.sync_enabled)+ setUnInterval(res.data.sync_interval)+ setUnModes(res.data.modes)+ })+ .catch(() => {/* unifi not configured */})}, [open])useEffect(() => subscribeAlignmentSettings(setAlignment), [])@@ -194,6 +222,19 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {}}+ const handleUnSyncNow = async () => {+ setUnSyncing(true)+ try {+ const res = await unifiApi.syncNow()+ const { infra_count, client_count } = res.data+ toast.success(`UniFi sync done — ${infra_count} device(s), ${client_count} client(s)`)+ } catch {+ toast.error('Failed to run UniFi sync')+ } finally {+ setUnSyncing(false)+ }+ }+const handleZbSyncNow = async () => {setZbSyncing(true)try {@@ -253,6 +294,15 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {sync_interval: zwInterval,})}+ if (unConfig) {+ // Connection config is env-only; the activation and which of the+ // controller's three inventories to pull are what persist.+ await unifiApi.saveConfig({+ sync_enabled: unSyncEnabled,+ sync_interval: unInterval,+ modes: unModes,+ })+ }toast.success('Settings saved')onClose()} catch {@@ -515,6 +565,91 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {)}</div>)}+ {/* UniFi auto-sync */}+ {!STANDALONE && unConfig && (+ <div className="pt-3 border-t border-border space-y-2">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">UniFi auto-sync</span>+ {!unConfig.credentials_configured ? (+ <p className="text-[10px] text-[#e3b341] leading-tight">+ No controller credentials configured. Set <span className="font-mono">UNIFI_USER</span> and{' '}+ <span className="font-mono">UNIFI_PASS</span> in the server .env to enable auto-sync.+ </p>+ ) : (+ <>+ <label className="flex items-center justify-between gap-2 cursor-pointer">+ <span className="text-xs text-foreground">Auto-sync UniFi inventory</span>+ <input+ type="checkbox"+ checked={unSyncEnabled}+ onChange={(e) => setUnSyncEnabled(e.target.checked)}+ className="cursor-pointer accent-[#0559c9]"+ aria-label="Toggle UniFi auto-sync"+ />+ </label>+ <div className={unSyncEnabled ? 'space-y-1.5' : 'space-y-1.5 opacity-50 pointer-events-none'}>+ <label className="text-xs text-muted-foreground">Sync interval (s)</label>+ <div className="flex items-center gap-2">+ <input+ type="number"+ min={300}+ max={86400}+ value={unInterval}+ onChange={(e) => { const v = Number(e.target.value); if (!isNaN(v)) setUnInterval(v) }}+ className="w-24 px-2 py-1 rounded-md text-xs font-mono bg-[#0d1117] border border-border text-foreground focus:outline-none focus:border-[#0559c9]"+ aria-label="UniFi sync interval"+ />+ <span className="text-xs text-muted-foreground">seconds</span>+ </div>+ </div>+ {/* Which of the controller's three inventories to pull. Applies+ to auto-sync and to Re-sync now, not to the import modal,+ which asks each time. */}+ <div className="space-y-1.5 pt-1">+ <span className="text-xs text-muted-foreground">Import from</span>+ {UNIFI_SOURCES.map((src) => (+ <label key={src.key} className="flex items-start justify-between gap-2 cursor-pointer">+ <span className="min-w-0">+ <span className="text-xs text-foreground">{src.label}</span>+ <span className="block text-[10px] text-muted-foreground leading-tight">{src.hint}</span>+ </span>+ <input+ type="checkbox"+ checked={unModes[src.key]}+ onChange={(e) => setUnModes((m) => ({ ...m, [src.key]: e.target.checked }))}+ className="mt-0.5 cursor-pointer accent-[#0559c9]"+ aria-label={`Import ${src.label}`}+ />+ </label>+ ))}+ {!anyUnifiSource && (+ <p className="text-[10px] text-[#e3b341] leading-tight">+ Select at least one source, or the sync has nothing to import.+ </p>+ )}+ </div>+ {unConfig.host ? (+ <div className="flex items-center gap-2 pt-1">+ <Button+ variant="outline"+ onClick={handleUnSyncNow}+ disabled={unSyncing || !anyUnifiSource}+ className="h-7 text-xs border-[#0559c9] text-[#0559c9] hover:bg-[#0559c9]/10"+ >+ {unSyncing ? 'Syncing…' : 'Re-sync now'}+ </Button>+ <span className="text-[10px] text-muted-foreground leading-tight">+ Runs one import immediately using the server .env config.+ </span>+ </div>+ ) : (+ <p className="text-[10px] text-[#e3b341] leading-tight pt-1">+ Set <span className="font-mono">UNIFI_HOST</span> in the server .env to enable manual re-sync.+ </p>+ )}+ </>+ )}+ </div>+ )}</div></div>diff --git a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx b/frontend/src/components/modals/__tests__/SettingsModal.test.tsxindex 14b0dbc..8be378d 100644--- a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx+++ b/frontend/src/components/modals/__tests__/SettingsModal.test.tsx@@ -23,9 +23,14 @@ vi.mock('@/api/client', () => ({saveConfig: vi.fn(),syncNow: vi.fn(),},+ unifiApi: {+ getConfig: vi.fn(),+ saveConfig: vi.fn(),+ syncNow: vi.fn(),+ },}))-import { settingsApi, proxmoxApi, zigbeeApi, zwaveApi } from '@/api/client'+import { settingsApi, proxmoxApi, zigbeeApi, zwaveApi, unifiApi } from '@/api/client'import { toast } from 'sonner'import { useCanvasStore } from '@/stores/canvasStore'@@ -44,6 +49,9 @@ describe('SettingsModal', () => {vi.mocked(zwaveApi.getConfig).mockRejectedValue(new Error('not configured'))vi.mocked(zwaveApi.saveConfig).mockResolvedValue({ data: {} } as never)vi.mocked(zwaveApi.syncNow).mockResolvedValue({ data: { status: 'running' } } as never)+ vi.mocked(unifiApi.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(unifiApi.saveConfig).mockResolvedValue({ data: {} } as never)+ vi.mocked(unifiApi.syncNow).mockResolvedValue({ data: { infra_count: 4, client_count: 1 } } as never)vi.mocked(toast.success).mockReset()vi.mocked(toast.error).mockReset()})@@ -213,3 +221,95 @@ describe('SettingsModal', () => {expect(onClose).toHaveBeenCalledOnce()})})++describe('SettingsModal — UniFi', () => {+ beforeEach(() => {+ vi.clearAllMocks()+ vi.mocked(settingsApi.get).mockResolvedValue({ data: { interval_seconds: 60, service_check_enabled: false, service_check_interval: 300 } } as never)+ vi.mocked(settingsApi.save).mockResolvedValue({ data: {} } as never)+ vi.mocked(proxmoxApi.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(zigbeeApi.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(zwaveApi.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(unifiApi.saveConfig).mockResolvedValue({ data: {} } as never)+ vi.mocked(unifiApi.syncNow).mockResolvedValue({ data: { infra_count: 4, client_count: 1 } } as never)+ vi.mocked(toast.success).mockReset()+ vi.mocked(toast.error).mockReset()+ })++ const config = (over = {}) => ({+ data: {+ host: 'unifi.local', port: 8443, site: 'default', verify_tls: false,+ sync_enabled: false, sync_interval: 3600, credentials_configured: true,+ modes: { infrastructure: true, known_clients: false, active_clients: false },+ ...over,+ },+ })++ it('stays hidden when the controller is not configured', async () => {+ vi.mocked(unifiApi.getConfig).mockRejectedValue(new Error('not configured'))+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(unifiApi.getConfig).toHaveBeenCalled())+ expect(screen.queryByText('UniFi auto-sync')).not.toBeInTheDocument()+ })++ it('asks for credentials instead of the toggle when none are set', async () => {+ vi.mocked(unifiApi.getConfig).mockResolvedValue(config({ credentials_configured: false }) as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(screen.getByText('UniFi auto-sync')).toBeInTheDocument())+ expect(screen.getByText(/UNIFI_USER/)).toBeInTheDocument()+ expect(screen.queryByLabelText('Toggle UniFi auto-sync')).not.toBeInTheDocument()+ })++ it('persists the import modes the user ticked', async () => {+ vi.mocked(unifiApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(screen.getByText('UniFi auto-sync')).toBeInTheDocument())++ fireEvent.click(screen.getByLabelText('Import Known clients'))+ fireEvent.click(screen.getByLabelText('Toggle UniFi auto-sync'))+ fireEvent.click(screen.getByRole('button', { name: /save/i }))++ await waitFor(() => expect(unifiApi.saveConfig).toHaveBeenCalled())+ expect(vi.mocked(unifiApi.saveConfig).mock.calls[0][0]).toEqual({+ sync_enabled: true,+ sync_interval: 3600,+ modes: { infrastructure: true, known_clients: true, active_clients: false },+ })+ })++ it('reflects the modes the server already had', async () => {+ vi.mocked(unifiApi.getConfig).mockResolvedValue(+ config({ modes: { infrastructure: false, known_clients: true, active_clients: true } }) as never,+ )+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(screen.getByText('UniFi auto-sync')).toBeInTheDocument())++ expect(screen.getByLabelText('Import Infrastructure')).not.toBeChecked()+ expect(screen.getByLabelText('Import Known clients')).toBeChecked()+ expect(screen.getByLabelText('Import Active clients')).toBeChecked()+ })++ it('blocks Re-sync now when no source is selected', async () => {+ vi.mocked(unifiApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(screen.getByText('UniFi auto-sync')).toBeInTheDocument())++ fireEvent.click(screen.getByLabelText('Import Infrastructure'))++ expect(screen.getByRole('button', { name: /re-sync now/i })).toBeDisabled()+ expect(screen.getByText(/select at least one source/i)).toBeInTheDocument()+ })++ it('reports what a manual re-sync imported', async () => {+ vi.mocked(unifiApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ await waitFor(() => expect(screen.getByText('UniFi auto-sync')).toBeInTheDocument())++ fireEvent.click(screen.getByRole('button', { name: /re-sync now/i }))++ await waitFor(() => expect(unifiApi.syncNow).toHaveBeenCalledOnce())+ expect(toast.success).toHaveBeenCalledWith(+ expect.stringContaining('4 device(s), 1 client(s)'),+ )+ })+})