Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(unifi): the UniFi import modal and sidebar entry

Pouzorfc0f7474ff50
diff --git a/backend/app/api/routes/unifi.py b/backend/app/api/routes/unifi.py
index 3ec4292..6ed8e61 100644
--- a/backend/app/api/routes/unifi.py
+++ b/backend/app/api/routes/unifi.py
@@ -61,15 +61,17 @@ async def test_connection_endpoint(
_: str = Depends(get_current_user),
) -> UnifiTestConnectionResponse:
username, password = _resolve_credentials(payload)
- connected, message = await test_unifi_connection(
+ connected, message, counts = await test_unifi_connection(
host=payload.host,
port=payload.port,
site=payload.site,
username=username,
password=password,
verify_tls=payload.verify_tls,
+ known_clients=payload.modes.known_clients,
+ active_clients=payload.modes.active_clients,
)
- return UnifiTestConnectionResponse(connected=connected, message=message)
+ return UnifiTestConnectionResponse(connected=connected, message=message, counts=counts)
@router.post("/import-pending", response_model=UnifiImportResponse)
diff --git a/backend/app/schemas/unifi.py b/backend/app/schemas/unifi.py
index eeddbfd..53e769b 100644
--- a/backend/app/schemas/unifi.py
+++ b/backend/app/schemas/unifi.py
@@ -43,6 +43,9 @@ class UnifiConnectionRequest(BaseModel):
class UnifiTestConnectionResponse(BaseModel):
connected: bool
message: str
+ # Rows each queried source holds right now, so the import UI can show what
+ # a box would pull in. Only the sources asked for are present.
+ counts: dict[str, int] = Field(default_factory=dict)
class UnifiDeviceOut(BaseModel):
diff --git a/backend/app/services/unifi_service.py b/backend/app/services/unifi_service.py
index b2ffdd6..a9eb5ce 100644
--- a/backend/app/services/unifi_service.py
+++ b/backend/app/services/unifi_service.py
@@ -45,22 +45,44 @@ async def test_unifi_connection(
username: str,
password: str,
verify_tls: bool = False,
-) -> tuple[bool, str]:
- """Test UniFi controller reachability and credentials."""
+ known_clients: bool = False,
+ active_clients: bool = False,
+) -> tuple[bool, str, dict[str, int]]:
+ """Test the controller and count what each selected source holds.
+
+ Infrastructure is always counted — it doubles as the reachability check.
+ The client sources are counted only when asked, so the UI can show how many
+ rows a box would import before the user ticks it; list/user runs long.
+ """
+ counts: dict[str, int] = {}
try:
client = httpx.AsyncClient(verify=verify_tls, timeout=10.0)
try:
cookies = await _login(client, host, port, username, password)
if not cookies:
- return False, "Login failed: invalid credentials or unreachable host"
- devices = await _fetch_devices(client, host, port, site, cookies)
- return True, f"Connected — {len(devices)} device(s) found in site '{site}'"
+ return False, "Login failed: invalid credentials or unreachable host", counts
+ counts["infrastructure"] = len(
+ await _fetch_devices(client, host, port, site, cookies)
+ )
+ if known_clients:
+ counts["known_clients"] = len(
+ await _fetch_known_clients(client, host, port, site, cookies)
+ )
+ if active_clients:
+ counts["active_clients"] = len(
+ await _fetch_clients(client, host, port, site, cookies)
+ )
+ return (
+ True,
+ f"Connected — {counts['infrastructure']} device(s) found in site '{site}'",
+ counts,
+ )
finally:
await client.aclose()
except httpx.ConnectError as exc:
- return False, f"Cannot reach {host}:{port} — {exc}"
+ return False, f"Cannot reach {host}:{port} — {exc}", counts
except Exception as exc:
- return False, str(exc)
+ return False, str(exc), counts
async def fetch_unifi_inventory(
diff --git a/backend/tests/test_unifi_service.py b/backend/tests/test_unifi_service.py
index 8f62dc9..e9324cd 100644
--- a/backend/tests/test_unifi_service.py
+++ b/backend/tests/test_unifi_service.py
@@ -117,7 +117,7 @@ def _self_hosted(devices: list, site: str = "default"):
async def test_login_falls_back_to_the_legacy_path() -> None:
ctx, factory = _patch(_self_hosted(_DEVICES))
with ctx:
- connected, message = await check_connection(
+ connected, message, _ = await check_connection(
"unifi.local", 8443, "default", "admin", "pw"
)
assert connected is True
@@ -144,7 +144,7 @@ async def test_bad_credentials_report_a_login_failure() -> None:
ctx, _ = _patch(handler)
with ctx:
- connected, message = await check_connection(
+ connected, message, _ = await check_connection(
"unifi.local", 8443, "default", "admin", "wrong"
)
assert connected is False
@@ -158,7 +158,7 @@ async def test_unknown_site_is_not_reported_as_connected() -> None:
"""Regression: a wrong site answered 401 and read as "Connected — 0 devices"."""
ctx, _ = _patch(_self_hosted(_DEVICES))
with ctx:
- connected, message = await check_connection(
+ connected, message, _ = await check_connection(
"unifi.local", 8443, "nosuchsite", "admin", "pw"
)
assert connected is False
@@ -177,7 +177,7 @@ async def test_an_empty_site_still_connects() -> None:
"""The other half of the regression: genuinely empty must stay a success."""
ctx, _ = _patch(_self_hosted([]))
with ctx:
- connected, message = await check_connection(
+ connected, message, _ = await check_connection(
"unifi.local", 8443, "default", "admin", "pw"
)
assert connected is True
@@ -327,3 +327,27 @@ async def test_a_client_without_a_mac_is_skipped() -> None:
from app.services.unifi_service import _normalize_client
assert _normalize_client({"name": "ghost"}) is None
+
+
+async def test_test_connection_counts_only_the_requested_sources() -> None:
+ ctx, factory = _patch(_full_controller())
+ with ctx:
+ connected, _msg, counts = await check_connection(
+ "unifi.local", 8443, "default", "admin", "pw", known_clients=True
+ )
+ assert connected is True
+ # Infrastructure always — it is the reachability check. stat/sta untouched.
+ assert counts == {"infrastructure": 3, "known_clients": 2}
+ assert not any("stat/sta" in p for p in (r.url.path for r in factory.requests))
+
+
+async def test_test_connection_counts_every_source_when_asked() -> None:
+ ctx, _ = _patch(_full_controller())
+ with ctx:
+ _c, _m, counts = await check_connection(
+ "unifi.local", 8443, "default", "admin", "pw",
+ known_clients=True, active_clients=True,
+ )
+ assert counts == {"infrastructure": 3, "known_clients": 2, "active_clients": 1}
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 7343616..d068a9f 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -28,6 +28,7 @@ import { SettingsModal } from '@/components/modals/SettingsModal'
import { ZigbeeImportModal } from '@/components/zigbee/ZigbeeImportModal'
import { ZwaveImportModal } from '@/components/zwave/ZwaveImportModal'
import { ProxmoxImportModal } from '@/components/proxmox/ProxmoxImportModal'
+import { UnifiImportModal } from '@/components/unifi/UnifiImportModal'
import { GroupRectModal, type GroupRectFormData } from '@/components/modals/GroupRectModal'
import { TextModal, type TextFormData } from '@/components/modals/TextModal'
import { ThemeModal } from '@/components/modals/ThemeModal'
@@ -158,6 +159,7 @@ export default function App() {
const [zigbeeImportOpen, setZigbeeImportOpen] = useState(false)
const [zwaveImportOpen, setZwaveImportOpen] = useState(false)
const [proxmoxImportOpen, setProxmoxImportOpen] = useState(false)
+ const [unifiImportOpen, setUnifiImportOpen] = useState(false)
// Declare handleSave before the Ctrl+S effect so it is in scope.
// Returns true on success, false on failure — the design-switch effect relies
@@ -1140,6 +1142,7 @@ export default function App() {
onAddText={() => setAddTextOpen(true)}
onScan={() => setScanConfigOpen(true)}
onZigbeeImport={() => setZigbeeImportOpen(true)}
+ onUnifiImport={() => setUnifiImportOpen(true)}
onZwaveImport={() => setZwaveImportOpen(true)}
onProxmoxImport={() => setProxmoxImportOpen(true)}
onSave={handleSave}
@@ -1325,6 +1328,16 @@ export default function App() {
/>
)}
+ {!STANDALONE && (
+ <UnifiImportModal
+ open={unifiImportOpen}
+ onClose={() => setUnifiImportOpen(false)}
+ // The UniFi import is synchronous and already reports its counts,
+ // so land the user on what it just created.
+ onInventoryImported={() => openInventoryModal()}
+ />
+ )}
+
{!STANDALONE && (
<ScanHistoryModal
open={scanHistoryOpen}
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index c8df312..17f1029 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -560,3 +560,63 @@ export const zwaveApi = {
api.post<ZwaveConfigData>('/zwave/config', data),
syncNow: () => api.post<ScanRunResult>('/zwave/sync-now'),
}
+
+export interface UnifiImportModes {
+ infrastructure: boolean
+ known_clients: boolean
+ active_clients: boolean
+}
+
+export interface UnifiConnection {
+ host: string
+ port: number
+ site: string
+ username?: string
+ password?: string
+ verify_tls?: boolean
+ modes?: UnifiImportModes
+}
+
+export interface UnifiConfigData {
+ host: string
+ port: number
+ site: string
+ verify_tls: boolean
+ sync_enabled: boolean
+ sync_interval: number
+ credentials_configured: boolean
+ modes: UnifiImportModes
+}
+
+export interface UnifiImportResult {
+ device_count: number
+ pending_created: number
+ pending_updated: number
+ infra_count: number
+ client_count: number
+}
+
+export const unifiApi = {
+ // `counts` holds a row count per source queried, so the import UI can show
+ // what a box would pull in before it is ticked.
+ testConnection: (data: UnifiConnection) =>
+ api.post<{
+ connected: boolean
+ message: string
+ counts: Partial<Record<keyof UnifiImportModes, number>>
+ }>('/unifi/test-connection', data),
+
+ importToPending: (data: UnifiConnection) =>
+ api.post<UnifiImportResult>('/unifi/import-pending', data),
+
+ getConfig: () => api.get<UnifiConfigData>('/unifi/config'),
+ // Only auto-sync activation and the import modes are persisted. Connection
+ // config (host/port/credentials/site) is env-only and never sent.
+ saveConfig: (data: {
+ sync_enabled: boolean
+ sync_interval: number
+ modes: UnifiImportModes
+ }) => api.post<UnifiConfigData>('/unifi/config', data),
+
+ syncNow: () => api.post<UnifiImportResult>('/unifi/sync-now'),
+}
diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsx
index 79ba176..ddfaaf8 100644
--- a/frontend/src/components/modals/DeviceInventoryModal.tsx
+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx
@@ -749,6 +749,13 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus
>
Proxmox
</button>
+ <button
+ onClick={() => setSourceFilter('unifi')}
+ className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'unifi' ? 'bg-[#0559c9]/20 text-[#0559c9]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
+ title="Imported from a UniFi controller — gear and clients"
+ >
+ UniFi
+ </button>
<button
onClick={() => setSourceFilter('rack')}
className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'rack' ? 'bg-[#39d353]/20 text-[#39d353]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}
diff --git a/frontend/src/components/panels/Sidebar.tsx b/frontend/src/components/panels/Sidebar.tsx
index c4e5983..b397584 100644
--- a/frontend/src/components/panels/Sidebar.tsx
+++ b/frontend/src/components/panels/Sidebar.tsx
@@ -1,5 +1,5 @@
import { useState, useCallback, useEffect } from 'react'
-import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, Square, Settings, LogOut, Network, RadioTower, Server, Type, PlusCircle, Pencil, Trash2, Rows3, BookOpen, Loader2 } from 'lucide-react'
+import { Plus, Save, ScanLine, ChevronLeft, ChevronRight, LayoutDashboard, Clock, Square, Settings, LogOut, Network, RadioTower, Server, Wifi, Type, PlusCircle, Pencil, Trash2, Rows3, BookOpen, Loader2 } from 'lucide-react'
import { Logo } from '@/components/ui/Logo'
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'
import { useCanvasStore } from '@/stores/canvasStore'
@@ -28,13 +28,14 @@ interface SidebarProps {
onZigbeeImport: () => void
onZwaveImport: () => void
onProxmoxImport: () => void
+ onUnifiImport: () => void
onSave: () => void
onOpenSettings: () => void
onOpenHistory: () => void
onOpenInventory: (deviceId?: string, status?: 'pending' | 'hidden') => void
}
-export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onZwaveImport, onProxmoxImport, onSave, onOpenSettings, onOpenHistory, onOpenInventory }: SidebarProps) {
+export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onZwaveImport, onProxmoxImport, onUnifiImport, onSave, onOpenSettings, onOpenHistory, onOpenInventory }: SidebarProps) {
const [collapsed, setCollapsed] = useState(false)
const logout = useAuthStore((s) => s.logout)
const { designs, activeDesignId, activeDesignType, setActiveDesign, addDesign, updateDesign, removeDesign } = useDesignStore()
@@ -316,6 +317,7 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
{!STANDALONE && !isRack && <SidebarItem icon={Network} label="Zigbee Import" collapsed={collapsed} onClick={onZigbeeImport} dataTour="zigbee-import" />}
{!STANDALONE && !isRack && <SidebarItem icon={RadioTower} label="Z-Wave Import" collapsed={collapsed} onClick={onZwaveImport} dataTour="zwave-import" />}
{!STANDALONE && !isRack && <SidebarItem icon={Server} label="Proxmox Import" collapsed={collapsed} onClick={onProxmoxImport} dataTour="proxmox-import" />}
+ {!STANDALONE && !isRack && <SidebarItem icon={Wifi} label="UniFi Import" collapsed={collapsed} onClick={onUnifiImport} dataTour="unifi-import" />}
<SidebarItem
icon={Save}
label={isRack ? 'Save Rack' : 'Save Canvas'}
diff --git a/frontend/src/components/unifi/UnifiImportModal.tsx b/frontend/src/components/unifi/UnifiImportModal.tsx
new file mode 100644
index 0000000..dc906c5
--- /dev/null
+++ b/frontend/src/components/unifi/UnifiImportModal.tsx
@@ -0,0 +1,298 @@
+import { useState } from 'react'
+import { Wifi, CheckCircle2, XCircle, Loader2, Download } from 'lucide-react'
+import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogFooter } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { unifiApi, type UnifiImportModes } from '@/api/client'
+import { toast } from 'sonner'
+
+interface UnifiImportModalProps {
+ open: boolean
+ onClose: () => void
+ onInventoryImported?: () => void
+}
+
+interface ConnectionForm {
+ host: string
+ port: string
+ site: string
+ username: string
+ password: string
+ verify_tls: boolean
+}
+
+const DEFAULT_FORM: ConnectionForm = {
+ host: '',
+ port: '8443',
+ site: 'default',
+ username: '',
+ password: '',
+ verify_tls: false,
+}
+
+const DEFAULT_MODES: UnifiImportModes = {
+ infrastructure: true,
+ known_clients: false,
+ active_clients: false,
+}
+
+/**
+ * The controller holds three inventories and they are not interchangeable, so
+ * each is its own opt-in rather than one "import everything" button.
+ */
+const SOURCES: {
+ key: keyof UnifiImportModes
+ label: string
+ endpoint: string
+ hint: string
+}[] = [
+ {
+ key: 'infrastructure',
+ label: 'Infrastructure',
+ endpoint: 'stat/device',
+ hint: 'Adopted APs, switches and gateways — with IP, model and firmware.',
+ },
+ {
+ key: 'known_clients',
+ label: 'Known clients',
+ endpoint: 'list/user',
+ hint: 'Every client the controller has ever recorded. No IP address, and long on a busy site.',
+ },
+ {
+ key: 'active_clients',
+ label: 'Active clients',
+ endpoint: 'stat/sta',
+ hint: 'Clients connected right now — carries the IP and the switch port or AP.',
+ },
+]
+
+export function UnifiImportModal({ open, onClose, onInventoryImported }: UnifiImportModalProps) {
+ const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)
+ const [modes, setModes] = useState<UnifiImportModes>(DEFAULT_MODES)
+ const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')
+ const [connectionMsg, setConnectionMsg] = useState('')
+ const [counts, setCounts] = useState<Record<string, number>>({})
+ const [importing, setImporting] = useState(false)
+
+ const anyMode = modes.infrastructure || modes.known_clients || modes.active_clients
+
+ const updateField = (field: keyof ConnectionForm, value: string) =>
+ setForm((f) => ({ ...f, [field]: value }))
+
+ const toggleMode = (key: keyof UnifiImportModes) =>
+ setModes((m) => ({ ...m, [key]: !m[key] }))
+
+ const buildPayload = () => ({
+ host: form.host.trim(),
+ port: Number(form.port) || 8443,
+ site: form.site.trim() || 'default',
+ // Blank falls back to the server env, like every other import.
+ username: form.username.trim() || undefined,
+ password: form.password || undefined,
+ verify_tls: form.verify_tls,
+ modes,
+ })
+
+ const handleClose = () => {
+ setForm(DEFAULT_FORM)
+ setModes(DEFAULT_MODES)
+ setConnectionStatus('idle')
+ setConnectionMsg('')
+ setCounts({})
+ onClose()
+ }
+
+ const handleTestConnection = async () => {
+ if (!form.host.trim()) { toast.error('Enter a controller host'); return }
+ setConnectionStatus('testing')
+ try {
+ const res = await unifiApi.testConnection(buildPayload())
+ setConnectionStatus(res.data.connected ? 'ok' : 'fail')
+ setConnectionMsg(res.data.message)
+ setCounts(res.data.counts || {})
+ } catch (e) {
+ setConnectionStatus('fail')
+ setConnectionMsg(e instanceof Error ? e.message : 'Connection failed')
+ setCounts({})
+ }
+ }
+
+ const handleImport = async () => {
+ if (!form.host.trim()) { toast.error('Enter a controller host'); return }
+ if (!anyMode) { toast.error('Select at least one source'); return }
+ setImporting(true)
+ try {
+ const res = await unifiApi.importToPending(buildPayload())
+ const { pending_created, pending_updated, infra_count, client_count } = res.data
+ toast.success(
+ `Imported ${infra_count} device(s) and ${client_count} client(s) — ` +
+ `${pending_created} new, ${pending_updated} updated`,
+ )
+ onInventoryImported?.()
+ handleClose()
+ } catch (e) {
+ toast.error(e instanceof Error ? e.message : 'UniFi import failed')
+ } finally {
+ setImporting(false)
+ }
+ }
+
+ return (
+ <Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
+ <DialogContent className="bg-[#161b22] border-border max-w-2xl max-h-[85vh] flex flex-col">
+ <DialogHeader>
+ <DialogTitle className="text-foreground flex items-center gap-2">
+ <Wifi size={16} className="text-[#0559c9]" />
+ UniFi Import
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="flex-1 overflow-y-auto space-y-4 py-2 min-h-0">
+ <div className="space-y-3">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
+ <div className="col-span-2 space-y-1">
+ <Label className="text-xs text-muted-foreground">Controller Host</Label>
+ <Input
+ value={form.host}
+ onChange={(e) => updateField('host', e.target.value)}
+ placeholder="192.168.1.x or unifi.local"
+ className="font-mono text-sm bg-[#0d1117] border-border"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label className="text-xs text-muted-foreground">Port</Label>
+ <Input
+ value={form.port}
+ onChange={(e) => updateField('port', e.target.value)}
+ placeholder="8443"
+ type="number"
+ className="font-mono text-sm bg-[#0d1117] border-border"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label className="text-xs text-muted-foreground">Site</Label>
+ <Input
+ value={form.site}
+ onChange={(e) => updateField('site', e.target.value)}
+ placeholder="default"
+ className="font-mono text-sm bg-[#0d1117] border-border"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label className="text-xs text-muted-foreground">Username (optional)</Label>
+ <Input
+ value={form.username}
+ onChange={(e) => updateField('username', e.target.value)}
+ placeholder="falls back to server env"
+ className="text-sm bg-[#0d1117] border-border"
+ />
+ </div>
+ <div className="space-y-1">
+ <Label className="text-xs text-muted-foreground">Password (optional)</Label>
+ <Input
+ value={form.password}
+ onChange={(e) => updateField('password', e.target.value)}
+ placeholder="••••••••"
+ type="password"
+ autoComplete="new-password"
+ className="text-sm bg-[#0d1117] border-border"
+ />
+ </div>
+ <div className="col-span-2 flex flex-wrap items-center gap-x-6 gap-y-2 pt-1">
+ <label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
+ <input
+ type="checkbox"
+ checked={form.verify_tls}
+ onChange={(e) => setForm((f) => ({ ...f, verify_tls: e.target.checked }))}
+ className="w-3 h-3 accent-[#0559c9] cursor-pointer"
+ />
+ Verify TLS certificate
+ <span className="text-muted-foreground/50">(off for a self-signed controller)</span>
+ </label>
+ </div>
+ </div>
+
+ {connectionStatus !== 'idle' && (
+ <div className={`flex items-center gap-1.5 text-xs px-2 py-1.5 rounded-md border ${
+ connectionStatus === 'ok'
+ ? 'bg-[#39d353]/10 border-[#39d353]/30 text-[#39d353]'
+ : connectionStatus === 'fail'
+ ? 'bg-[#f85149]/10 border-[#f85149]/30 text-[#f85149]'
+ : 'bg-[#e3b341]/10 border-[#e3b341]/30 text-[#e3b341]'
+ }`}>
+ {connectionStatus === 'testing' && <Loader2 size={12} className="animate-spin" />}
+ {connectionStatus === 'ok' && <CheckCircle2 size={12} />}
+ {connectionStatus === 'fail' && <XCircle size={12} />}
+ <span>{connectionStatus === 'testing' ? 'Testing…' : connectionMsg}</span>
+ </div>
+ )}
+
+ <div className="space-y-2 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5">
+ <span className="block text-xs text-muted-foreground">Import from</span>
+ <div className="space-y-2">
+ {SOURCES.map((s) => (
+ <label
+ key={s.key}
+ className="flex items-start gap-2 text-xs cursor-pointer text-foreground"
+ >
+ <input
+ type="checkbox"
+ checked={modes[s.key]}
+ onChange={() => toggleMode(s.key)}
+ aria-label={s.label}
+ className="w-3 h-3 mt-0.5 accent-[#0559c9] cursor-pointer"
+ />
+ <span className="min-w-0">
+ <span className="flex flex-wrap items-center gap-x-2">
+ {s.label}
+ <code className="font-mono text-[10px] text-muted-foreground/70">{s.endpoint}</code>
+ {counts[s.key] !== undefined && (
+ <span className="text-[#0559c9]">{counts[s.key]} found</span>
+ )}
+ </span>
+ <span className="block text-muted-foreground/60">{s.hint}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ {!anyMode && (
+ <span className="block text-xs text-[#e3b341]">Select at least one source.</span>
+ )}
+ </div>
+
+ <p className="text-xs text-muted-foreground/60">
+ Everything lands in the device inventory as pending, to approve onto a canvas
+ like any other discovery.
+ </p>
+ </div>
+ </div>
+
+ <DialogFooter className="gap-2 shrink-0 pt-2 border-t border-border">
+ <Button variant="ghost" onClick={handleClose}>Cancel</Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="gap-1.5 text-muted-foreground hover:text-foreground border border-border hover:bg-[#21262d]"
+ onClick={handleTestConnection}
+ disabled={connectionStatus === 'testing' || importing}
+ >
+ {connectionStatus === 'testing'
+ ? <Loader2 size={13} className="animate-spin" />
+ : <CheckCircle2 size={13} />}
+ Test Connection
+ </Button>
+ <Button
+ onClick={handleImport}
+ disabled={!anyMode || importing}
+ style={{ background: '#0559c9', color: '#ffffff' }}
+ className="gap-1.5"
+ >
+ {importing ? <Loader2 size={13} className="animate-spin" /> : <Download size={13} />}
+ Import to Inventory
+ </Button>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx b/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx
new file mode 100644
index 0000000..96d4568
--- /dev/null
+++ b/frontend/src/components/unifi/__tests__/UnifiImportModal.test.tsx
@@ -0,0 +1,167 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { UnifiImportModal } from '../UnifiImportModal'
+
+vi.mock('@/api/client', () => ({
+ unifiApi: {
+ testConnection: vi.fn(),
+ importToPending: vi.fn(),
+ },
+}))
+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
+
+import { unifiApi } from '@/api/client'
+import { toast } from 'sonner'
+
+const defaultProps = {
+ open: true,
+ onClose: vi.fn(),
+}
+
+const importResult = {
+ data: {
+ device_count: 5,
+ pending_created: 4,
+ pending_updated: 1,
+ infra_count: 4,
+ client_count: 1,
+ },
+}
+
+function typeHost(value = 'unifi.local') {
+ fireEvent.change(screen.getByPlaceholderText('192.168.1.x or unifi.local'), {
+ target: { value },
+ })
+}
+
+describe('UnifiImportModal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ vi.mocked(unifiApi.importToPending).mockResolvedValue(importResult as never)
+ })
+
+ it('imports infrastructure only by default', async () => {
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
+
+ await waitFor(() => expect(unifiApi.importToPending).toHaveBeenCalled())
+ const payload = vi.mocked(unifiApi.importToPending).mock.calls[0][0]
+ expect(payload.modes).toEqual({
+ infrastructure: true,
+ known_clients: false,
+ active_clients: false,
+ })
+ expect(payload.site).toBe('default')
+ expect(payload.port).toBe(8443)
+ })
+
+ it('sends the sources the user ticked', async () => {
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByLabelText('Known clients'))
+ fireEvent.click(screen.getByLabelText('Active clients'))
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
+
+ await waitFor(() => expect(unifiApi.importToPending).toHaveBeenCalled())
+ expect(vi.mocked(unifiApi.importToPending).mock.calls[0][0].modes).toEqual({
+ infrastructure: true,
+ known_clients: true,
+ active_clients: true,
+ })
+ })
+
+ it('blocks the import when every source is unticked', () => {
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByLabelText('Infrastructure'))
+
+ expect(screen.getByRole('button', { name: /import to inventory/i })).toBeDisabled()
+ expect(screen.getByText(/select at least one source/i)).toBeInTheDocument()
+ expect(unifiApi.importToPending).not.toHaveBeenCalled()
+ })
+
+ it('shows the per-source row counts a test returned', async () => {
+ vi.mocked(unifiApi.testConnection).mockResolvedValue({
+ data: {
+ connected: true,
+ message: "Connected — 4 device(s) found in site 'default'",
+ counts: { infrastructure: 4, known_clients: 412 },
+ },
+ } as never)
+
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByLabelText('Known clients'))
+ fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
+
+ await waitFor(() => expect(screen.getByText('412 found')).toBeInTheDocument())
+ expect(screen.getByText('4 found')).toBeInTheDocument()
+ // The untested source stays blank rather than showing a stale zero.
+ expect(screen.queryByText('0 found')).not.toBeInTheDocument()
+ })
+
+ it('asks the test for the counts of the ticked sources only', async () => {
+ vi.mocked(unifiApi.testConnection).mockResolvedValue({
+ data: { connected: true, message: 'ok', counts: {} },
+ } as never)
+
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByLabelText('Active clients'))
+ fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
+
+ await waitFor(() => expect(unifiApi.testConnection).toHaveBeenCalled())
+ expect(vi.mocked(unifiApi.testConnection).mock.calls[0][0].modes).toEqual({
+ infrastructure: true,
+ known_clients: false,
+ active_clients: true,
+ })
+ })
+
+ it('reports the connection failure instead of a success', async () => {
+ vi.mocked(unifiApi.testConnection).mockResolvedValue({
+ data: {
+ connected: false,
+ message: 'UniFi device endpoint unavailable (/api/s/nope/stat/device → HTTP 401)',
+ counts: {},
+ },
+ } as never)
+
+ render(<UnifiImportModal {...defaultProps} />)
+ typeHost()
+ fireEvent.click(screen.getByRole('button', { name: /test connection/i }))
+
+ await waitFor(() =>
+ expect(screen.getByText(/endpoint unavailable/i)).toBeInTheDocument(),
+ )
+ })
+
+ it('reports what the import created and closes', async () => {
+ const onClose = vi.fn()
+ const onInventoryImported = vi.fn()
+ render(
+ <UnifiImportModal
+ {...defaultProps}
+ onClose={onClose}
+ onInventoryImported={onInventoryImported}
+ />,
+ )
+ typeHost()
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
+
+ await waitFor(() => expect(onInventoryImported).toHaveBeenCalled())
+ expect(toast.success).toHaveBeenCalledWith(
+ expect.stringContaining('4 device(s) and 1 client(s)'),
+ )
+ expect(onClose).toHaveBeenCalled()
+ })
+
+ it('refuses to call the API without a host', () => {
+ render(<UnifiImportModal {...defaultProps} />)
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
+
+ expect(unifiApi.importToPending).not.toHaveBeenCalled()
+ expect(toast.error).toHaveBeenCalledWith('Enter a controller host')
+ })
+})
diff --git a/frontend/src/utils/__tests__/deviceSources.test.ts b/frontend/src/utils/__tests__/deviceSources.test.ts
index 6b3b70c..25c0e36 100644
--- a/frontend/src/utils/__tests__/deviceSources.test.ts
+++ b/frontend/src/utils/__tests__/deviceSources.test.ts
@@ -24,6 +24,18 @@ describe('sourceBuckets', () => {
expect([...buckets].sort()).toEqual(['ip', 'proxmox'])
})
+ it('buckets UniFi infrastructure and clients together', () => {
+ // Both must be recognised explicitly: the fallback branch sends anything
+ // unknown to the ip bucket, which would hide them behind the IP filter.
+ expect([...sourceBuckets(device({ discovery_sources: ['unifi'] }))]).toEqual(['unifi'])
+ expect([...sourceBuckets(device({ discovery_sources: ['unifi-client'] }))]).toEqual(['unifi'])
+ })
+
+ it('keeps both sources for a host seen by an IP scan and by UniFi', () => {
+ const buckets = sourceBuckets(device({ discovery_sources: ['arp', 'unifi-client'] }))
+ expect([...buckets].sort()).toEqual(['ip', 'unifi'])
+ })
+
it('maps arp and mdns to the single ip bucket', () => {
expect([...sourceBuckets(device({ discovery_sources: ['arp'] }))]).toEqual(['ip'])
expect([...sourceBuckets(device({ discovery_sources: ['mdns'] }))]).toEqual(['ip'])
diff --git a/frontend/src/utils/deviceSources.ts b/frontend/src/utils/deviceSources.ts
index 970f94b..2aa67d4 100644
--- a/frontend/src/utils/deviceSources.ts
+++ b/frontend/src/utils/deviceSources.ts
@@ -7,12 +7,13 @@
*/
import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
-export type SourceBucket = 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'rack' | 'canvas'
+export type SourceBucket = 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unifi' | 'rack' | 'canvas'
export const SOURCE_META: Record<SourceBucket, { color: string; label: string }> = {
zigbee: { color: '#00d4ff', label: 'ZIGBEE' },
zwave: { color: '#ff6e00', label: 'Z-WAVE' },
proxmox: { color: '#e57000', label: 'PROXMOX' },
+ unifi: { color: '#0559c9', label: 'UNIFI' },
ip: { color: '#a855f7', label: 'IP' },
rack: { color: '#39d353', label: 'RACK' },
// Documented straight on a canvas — no scan ever saw it.
@@ -20,7 +21,7 @@ export const SOURCE_META: Record<SourceBucket, { color: string; label: string }>
}
// Stable badge order (IP first — it's the primary discovery path).
-const SOURCE_ORDER: SourceBucket[] = ['ip', 'proxmox', 'zigbee', 'zwave', 'rack', 'canvas']
+const SOURCE_ORDER: SourceBucket[] = ['ip', 'proxmox', 'unifi', 'zigbee', 'zwave', 'rack', 'canvas']
/** Every source bucket that has observed this device. A device found by both an
* IP scan and a Proxmox import returns {ip, proxmox}. */
@@ -33,6 +34,9 @@ export function sourceBuckets(d: InventoryEntry): Set<SourceBucket> {
if (s === 'zwave') buckets.add('zwave')
else if (s === 'zigbee') buckets.add('zigbee')
else if (s === 'proxmox') buckets.add('proxmox')
+ // UniFi infrastructure ('unifi') and clients ('unifi-client') share one
+ // bucket — the type filter already separates ap/switch/router from hosts.
+ else if (s === 'unifi' || s === 'unifi-client') buckets.add('unifi')
// Created from a rack canvas: inventory gear that never lands on a
// logical canvas.
else if (s === 'rack') buckets.add('rack')