Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(unraid): add Unraid server import for vms and containers (#556)
JSe0208ea49284
diff --git a/.env.example b/.env.exampleindex 4740b63..fc24fb7 100644--- a/.env.example+++ b/.env.example@@ -95,6 +95,15 @@ MCP_SERVICE_KEY=svc_changeme# PROXMOX_PORT=8006# PROXMOX_VERIFY_TLS=true # set false only for self-signed certs+# Unraid import (Docker containers and VMs) -- Unraid 7.2+ API (Unraid Connect plugin before). Create a key under+# Settings > Management Access > API Keys with read access to Docker, VMs and Info.+# Required only for auto-sync; one-off imports can pass the key in the dialog.+# UNRAID_API_KEY=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx+# UNRAID_HOST=192.168.1.20+# UNRAID_USE_HTTPS=false # true when Unraid's "Use SSL/TLS" is on+# UNRAID_PORT=80 # defaults to 80, or 443 with HTTPS+# UNRAID_VERIFY_TLS=false # used with HTTPS; true once the server has a trusted cert+# Zigbee2MQTT auto-sync — pull the mesh from an MQTT broker on a schedule.# MQTT credentials are secrets: kept in memory only, never written to disk by# the app, never returned by any API. Manual imports (the Zigbee dialog) arediff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.pyindex 598a302..767fcac 100644--- a/backend/app/api/routes/scan.py+++ b/backend/app/api/routes/scan.py@@ -661,12 +661,13 @@ async def list_proxmox_children(db: AsyncSession = Depends(get_db),_: str = Depends(get_current_user),) -> list[InventoryDevice]:- """Inventory rows for the guests a Proxmox host runs.+ """Inventory rows for the guests a Proxmox host (or Unraid server) runs.- The Proxmox import records host -> guest as a ``device_inventory_links`` row- with ``discovery_source == "proxmox"``, keyed by IEEE. This resolves those- targets back to inventory rows so the UI can offer "add the children too"- when a host is placed on a canvas. Empty for anything that is not a host.+ The Proxmox and Unraid imports record host -> guest/container as a+ ``device_inventory_links`` row with ``discovery_source`` "proxmox" or+ "unraid", keyed by IEEE. This resolves those targets back to inventory rows+ so the UI can offer "add the children too" when a host is placed on a+ canvas. Empty for anything that is not a host."""device = await db.get(InventoryDevice, device_id)if device is None:@@ -678,7 +679,7 @@ async def list_proxmox_children(await db.execute(select(InventoryDeviceLink.target_ieee).where(InventoryDeviceLink.source_ieee == device.ieee_address,- InventoryDeviceLink.discovery_source == "proxmox",+ InventoryDeviceLink.discovery_source.in_(("proxmox", "unraid")),)))@@ -1159,9 +1160,10 @@ async def _resolve_pending_links_for_ieee(# '-t' target id does not resolve here and RF falls back to the top# handle, so never emit one.# proxmox → 'virtual' host→guest, vertical (bottom → top)+ # unraid -> 'virtual' host->container, same shape# proxmox_cluster → 'cluster' host↔host, horizontal (right → left)# anything else → 'iot' mesh link, vertical- if link.discovery_source == "proxmox":+ if link.discovery_source in ("proxmox", "unraid"):edge_type, src_handle, tgt_handle = "virtual", "bottom", "top"elif link.discovery_source == "proxmox_cluster":edge_type, src_handle, tgt_handle = "cluster", "right", "left"diff --git a/backend/app/api/routes/unraid.py b/backend/app/api/routes/unraid.pynew file mode 100644index 0000000..039a914--- /dev/null+++ b/backend/app/api/routes/unraid.py@@ -0,0 +1,479 @@+"""FastAPI router for the Unraid import (containers and VMs) + auto-sync config.++Fetches the server, its containers and VMs from the Unraid GraphQL API and upserts+them into the Device Inventory (same review->approve flow as the Proxmox import).++Credentials: the API key comes from the request body when provided, else falls+back to the server-configured env key - only for the configured host and port,+and never with TLS verification off when the server keeps it on. The key is+never persisted by the app and never returned by any endpoint.+"""++import logging+from datetime import datetime, timezone+from typing import Any++from fastapi import APIRouter, BackgroundTasks, Depends, HTTPException+from sqlalchemy import delete as sa_delete+from sqlalchemy import select+from sqlalchemy.ext.asyncio import AsyncSession++from app.api.deps import get_current_user+from app.core.config import settings+from app.core.scheduler import reschedule_unraid_sync, set_unraid_sync_enabled+from app.db.database import AsyncSessionLocal, get_db+from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun+from app.schemas.scan import ScanRunResponse+from app.schemas.unraid import (+ UnraidConfig,+ UnraidConnectionRequest,+ UnraidEdgeOut,+ UnraidImportPendingResponse,+ UnraidImportResponse,+ UnraidNodeOut,+ UnraidSyncConfig,+ UnraidTestConnectionResponse,+)+from app.services.discovery_sources import add_source+from app.services.inventory_sync import attach_device_ids, merge_services+from app.services.node_dedupe import dedupe_nodes_by_device+from app.services.unraid_service import (+ build_unraid_properties,+ fetch_unraid_inventory,+ merge_unraid_properties,+ test_unraid_connection,+)++logger = logging.getLogger(__name__)+router = APIRouter()++_UNRAID_SOURCE = "unraid"+_UNRAID_IEEE_PREFIX = "unraid-"+# Synthetic ieee prefixes an Unraid import may take over on a row it matched by+# MAC: its own (a renamed container) and UniFi's, which re-finds rows by MAC.+_ADOPTABLE_PREFIXES = (_UNRAID_IEEE_PREFIX, "unifi-")+++def _resolve_api_key(payload: UnraidConnectionRequest) -> str:+ """The key from the request, else the env key for the configured endpoint only."""+ if payload.api_key:+ return payload.api_key++ configured_host = settings.unraid_host.strip().rstrip(".").lower()+ request_host = payload.host.strip().rstrip(".").lower()+ if (+ not configured_host+ or request_host != configured_host+ or payload.effective_port != settings.unraid_effective_port+ ):+ raise HTTPException(+ status_code=400,+ detail="Custom Unraid hosts require an explicit API key",+ )+ # Never send the env key in clear text to a server configured for HTTPS.+ if settings.unraid_use_https and not payload.use_https:+ raise HTTPException(+ status_code=400,+ detail="The server-configured Unraid API key requires HTTPS",+ )+ if settings.unraid_verify_tls and not payload.verify_tls:+ raise HTTPException(+ status_code=400,+ detail="The server-configured Unraid API key requires TLS verification",+ )+ if not settings.unraid_api_key:+ raise HTTPException(+ status_code=400,+ detail="No Unraid API key provided and none configured on the server.",+ )+ return settings.unraid_api_key+++def _keep(nodes_raw: list[dict[str, Any]], include_offline: bool) -> list[dict[str, Any]]:+ """Drop stopped containers and VMs unless they are wanted. The host always stays."""+ if include_offline:+ return nodes_raw+ return [n for n in nodes_raw if n.get("type") == "docker_host" or n.get("status") == "online"]+++def _edges_between(edges_raw: list[dict[str, Any]], nodes: list[dict[str, Any]]) -> list[dict[str, Any]]:+ ids = {n["id"] for n in nodes}+ return [e for e in edges_raw if e.get("source") in ids and e.get("target") in ids]++[email protected]("/test-connection", response_model=UnraidTestConnectionResponse)+async def test_connection_endpoint(+ payload: UnraidConnectionRequest,+ _: str = Depends(get_current_user),+) -> UnraidTestConnectionResponse:+ """Validate host reachability + API key before importing."""+ api_key = _resolve_api_key(payload)+ connected, message = await test_unraid_connection(+ host=payload.host,+ port=payload.effective_port,+ api_key=api_key,+ verify_tls=payload.verify_tls,+ use_https=payload.use_https,+ )+ return UnraidTestConnectionResponse(connected=connected, message=message)++[email protected]("/import", response_model=UnraidImportResponse)+async def import_unraid(+ payload: UnraidConnectionRequest,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> UnraidImportResponse:+ """Fetch the containers and VMs and return nodes + edges ready for canvas drop.++ Like the Proxmox import, everything returned also lands in the Device+ Inventory. Stopped containers and VMs are left out of both unless+ ``include_offline`` is set.+ """+ api_key = _resolve_api_key(payload)+ try:+ nodes_raw, edges_raw, notice = await fetch_unraid_inventory(+ host=payload.host,+ port=payload.effective_port,+ api_key=api_key,+ verify_tls=payload.verify_tls,+ use_https=payload.use_https,+ )+ except ConnectionError as exc:+ raise HTTPException(status_code=502, detail=str(exc)) from exc+ except ValueError as exc:+ raise HTTPException(status_code=422, detail=str(exc)) from exc+ except Exception as exc:+ logger.exception("Unexpected error during Unraid import")+ raise HTTPException(status_code=500, detail="Unexpected error during Unraid import") from exc++ stored = _keep(nodes_raw, payload.include_offline)+ await _persist_pending_import(db, stored, _edges_between(edges_raw, stored))++ drawn = await attach_device_ids(db, stored)+ drawn = await _with_row_lists(db, drawn)+ nodes = [UnraidNodeOut(**n) for n in drawn]+ edges = [UnraidEdgeOut(**e) for e in _edges_between(edges_raw, drawn)]+ return UnraidImportResponse(nodes=nodes, edges=edges, device_count=len(nodes), notice=notice)+++async def _with_row_lists(db: AsyncSession, nodes: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Carry each row's services and properties on the node drawing it.++ A freshly dropped node has no baseline to diff against, so its first canvas+ save sends every list as an edit and replaces the row's. Without these the+ save would erase the web UI service and the properties the import just wrote.+ """+ out: list[dict[str, Any]] = []+ for n in nodes:+ row = await db.get(InventoryDevice, n["device_id"]) if n.get("device_id") else None+ if row is None:+ out.append(n)+ continue+ out.append({**n, "services": list(row.services or []), "properties": list(row.properties or [])})+ return out++[email protected]("/import-pending", response_model=ScanRunResponse)+async def import_unraid_to_pending(+ payload: UnraidConnectionRequest,+ background_tasks: BackgroundTasks,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> ScanRun:+ """Queue an Unraid inventory import as a background scan run (kind=unraid)."""+ api_key = _resolve_api_key(payload)+ run = ScanRun(+ status="running",+ kind="unraid",+ ranges=[f"{payload.host}:{payload.effective_port}"],+ )+ db.add(run)+ await db.commit()+ await db.refresh(run)+ background_tasks.add_task(+ _background_unraid_import,+ run.id,+ payload.host,+ payload.effective_port,+ api_key,+ payload.verify_tls,+ payload.use_https,+ payload.include_offline,+ )+ return run++[email protected]("/sync-now", response_model=ScanRunResponse)+async def sync_unraid_now(+ background_tasks: BackgroundTasks,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> ScanRun:+ """Trigger an immediate Unraid sync using the server env config."""+ if not (settings.unraid_host and settings.unraid_api_key):+ raise HTTPException(+ status_code=400,+ detail="Cannot sync: no Unraid host/API key configured on the server.",+ )+ run = ScanRun(+ status="running",+ kind="unraid",+ ranges=[f"{settings.unraid_host}:{settings.unraid_effective_port}"],+ )+ db.add(run)+ await db.commit()+ await db.refresh(run)+ background_tasks.add_task(+ _background_unraid_import,+ run.id,+ settings.unraid_host,+ settings.unraid_effective_port,+ settings.unraid_api_key,+ settings.unraid_verify_tls,+ settings.unraid_use_https,+ settings.unraid_sync_include_offline,+ )+ return run+++async def _background_unraid_import(+ run_id: str,+ host: str,+ port: int,+ api_key: str,+ verify_tls: bool,+ use_https: bool,+ include_offline: bool,+) -> None:+ async with AsyncSessionLocal() as db:+ try:+ nodes_raw, edges_raw, notice = await fetch_unraid_inventory(+ host=host,+ port=port,+ api_key=api_key,+ verify_tls=verify_tls,+ use_https=use_https,+ )+ stored = _keep(nodes_raw, include_offline)+ result = await _persist_pending_import(db, stored, _edges_between(edges_raw, stored))+ run = await db.get(ScanRun, run_id)+ if run:+ run.status = "done"+ run.devices_found = result.device_count+ run.finished_at = datetime.now(timezone.utc)+ # Non-fatal, like the Proxmox guest-visibility advisory: the run+ # is done, the UI shows it as a warning.+ run.error = notice+ await db.commit()+ from app.api.routes.status import broadcast_scan_update+ await broadcast_scan_update(run_id=run_id, devices_found=result.device_count)+ except Exception as exc:+ logger.exception("Unraid import %s failed", run_id)+ await db.rollback()+ run = await db.get(ScanRun, run_id)+ if run:+ run.status = "error"+ run.error = str(exc)[:500]+ run.finished_at = datetime.now(timezone.utc)+ await db.commit()+++async def _persist_pending_import(+ db: AsyncSession,+ nodes_raw: list[dict[str, Any]],+ edges_raw: list[dict[str, Any]],+) -> UnraidImportPendingResponse:+ """Upsert the host, containers and VMs into device_inventory, replace the host's links.++ Update-in-place only: nothing is deleted, hidden rows stay hidden, and a row+ approved earlier but drawn on no canvas any more is revived to pending.+ """+ await dedupe_nodes_by_device(db)++ pending_created = 0+ pending_updated = 0+ for n in nodes_raw:+ ieee = n.get("ieee_address")+ if not ieee:+ continue+ props = build_unraid_properties(n)+ row = await _find_existing(db, ieee, n.get("ip"), n.get("mac"))+ if row is None:+ db.add(_new_row(ieee, n, props))+ pending_created += 1+ continue+ drawn = (+ await db.execute(select(Node.id).where(Node.device_id == row.id).limit(1))+ ).scalar_one_or_none() is not None+ _refresh_row(row, ieee, n, props)+ if row.status == "approved" and not drawn:+ row.status = "pending"+ pending_updated += 1++ links_recorded = await _replace_links(db, nodes_raw, edges_raw)+ await db.commit()+ return UnraidImportPendingResponse(+ pending_created=pending_created,+ pending_updated=pending_updated,+ links_recorded=links_recorded,+ device_count=len(nodes_raw),+ )+++async def _find_existing(+ db: AsyncSession, ieee: str, ip: str | None, mac: str | None+) -> InventoryDevice | None:+ """The inventory row this host/container *is*, in precedence order.++ 1. The synthetic ``ieee_address``.+ 2. A row holding both the IP and the MAC.+ 3. An unclaimed row (no ieee) holding the IP - a device an IP scan found.+ 4. A row holding the MAC.++ IP+MAC goes before either alone because an ipvlan container answers ARP+ with the host's MAC: a scan files it as its own IP with the host's MAC, and+ a MAC-only match would merge the host into that container's row.+ Oldest row wins at each step, so a re-import is stable.+ """+ exact = (+ await db.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == ieee))+ ).scalars().first()+ if exact is not None:+ return exact++ candidates: list[list[Any]] = []+ if ip and mac:+ candidates.append([InventoryDevice.ip == ip, InventoryDevice.mac == mac])+ if ip:+ candidates.append([InventoryDevice.ip == ip, InventoryDevice.ieee_address.is_(None)])+ if mac:+ candidates.append([InventoryDevice.mac == mac])+ for where in candidates:+ row = (+ await db.execute(+ select(InventoryDevice)+ .where(*where)+ .order_by(InventoryDevice.discovered_at, InventoryDevice.id)+ )+ ).scalars().first()+ if row is not None:+ return row+ return None+++def _new_row(ieee: str, n: dict[str, Any], props: list[dict[str, Any]]) -> InventoryDevice:+ return InventoryDevice(+ ieee_address=ieee,+ ip=n.get("ip"),+ mac=n.get("mac"),+ hostname=n.get("hostname"),+ friendly_name=n.get("label"),+ suggested_type=n.get("type"),+ vendor=n.get("vendor"),+ model=n.get("model"),+ os=n.get("os_version"),+ cpu_count=n.get("cpu_count"),+ cpu_model=n.get("cpu_model"),+ services=list(n.get("services") or []),+ properties=props,+ status="pending",+ discovery_source=_UNRAID_SOURCE,+ discovery_sources=[_UNRAID_SOURCE],+ )+++def _refresh_row(row: InventoryDevice, ieee: str, n: dict[str, Any], props: list[dict[str, Any]]) -> None:+ row.discovery_sources = add_source(+ add_source(row.discovery_sources, row.discovery_source), _UNRAID_SOURCE+ )+ if not row.ieee_address or row.ieee_address.startswith(_ADOPTABLE_PREFIXES):+ row.ieee_address = ieee+ row.ip = n.get("ip") or row.ip+ row.mac = row.mac or n.get("mac")+ row.hostname = n.get("hostname") or row.hostname+ row.friendly_name = n.get("label") or row.friendly_name+ row.suggested_type = n.get("type") or row.suggested_type+ row.vendor = n.get("vendor") or row.vendor+ row.model = n.get("model") or row.model+ row.os = n.get("os_version") or row.os+ row.cpu_count = row.cpu_count or n.get("cpu_count")+ row.cpu_model = row.cpu_model or n.get("cpu_model")+ row.properties = merge_unraid_properties(list(row.properties or []), props)+ # discovered=True: refresh the address, keep a name or icon the user set.+ row.services = merge_services(row.services, n.get("services"), discovered=True)+++async def _replace_links(+ db: AsyncSession,+ nodes_raw: list[dict[str, Any]],+ edges_raw: list[dict[str, Any]],+) -> int:+ """Replace this host's host->container links with the fresh set.++ Scoped to the imported host so a second Unraid server keeps its own links.+ """+ hosts = [n["ieee_address"] for n in nodes_raw if n.get("type") == "docker_host"]+ if hosts:+ await db.execute(+ sa_delete(InventoryDeviceLink).where(+ InventoryDeviceLink.discovery_source == _UNRAID_SOURCE,+ InventoryDeviceLink.source_ieee.in_(hosts),+ )+ )+ recorded = 0+ seen: set[tuple[str, str]] = set()+ for e in edges_raw:+ src, tgt = e.get("source"), e.get("target")+ if not src or not tgt or (src, tgt) in seen:+ continue+ seen.add((src, tgt))+ db.add(InventoryDeviceLink(source_ieee=src, target_ieee=tgt, discovery_source=_UNRAID_SOURCE))+ recorded += 1+ return recorded++[email protected]("/config", response_model=UnraidConfig)+async def get_unraid_config(_: str = Depends(get_current_user)) -> UnraidConfig:+ """Return non-secret Unraid config. Never includes the API key."""+ return UnraidConfig(+ host=settings.unraid_host,+ port=settings.unraid_effective_port,+ use_https=settings.unraid_use_https,+ verify_tls=settings.unraid_verify_tls,+ sync_enabled=settings.unraid_sync_enabled,+ sync_interval=settings.unraid_sync_interval,+ include_offline=settings.unraid_sync_include_offline,+ api_key_configured=bool(settings.unraid_api_key),+ )++[email protected]("/config", response_model=UnraidConfig)+async def save_unraid_config(+ payload: UnraidSyncConfig,+ _: str = Depends(get_current_user),+) -> UnraidConfig:+ """Persist the auto-sync activation and apply it live.++ Connection settings (host, port, API key, use_https, verify_tls) are env-only and are+ never accepted or persisted here.+ """+ if payload.sync_enabled and not (settings.unraid_host and settings.unraid_api_key):+ raise HTTPException(+ status_code=400,+ detail="Cannot enable auto-sync: no Unraid host/API key configured in the server env.",+ )+ try:+ settings.unraid_sync_enabled = payload.sync_enabled+ settings.unraid_sync_interval = payload.sync_interval+ settings.unraid_sync_include_offline = payload.include_offline+ settings.save_overrides()+ set_unraid_sync_enabled(payload.sync_enabled)+ if payload.sync_enabled:+ reschedule_unraid_sync(payload.sync_interval)+ except HTTPException:+ raise+ except Exception as exc:+ raise HTTPException(status_code=500, detail=str(exc)) from exc++ return await get_unraid_config()diff --git a/backend/app/core/config.py b/backend/app/core/config.pyindex d6400e8..66a2843 100644--- a/backend/app/core/config.py+++ b/backend/app/core/config.py@@ -226,6 +226,21 @@ class Settings(BaseSettings):proxmox_sync_enabled: bool = Falseproxmox_sync_interval: int = 3600 # seconds (floor 300 enforced on write)+ # Unraid import (Docker containers). Same rules as Proxmox: the API key is a+ # credential -> env/.env ONLY, never persisted by the app and never returned+ # by the API. Connection config is env-only; only the auto-sync activation+ # is persisted.+ unraid_api_key: str = ""+ unraid_host: str = ""+ # Unraid serves plain HTTP unless "Use SSL/TLS" is turned on in its settings.+ unraid_use_https: bool = False+ unraid_port: int | None = None # None = 443 for HTTPS, 80 for HTTP+ unraid_verify_tls: bool = False # Unraid's own certificate is self-signed+ unraid_sync_enabled: bool = False+ unraid_sync_interval: int = 3600 # seconds (floor 300 enforced on write)+ # Import stopped containers on auto-sync / sync-now too.+ unraid_sync_include_offline: bool = True+# Zigbee2MQTT auto-sync import.# MQTT credentials are secrets → env/.env ONLY, never persisted by the app to# scan_config.json and never returned by the API. Only the auto-sync@@ -291,6 +306,11 @@ class Settings(BaseSettings):return parsed.hostname or self.unifi_urlreturn self.unifi_host+ @property+ def unraid_effective_port(self) -> int:+ """UNRAID_PORT if set, else the default port of the configured scheme."""+ return self.unraid_port or (443 if self.unraid_use_https else 80)+@propertydef unifi_effective_port(self) -> int:"""Return port from UNIFI_URL if set, else UNIFI_PORT."""@@ -335,6 +355,13 @@ class Settings(BaseSettings):self.proxmox_sync_enabled = bool(data["proxmox_sync_enabled"])if "proxmox_sync_interval" in data:self.proxmox_sync_interval = int(data["proxmox_sync_interval"])+ # Unraid: auto-sync activation only, same reason as Proxmox.+ if "unraid_sync_enabled" in data:+ self.unraid_sync_enabled = bool(data["unraid_sync_enabled"])+ if "unraid_sync_interval" in data:+ self.unraid_sync_interval = int(data["unraid_sync_interval"])+ if "unraid_sync_include_offline" in data:+ self.unraid_sync_include_offline = bool(data["unraid_sync_include_offline"])# Zigbee/Z-Wave: only the auto-sync activation is persisted. MQTT# connection config (host, port, credentials, topic, tls) is env-only# by design — never read from or written to this file.@@ -378,6 +405,11 @@ class Settings(BaseSettings):# be written to disk — that is the single source of truth."proxmox_sync_enabled": self.proxmox_sync_enabled,"proxmox_sync_interval": self.proxmox_sync_interval,+ # Unraid: only the auto-sync activation. Host/port/key/verify_tls+ # are env-only.+ "unraid_sync_enabled": self.unraid_sync_enabled,+ "unraid_sync_interval": self.unraid_sync_interval,+ "unraid_sync_include_offline": self.unraid_sync_include_offline,# Zigbee/Z-Wave: only the auto-sync activation is persisted. MQTT# connection config (host/port/credentials/topic/tls) is env-only."zigbee_sync_enabled": self.zigbee_sync_enabled,diff --git a/backend/app/core/scheduler.py b/backend/app/core/scheduler.pyindex 9da5625..c18148f 100644--- a/backend/app/core/scheduler.py+++ b/backend/app/core/scheduler.py@@ -231,6 +231,38 @@ async def _run_proxmox_sync() -> None:)+async def _run_unraid_sync() -> None:+ """Fetch the Unraid containers and upsert them into pending (auto-sync)."""+ if not settings.unraid_sync_enabled:+ return+ if not (settings.unraid_host and settings.unraid_api_key):+ logger.warning("Unraid auto-sync enabled but host/API key not configured - skipping")+ return+ from app.api.routes.unraid import _background_unraid_import+ from app.db.models import ScanRun++ async with AsyncSessionLocal() as db:+ run = ScanRun(+ status="running",+ kind="unraid",+ ranges=[f"{settings.unraid_host}:{settings.unraid_effective_port}"],+ )+ db.add(run)+ await db.commit()+ await db.refresh(run)+ run_id = run.id++ await _background_unraid_import(+ run_id,+ settings.unraid_host,+ settings.unraid_effective_port,+ settings.unraid_api_key,+ settings.unraid_verify_tls,+ settings.unraid_use_https,+ settings.unraid_sync_include_offline,+ )++async def _run_mesh_sync(kind: str) -> None:"""Shared auto-sync for the MQTT mesh imports (Zigbee / Z-Wave).@@ -330,6 +362,22 @@ def _add_proxmox_sync_job() -> None:)+def _unraid_sync_interval() -> int:+ # .env and the settings file bypass the >= 300 check on write, so clamp here+ return max(300, settings.unraid_sync_interval)+++def _add_unraid_sync_job() -> None:+ scheduler.add_job(+ _run_unraid_sync,+ "interval",+ seconds=_unraid_sync_interval(),+ id="unraid_sync",+ max_instances=1,+ coalesce=True,+ )++def _add_zigbee_sync_job() -> None:scheduler.add_job(_run_zigbee_sync,@@ -384,6 +432,8 @@ def start_scheduler() -> None:_add_service_check_job()if settings.proxmox_sync_enabled:_add_proxmox_sync_job()+ if settings.unraid_sync_enabled:+ _add_unraid_sync_job()if settings.zigbee_sync_enabled:_add_zigbee_sync_job()if settings.zwave_sync_enabled:@@ -464,6 +514,31 @@ def set_proxmox_sync_enabled(enabled: bool) -> None:logger.info("Proxmox auto-sync disabled")+def reschedule_unraid_sync(interval_seconds: int) -> None:+ """Update the Unraid auto-sync interval on the running scheduler (if enabled)."""+ if interval_seconds < 300:+ raise ValueError(f"interval_seconds must be >= 300, got {interval_seconds}")+ if not scheduler.running:+ logger.warning("Scheduler not running, skipping reschedule")+ return+ if scheduler.get_job("unraid_sync"):+ scheduler.reschedule_job("unraid_sync", trigger="interval", seconds=interval_seconds)+ logger.info("Unraid auto-sync rescheduled to every %ds", interval_seconds)+++def set_unraid_sync_enabled(enabled: bool) -> None:+ """Add or remove the Unraid auto-sync job on the running scheduler."""+ if not scheduler.running:+ return+ job = scheduler.get_job("unraid_sync")+ if enabled and not job:+ _add_unraid_sync_job()+ logger.info("Unraid auto-sync enabled - every %ds", _unraid_sync_interval())+ elif not enabled and job:+ scheduler.remove_job("unraid_sync")+ logger.info("Unraid auto-sync disabled")++def reschedule_zigbee_sync(interval_seconds: int) -> None:"""Update the Zigbee auto-sync interval on the running scheduler (if enabled)."""if interval_seconds < 300:diff --git a/backend/app/main.py b/backend/app/main.pyindex 70d16d1..0201d8a 100644--- a/backend/app/main.py+++ b/backend/app/main.py@@ -24,6 +24,7 @@ from app.api.routes import (stats,status,unifi,+ unraid,zigbee,zwave,)@@ -99,6 +100,7 @@ app.include_router(zigbee.router, prefix="/api/v1/zigbee", tags=["zigbee"])app.include_router(zwave.router, prefix="/api/v1/zwave", tags=["zwave"])app.include_router(proxmox.router, prefix="/api/v1/proxmox", tags=["proxmox"])app.include_router(unifi.router, prefix="/api/v1/unifi", tags=["unifi"])+app.include_router(unraid.router, prefix="/api/v1/unraid", tags=["unraid"])app.include_router(stats.router, prefix="/api/v1/stats", tags=["stats"])app.include_router(media.router, prefix="/api/v1/media", tags=["media"])app.include_router(documents.router, prefix="/api/v1/documents", tags=["documents"])diff --git a/backend/app/schemas/unraid.py b/backend/app/schemas/unraid.pynew file mode 100644index 0000000..8104702--- /dev/null+++ b/backend/app/schemas/unraid.py@@ -0,0 +1,93 @@+"""Pydantic v2 schemas for the Unraid import.++The API key is accepted on requests only and is optional - when omitted the+backend falls back to the server-configured key (env), for the configured host+only. No response schema ever carries the key.+"""++from typing import Any++from pydantic import BaseModel, Field+++class UnraidConnectionRequest(BaseModel):+ host: str = Field(..., description="Unraid server host or IP")+ port: int | None = Field(None, ge=1, le=65535, description="Unraid port (default 443 for HTTPS, 80 for HTTP)")+ api_key: str | None = Field(None, description="Unraid API key (falls back to server env)")+ # Off by default, like Unraid's own "Use SSL/TLS" setting.+ use_https: bool = Field(False, description="Talk to the Unraid API over HTTPS")+ # Off by default: Unraid's own certificate is self-signed. Only used over HTTPS.+ verify_tls: bool = Field(False, description="Verify the Unraid TLS certificate")+ # Stopped containers and VMs: imported (and, in canvas mode, listed) like+ # running ones, or left out entirely.+ include_offline: bool = True++ @property+ def effective_port(self) -> int:+ return self.port or (443 if self.use_https else 80)+++class UnraidTestConnectionResponse(BaseModel):+ connected: bool+ message: str+++class UnraidNodeOut(BaseModel):+ """A homelable-ready node for the Unraid host, one of its containers or a VM."""++ id: str+ label: str+ type: str # docker_host | docker_container | vm+ ieee_address: str+ hostname: str | None = None+ ip: str | None = None+ status: str+ vendor: str | None = None+ model: str | None = None+ parent_ieee: str | None = None+ # The Device Inventory row this node draws, stamped by the import.+ device_id: str | None = None+ # The row's lists, so the node's first canvas save writes them back intact.+ services: list[dict[str, Any]] = []+ properties: list[dict[str, Any]] = []+++class UnraidEdgeOut(BaseModel):+ source: str+ target: str+++class UnraidImportResponse(BaseModel):+ nodes: list[UnraidNodeOut]+ edges: list[UnraidEdgeOut]+ device_count: int+ # Why VMs were left out (e.g. the key has no VM access); None when they weren't.+ notice: str | None = None+++class UnraidImportPendingResponse(BaseModel):+ pending_created: int+ pending_updated: int+ links_recorded: int+ device_count: int+++class UnraidConfig(BaseModel):+ """Non-secret Unraid connection + auto-sync config (GET response)."""++ host: str = ""+ port: int = Field(80, ge=1, le=65535)+ use_https: bool = False+ verify_tls: bool = False+ sync_enabled: bool = False+ sync_interval: int = Field(3600, ge=300)+ include_offline: bool = True+ api_key_configured: bool = False+++class UnraidSyncConfig(BaseModel):+ """User-editable auto-sync config (POST body). Connection fields are env-only."""++ sync_enabled: bool = False+ sync_interval: int = Field(3600, ge=300, le=86400)+ include_offline: bool = Truediff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.pyindex e66c7fa..e678e5d 100644--- a/backend/app/services/scanner.py+++ b/backend/app/services/scanner.py@@ -777,9 +777,9 @@ async def process_host(# discovered=: the fingerprint may add services and refresh what it# knows, but never repaints an icon or category the user chose.keep.services = merge_services(keep.services, services, discovered=True)- # Don't downgrade a Proxmox-typed guest (vm/lxc) to the generic- # scan guess; the importer knows the true type.- if not (keep.ieee_address or "").startswith("pve-"):+ # Don't downgrade a Proxmox-typed guest (vm/lxc) or an Unraid+ # container to the generic scan guess; the importer knows the true type.+ if not (keep.ieee_address or "").startswith(("pve-", "unraid-")):keep.suggested_type = suggested_type# Merged row carries both sources (e.g. ["proxmox", "arp"]).keep.discovery_sources = add_source(keep.discovery_sources, discovery_source)diff --git a/backend/app/services/unraid_service.py b/backend/app/services/unraid_service.pynew file mode 100644index 0000000..c18bdc6--- /dev/null+++ b/backend/app/services/unraid_service.py@@ -0,0 +1,484 @@+"""Unraid inventory service: fetch the server, its Docker containers and VMs.++Talks to the Unraid API (GraphQL at ``/graphql``, built in from Unraid 7.2, the+Unraid Connect plugin before that) with an API key in the ``x-api-key`` header,+over HTTP or HTTPS - Unraid serves its web UI over plain HTTP by default. Returns plain+homelable node dicts + host->guest edge hints; DB persistence lives in the+route layer (``app.api.routes.unraid``).++Container identity is the host UUID plus the container *name*: Unraid recreates+a container on every update, so its Docker id is not stable. A VM is keyed on+its libvirt UUID. The API reports a VM as name + state only - no NIC MAC, IP,+CPU or RAM - so a VM cannot be matched to a device a scan already found.+"""++from __future__ import annotations++import html+import logging+import re+from typing import Any+from urllib.parse import parse_qsl, urlencode, urlsplit++import httpx++from app.services.mac_utils import normalize_mac+from app.services.zigbee_service import merge_zigbee_properties++logger = logging.getLogger(__name__)++# Same NodeProperty shape + visibility-preservation rules as the other importers.+merge_unraid_properties = merge_zigbee_properties++_CONNECT_TIMEOUT = 8.0+_READ_TIMEOUT = 30.0++# Docker network drivers that give a container its own address on the LAN.+# Everything else (bridge, host, none, container:<id>) sits behind the host IP.+_LAN_DRIVERS = {"macvlan", "ipvlan"}++_INVENTORY_QUERY = """+query {+ info {+ system { uuid manufacturer model }+ cpu { brand threads }+ os { hostname }+ primaryNetwork { macAddress ipAddress }+ versions { core { unraid } }+ }+ docker {+ networks { name driver }+ containers {+ id names image state status autoStart webUiUrl labels lanIpPorts+ hostConfig { networkMode }+ networkSettings+ }+ }+}+"""++_VERSION_QUERY = "query { info { os { hostname } versions { core { unraid } } } }"++# Asked apart from the inventory query: a key without VM access, or a server+# with the VM manager off, must not cost the user the containers.+_VM_QUERY = "query { vms { domains { id name state } } }"++# libvirt states in which the guest is up. IDLE is a running guest blocked on I/O.+_VM_ONLINE_STATES = {"RUNNING", "IDLE"}+++class UnraidAuthError(ConnectionError):+ """The API rejected the key (bad key, or missing permissions)."""+++def _sanitize_unraid_error(exc: BaseException) -> str:+ """Return a generic, credential-free message for an Unraid/HTTP error."""+ logger.warning("Unraid error (sanitized for client): %r", exc)+ if isinstance(exc, UnraidAuthError):+ return str(exc)+ if isinstance(exc, httpx.HTTPStatusError):+ code = exc.response.status_code+ if code in (401, 403):+ return "Authentication failed - check the API key and its permissions"+ if code == 404:+ return "Unraid API not found - is this Unraid 7.2+ (or has the Unraid Connect plugin)?"+ if exc.response.is_redirect and exc.response.headers.get("location", "").startswith("https://"):+ # A server with SSL on answers plain HTTP with a redirect to HTTPS.+ return "This server uses HTTPS - tick 'Use HTTPS'"+ return f"Unraid API returned HTTP {code}"+ raw = str(exc).lower()+ if "name or service not known" in raw or "getaddrinfo" in raw or "nodename nor servname" in raw:+ return "Unraid host could not be resolved"+ if "refused" in raw:+ return "Connection refused by Unraid host"+ if "wrong_version_number" in raw or "wrong version number" in raw or "record layer" in raw:+ # HTTPS spoken to a port that answers plain HTTP.+ return "This server does not answer HTTPS on that port - untick 'Use HTTPS'"+ if "certificate" in raw or "ssl" in raw or "tls" in raw:+ return "TLS verification failed - untick 'Verify TLS certificate' for self-signed certs"+ if "timed out" in raw or "timeout" in raw:+ return "Connection to Unraid host timed out"+ return "Unraid connection failed"+++def _graphql_errors(payload: dict[str, Any]) -> None:+ """Raise for GraphQL-level errors. The API answers auth failures with HTTP 200."""+ errors = payload.get("errors")+ if not errors:+ return+ codes = {(e.get("extensions") or {}).get("code") for e in errors if isinstance(e, dict)}+ if "UNAUTHENTICATED" in codes:+ raise UnraidAuthError("Authentication failed - check the API key")+ if "FORBIDDEN" in codes:+ raise UnraidAuthError("The API key lacks permission - it needs read access to Docker, VMs and Info")+ first = errors[0].get("message") if isinstance(errors[0], dict) else None+ raise ValueError(f"Unraid API error: {first or 'unknown'}")+++async def _query(client: httpx.AsyncClient, query: str) -> dict[str, Any]:+ resp = await client.post("/graphql", json={"query": query})+ resp.raise_for_status()+ payload = resp.json()+ if not isinstance(payload, dict):+ raise ValueError("Malformed Unraid API response")+ _graphql_errors(payload)+ data = payload.get("data")+ if not isinstance(data, dict):+ raise ValueError("Malformed Unraid API response")+ return data+++def _client(host: str, port: int, api_key: str, verify_tls: bool, use_https: bool) -> httpx.AsyncClient:+ # Never follows redirects: an HTTP request a server bounces to HTTPS is+ # reported, not silently retried, so the key's transport stays the user's call.+ return httpx.AsyncClient(+ base_url=f"{'https' if use_https else 'http'}://{host}:{port}",+ headers={"x-api-key": api_key},+ verify=verify_tls,+ timeout=httpx.Timeout(_READ_TIMEOUT, connect=_CONNECT_TIMEOUT),+ )+++def _host_key(info: dict[str, Any]) -> str | None:+ """Stable host key: the system UUID, else the hostname."""+ key = ((info.get("system") or {}).get("uuid")) or ((info.get("os") or {}).get("hostname"))+ return str(key).lower() if key else None+++def _server_web_ui(host: str, port: int, use_https: bool) -> dict[str, Any]:+ """A "Web UI" service for the server, at the address the import connected to.++ The GraphQL API is served by the web UI's own web server, so that address is+ known to answer. The server's advertised access URLs are not: they include+ myunraid.net and Tailscale names the backend may not reach.+ """+ scheme = "https" if use_https else "http"+ name = f"[{host}]" if ":" in host else host+ default = 443 if use_https else 80+ netloc = name if port == default else f"{name}:{port}"+ return {+ "port": port,+ "protocol": "tcp",+ "service_name": "Web UI",+ "host": f"{scheme}://{netloc}",+ "path": "",+ }+++def _host_node(info: dict[str, Any], host_ieee: str) -> dict[str, Any]:+ system = info.get("system") or {}+ net = info.get("primaryNetwork") or {}+ cpu = info.get("cpu") or {}+ hostname = (info.get("os") or {}).get("hostname")+ version = ((info.get("versions") or {}).get("core") or {}).get("unraid")+ model = " ".join(p for p in (system.get("manufacturer"), system.get("model")) if p) or None+ threads = cpu.get("threads")+ return {+ "id": host_ieee,+ "label": hostname or "Unraid",+ "type": "docker_host",+ "ieee_address": host_ieee,+ "hostname": hostname,+ "ip": net.get("ipAddress") or None,+ "mac": normalize_mac(net.get("macAddress")),+ "status": "online",+ "cpu_count": threads if isinstance(threads, int) else None,+ "cpu_model": cpu.get("brand") or None,+ "vendor": "Unraid",+ "model": model,+ "os_version": f"Unraid {version}" if version else None,+ "services": [],+ "parent_ieee": None,+ }+++def _container_name(raw: dict[str, Any]) -> str | None:+ names = raw.get("names") or []+ if not names or not isinstance(names[0], str):+ return None+ return names[0].lstrip("/") or None+++def _lan_address(+ networks: dict[str, Any], drivers: dict[str, str | None]+) -> tuple[str | None, str | None]:+ """(ip, mac) when the container sits on a macvlan/ipvlan network, else (None, None).++ A bridge address is internal to the host and a bridge MAC changes on every+ recreate, so neither identifies the container. An ipvlan container shares+ the parent interface's MAC, so only macvlan contributes one.+ """+ for net_name, net in networks.items():+ driver = drivers.get(net_name)+ if driver not in _LAN_DRIVERS or not isinstance(net, dict):+ continue+ ip = net.get("IPAddress") or None+ if not ip:+ continue+ mac = normalize_mac(net.get("MacAddress")) if driver == "macvlan" else None+ return ip, mac+ return None, None+++# Query parameter names that carry a credential. Compared on the whole name,+# letters only ("api_key" -> "apikey"), so "design" or "autoconnect" survive.+_SECRET_PARAMS = {+ "key", "apikey", "token", "accesstoken", "authtoken", "auth", "password",+ "passwd", "pass", "pwd", "secret", "sig", "signature", "session", "sessionid",+ "sid", "jwt",+}+_SECRET_SUFFIXES = ("token", "apikey", "secret", "password")+++def _is_secret_param(name: str) -> bool:+ letters = re.sub(r"[^a-z]", "", name.lower())+ return letters in _SECRET_PARAMS or letters.endswith(_SECRET_SUFFIXES)+++def _web_ui_service(+ url: str | None, own_ip: str | None = None, server_ip: str | None = None+) -> dict[str, Any] | None:+ """A "Web UI" service for the URL Unraid resolved from the template, or None.++ The address goes in ``host`` because most containers sit behind the server's+ IP on a published port, not on an address of their own. The URL comes+ HTML-escaped from the template (``&`` in a query string).++ Unraid resolves the template's ``[IP]`` to the server even for a container+ with its own LAN address, where nothing answers on the server IP. Such a+ container gets its own address instead.++ The service is stored and shown on canvases (a shared live view included),+ so credentials never come along: userinfo is dropped and so are query+ parameters named like a secret.+ """+ if not url:+ return None+ parts = urlsplit(html.unescape(url).strip())+ if parts.scheme not in ("http", "https") or not parts.hostname:+ return None+ try:+ port = parts.port or (443 if parts.scheme == "https" else 80)+ except ValueError:+ return None+ hostname = own_ip if own_ip and server_ip and parts.hostname == server_ip else parts.hostname+ name = f"[{hostname}]" if ":" in hostname else hostname+ netloc = f"{name}:{parts.port}" if parts.port else name+ query = urlencode(+ [(k, v) for k, v in parse_qsl(parts.query, keep_blank_values=True) if not _is_secret_param(k)]+ )+ path = parts.path + (f"?{query}" if query else "")+ return {+ "port": port,+ "protocol": "tcp",+ "service_name": "Web UI",+ "host": f"{parts.scheme}://{netloc}",+ "path": path,+ }+++def _container_node(+ raw: dict[str, Any],+ host_key: str,+ drivers: dict[str, str | None],+ names_by_id: dict[str, str],+ server_ip: str | None = None,+) -> dict[str, Any] | None:+ name = _container_name(raw)+ if not name:+ return None+ ieee = f"unraid-{host_key}-ct-{name}"+ settings_json = raw.get("networkSettings") or {}+ networks = settings_json.get("Networks") if isinstance(settings_json, dict) else None+ ip, mac = _lan_address(networks or {}, drivers)++ network_mode = (raw.get("hostConfig") or {}).get("networkMode") or None+ if network_mode and network_mode.startswith("container:"):+ # Shares another container's network namespace (a VPN sidecar, usually).+ target = network_mode.split(":", 1)[1]+ network_mode = f"container:{names_by_id.get(target, target[:12])}"++ labels = raw.get("labels") or {}+ ports = sorted(set(raw.get("lanIpPorts") or []))+ web_ui = _web_ui_service(raw.get("webUiUrl"), ip, server_ip)+ return {+ "id": ieee,+ "label": name,+ "type": "docker_container",+ "ieee_address": ieee,+ "hostname": name,+ "ip": ip,+ "mac": mac,+ "status": "online" if raw.get("state") == "RUNNING" else "offline",+ "vendor": "Docker",+ "model": raw.get("image") or None,+ "network": network_mode,+ "ports": ports,+ "services": [web_ui] if web_ui else [],+ "compose_project": labels.get("com.docker.compose.project") if isinstance(labels, dict) else None,+ "parent_ieee": f"unraid-host-{host_key}",+ }+++def _vm_node(raw: dict[str, Any], host_key: str) -> dict[str, Any] | None:+ # PrefixedID is "<server>:<libvirt uuid>".+ uuid = str(raw.get("id") or "").split(":")[-1].lower()+ if not uuid:+ return None+ ieee = f"unraid-{host_key}-vm-{uuid}"+ name = raw.get("name") or f"vm-{uuid[:8]}"+ return {+ "id": ieee,+ "label": name,+ "type": "vm",+ "ieee_address": ieee,+ "hostname": name,+ "ip": None,+ "mac": None,+ "status": "online" if raw.get("state") in _VM_ONLINE_STATES else "offline",+ "vendor": "Unraid",+ "model": "KVM",+ "uuid": uuid,+ "services": [],+ "parent_ieee": f"unraid-host-{host_key}",+ }+++def _parse_inventory(+ data: dict[str, Any],+ vms: list[dict[str, Any]] | None = None,+ web_ui: dict[str, Any] | None = None,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]:+ info = data.get("info")+ docker = data.get("docker")+ if not isinstance(info, dict) or not isinstance(docker, dict):+ raise ValueError("Malformed Unraid API response")+ host_key = _host_key(info)+ if host_key is None:+ raise ValueError("Unraid API returned no system UUID or hostname")+ host_ieee = f"unraid-host-{host_key}"++ drivers = {+ n["name"]: n.get("driver")+ for n in docker.get("networks") or []+ if isinstance(n, dict) and n.get("name")+ }+ containers = [c for c in docker.get("containers") or [] if isinstance(c, dict)]+ # PrefixedID is "<server>:<docker id>"; networkMode references the bare id.+ names_by_id = {+ str(c.get("id", "")).split(":")[-1]: name+ for c in containers+ if (name := _container_name(c))+ }++ host = _host_node(info, host_ieee)+ if web_ui:+ host["services"] = [web_ui]+ nodes = [host]+ edges: list[dict[str, Any]] = []+ seen = {host_ieee}+ for raw in containers:+ node = _container_node(raw, host_key, drivers, names_by_id, host["ip"])+ if node is None or node["id"] in seen:+ continue+ seen.add(node["id"])+ nodes.append(node)+ edges.append({"source": host_ieee, "target": node["id"]})+ for raw in vms or []:+ node = _vm_node(raw, host_key)+ if node is None or node["id"] in seen:+ continue+ seen.add(node["id"])+ nodes.append(node)+ edges.append({"source": host_ieee, "target": node["id"]})+ return nodes, edges+++def build_unraid_properties(node: dict[str, Any]) -> list[dict[str, Any]]:+ """NodeProperty list for an Unraid host or container. All hidden by default."""+ props: list[dict[str, Any]] = []++ def add(key: str, value: Any, icon: str | None = None) -> None:+ if value:+ props.append({"key": key, "value": str(value), "icon": icon, "visible": False})++ if node.get("type") == "docker_host":+ add("OS", node.get("os_version"))+ add("CPU Model", node.get("cpu_model"), "Cpu")+ if node.get("cpu_count") is not None:+ add("CPU Threads", node["cpu_count"], "Cpu")+ elif node.get("type") == "vm":+ add("UUID", node.get("uuid"))+ add("Kind", node.get("model"))+ else:+ add("Image", node.get("model"))+ add("Network", node.get("network"))+ add("Ports", ", ".join(node.get("ports") or []))+ add("Compose Project", node.get("compose_project"))+ props.append({"key": "Source", "value": "Unraid", "icon": None, "visible": False})+ return props+++async def _fetch_vms(client: httpx.AsyncClient) -> tuple[list[dict[str, Any]], str | None]:+ """The server's VM list, or ([], why it could not be read). Never raises on a+ GraphQL error: missing VM access must not fail the container import."""+ try:+ data = await _query(client, _VM_QUERY)+ except UnraidAuthError:+ return [], "VMs were not imported: the API key has no read access to VMs"+ except ValueError as exc:+ logger.warning("Unraid VM list unavailable: %s", exc)+ return [], "VMs were not imported: the server did not return its VM list"+ domains = (data.get("vms") or {}).get("domains")+ return [d for d in domains or [] if isinstance(d, dict)], None+++async def fetch_unraid_inventory(+ host: str,+ port: int,+ api_key: str,+ verify_tls: bool = True,+ use_https: bool = False,+) -> tuple[list[dict[str, Any]], list[dict[str, Any]], str | None]:+ """Fetch the Unraid host, its containers and VMs: (nodes, edges, notice).++ ``notice`` says why VMs were left out, when they were; None otherwise.++ Raises:+ ConnectionError: transport/TLS/auth failures (sanitized message).+ ValueError: malformed API response or a GraphQL error.+ """+ try:+ async with _client(host, port, api_key, verify_tls, use_https) as client:+ data = await _query(client, _INVENTORY_QUERY)+ vms, notice = await _fetch_vms(client)+ except UnraidAuthError:+ raise+ except httpx.HTTPError as exc:+ raise ConnectionError(_sanitize_unraid_error(exc)) from exc+ nodes, edges = _parse_inventory(data, vms, _server_web_ui(host, port, use_https))+ return nodes, edges, notice+++async def test_unraid_connection(+ host: str,+ port: int,+ api_key: str,+ verify_tls: bool = True,+ use_https: bool = False,+) -> tuple[bool, str]:+ """Quick reachability + auth check. Returns (connected, message)."""+ try:+ async with _client(host, port, api_key, verify_tls, use_https) as client:+ data = await _query(client, _VERSION_QUERY)+ _, notice = await _fetch_vms(client)+ except (httpx.HTTPError, UnraidAuthError) as exc:+ return False, _sanitize_unraid_error(exc)+ except Exception as exc: # noqa: BLE001 - surface a safe message, log the rest+ logger.exception("Unexpected error during Unraid connection test")+ return False, _sanitize_unraid_error(exc)+ info = data.get("info") or {}+ hostname = (info.get("os") or {}).get("hostname") or "Unraid"+ version = ((info.get("versions") or {}).get("core") or {}).get("unraid") or "?"+ message = f"Connected to {hostname} (Unraid {version})"+ return True, f"{message}. {notice}" if notice else messagediff --git a/backend/tests/conftest.py b/backend/tests/conftest.pyindex f21fd79..3fd8117 100644--- a/backend/tests/conftest.py+++ b/backend/tests/conftest.py@@ -47,6 +47,7 @@ async def db_session():"app.api.routes.zwave","app.api.routes.proxmox","app.api.routes.unifi",+ "app.api.routes.unraid","app.api.routes.scan",)]diff --git a/backend/tests/test_scan_proxmox_children.py b/backend/tests/test_scan_proxmox_children.pyindex 9dbcff3..068beca 100644--- a/backend/tests/test_scan_proxmox_children.py+++ b/backend/tests/test_scan_proxmox_children.py@@ -101,3 +101,23 @@ async def test_requires_auth(client: AsyncClient, db_session):ids = await _seed(db_session)res = await client.get(f"/api/v1/scan/pending/{ids['host']}/proxmox-children")assert res.status_code == 401+++async def test_returns_the_containers_of_an_unraid_server(client: AsyncClient, headers, db_session):+ server = InventoryDevice(+ ieee_address="unraid-host-abc", hostname="tower", suggested_type="docker_host", status="pending"+ )+ plex = InventoryDevice(+ ieee_address="unraid-abc-ct-plex", hostname="plex", suggested_type="docker_container", status="pending"+ )+ db_session.add_all([server, plex])+ await db_session.flush()+ db_session.add(+ InventoryDeviceLink(+ source_ieee="unraid-host-abc", target_ieee="unraid-abc-ct-plex", discovery_source="unraid"+ )+ )+ await db_session.commit()+ res = await client.get(f"/api/v1/scan/pending/{server.id}/proxmox-children", headers=headers)+ assert [d["id"] for d in res.json()] == [plex.id]diff --git a/backend/tests/test_scheduler.py b/backend/tests/test_scheduler.pyindex 4cc7693..914f59b 100644--- a/backend/tests/test_scheduler.py+++ b/backend/tests/test_scheduler.py@@ -19,6 +19,7 @@ from app.core.scheduler import (reschedule_zwave_sync,set_proxmox_sync_enabled,set_service_checks_enabled,+ set_unraid_sync_enabled,set_zigbee_sync_enabled,set_zwave_sync_enabled,start_scheduler,@@ -329,6 +330,7 @@ def test_scheduler_uses_settings_interval():mock_settings.zigbee_sync_enabled = Falsemock_settings.zwave_sync_enabled = Falsemock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = Falsestart_scheduler()_, kwargs = mock_sched.add_job.call_argsassert kwargs["seconds"] == 45@@ -345,6 +347,7 @@ def test_start_and_stop_scheduler():mock_settings.zigbee_sync_enabled = Falsemock_settings.zwave_sync_enabled = Falsemock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = Falsestart_scheduler()stop_scheduler()mock_sched.add_job.assert_called_once()@@ -440,6 +443,8 @@ def test_start_scheduler_adds_service_job_when_enabled():mock_settings.proxmox_sync_enabled = Falsemock_settings.zigbee_sync_enabled = Falsemock_settings.zwave_sync_enabled = False+ mock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = Falsestart_scheduler()job_ids = [kw.get("id") for _, kw in mock_sched.add_job.call_args_list]assert "status_checks" in job_ids@@ -667,6 +672,8 @@ def test_start_scheduler_adds_mesh_jobs_when_enabled():mock_settings.zigbee_sync_interval = 3600mock_settings.zwave_sync_enabled = Truemock_settings.zwave_sync_interval = 3600+ mock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = Falsestart_scheduler()job_ids = [kw.get("id") for _, kw in mock_sched.add_job.call_args_list]assert "zigbee_sync" in job_ids@@ -720,3 +727,54 @@ def test_reschedule_proxmox_sync_noop_when_not_running():with patch("app.core.scheduler.scheduler", mock_sched):reschedule_proxmox_sync(600)mock_sched.reschedule_job.assert_not_called()+++def _unraid_sync_seconds(mock_sched: MagicMock) -> int:+ for _, kwargs in mock_sched.add_job.call_args_list:+ if kwargs.get("id") == "unraid_sync":+ return kwargs["seconds"]+ raise AssertionError("unraid_sync job was not added")+++def test_start_scheduler_floors_a_short_unraid_sync_interval():+ """A sub-300s UNRAID_SYNC_INTERVAL from .env must not reach the scheduler."""+ mock_sched = MagicMock()+ with patch("app.core.scheduler.settings") as mock_settings, \+ patch("app.core.scheduler.AsyncIOScheduler", return_value=mock_sched):+ mock_settings.status_checker_interval = 60+ mock_settings.service_check_enabled = False+ mock_settings.proxmox_sync_enabled = False+ mock_settings.zigbee_sync_enabled = False+ mock_settings.zwave_sync_enabled = False+ mock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = True+ mock_settings.unraid_sync_interval = 5+ start_scheduler()+ assert _unraid_sync_seconds(mock_sched) == 300+++def test_start_scheduler_keeps_a_valid_unraid_sync_interval():+ mock_sched = MagicMock()+ with patch("app.core.scheduler.settings") as mock_settings, \+ patch("app.core.scheduler.AsyncIOScheduler", return_value=mock_sched):+ mock_settings.status_checker_interval = 60+ mock_settings.service_check_enabled = False+ mock_settings.proxmox_sync_enabled = False+ mock_settings.zigbee_sync_enabled = False+ mock_settings.zwave_sync_enabled = False+ mock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = True+ mock_settings.unraid_sync_interval = 1800+ start_scheduler()+ assert _unraid_sync_seconds(mock_sched) == 1800+++def test_set_unraid_sync_enabled_floors_a_short_interval():+ mock_sched = MagicMock()+ mock_sched.running = True+ mock_sched.get_job.return_value = None+ with patch("app.core.scheduler.scheduler", mock_sched), \+ patch("app.core.scheduler.settings") as mock_settings:+ mock_settings.unraid_sync_interval = 5+ set_unraid_sync_enabled(True)+ assert _unraid_sync_seconds(mock_sched) == 300diff --git a/backend/tests/test_status_checker_toggle.py b/backend/tests/test_status_checker_toggle.pyindex b3aeed2..fb3b5e8 100644--- a/backend/tests/test_status_checker_toggle.py+++ b/backend/tests/test_status_checker_toggle.py@@ -22,6 +22,7 @@ def _configure(mock_settings, *, checker: bool, services: bool = False) -> None:mock_settings.zigbee_sync_enabled = Falsemock_settings.zwave_sync_enabled = Falsemock_settings.unifi_sync_enabled = False+ mock_settings.unraid_sync_enabled = Falsedef _job_ids(mock_sched: MagicMock) -> list[str]:diff --git a/backend/tests/test_unraid_router.py b/backend/tests/test_unraid_router.pynew file mode 100644index 0000000..401ff56--- /dev/null+++ b/backend/tests/test_unraid_router.py@@ -0,0 +1,489 @@+"""API + persistence tests for /api/v1/unraid/*."""++from __future__ import annotations++import uuid+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock, patch++import pytest+from httpx import AsyncClient+from sqlalchemy import select++from app.api.routes.unraid import _background_unraid_import, _persist_pending_import+from app.core.config import settings+from app.db.models import InventoryDevice, InventoryDeviceLink, Node++HOST = "unraid-host-abc"++[email protected](autouse=True)+def _clear_env():+ """A clean env-config state per test; restored afterwards."""+ fields = ("unraid_host", "unraid_port", "unraid_api_key", "unraid_verify_tls", "unraid_use_https")+ saved = {f: getattr(settings, f) for f in fields}+ settings.unraid_host = ""+ settings.unraid_port = None+ settings.unraid_api_key = ""+ settings.unraid_verify_tls = False+ settings.unraid_use_https = False+ yield+ for field, value in saved.items():+ setattr(settings, field, value)+++def _host(ip: str = "10.1.1.231", mac: str = "a0:36:9f:77:f9:44") -> dict:+ return {+ "id": HOST, "label": "Pearl", "type": "docker_host", "ieee_address": HOST,+ "hostname": "Pearl", "ip": ip, "mac": mac, "status": "online",+ "cpu_count": 20, "cpu_model": "i5", "vendor": "Unraid", "model": "MSI",+ "os_version": "Unraid 7.3.1", "parent_ieee": None,+ }+++def _ct(name: str, status: str = "online", ip: str | None = None) -> dict:+ ieee = f"unraid-abc-ct-{name}"+ return {+ "id": ieee, "label": name, "type": "docker_container", "ieee_address": ieee,+ "hostname": name, "ip": ip, "mac": None, "status": status,+ "vendor": "Docker", "model": f"img/{name}", "network": "bridge",+ "ports": [], "services": [], "compose_project": None, "parent_ieee": HOST,+ }+++def _inventory(*containers: dict) -> tuple[list[dict], list[dict]]:+ nodes = [_host(), *containers]+ return nodes, [{"source": HOST, "target": c["id"]} for c in containers]+++def _fetched(*guests: dict, notice: str | None = None) -> tuple[list[dict], list[dict], str | None]:+ """What fetch_unraid_inventory returns: nodes, edges and the VM notice."""+ return (*_inventory(*guests), notice)+++def _vm(name: str, status: str = "online") -> dict:+ ieee = f"unraid-abc-vm-{name}-uuid"+ return {+ "id": ieee, "label": name, "type": "vm", "ieee_address": ieee,+ "hostname": name, "ip": None, "mac": None, "status": status,+ "vendor": "Unraid", "model": "KVM", "uuid": f"{name}-uuid",+ "services": [], "parent_ieee": HOST,+ }+++BODY = {"host": "pearl", "api_key": "k"}+WEB_UI = {+ "port": 32400, "protocol": "tcp", "service_name": "Web UI",+ "host": "http://10.1.1.231:32400", "path": "/web/index.html",+}+++# --- endpoints -------------------------------------------------------------++async def test_custom_host_without_key_is_rejected(client: AsyncClient, headers: dict) -> None:+ settings.unraid_host = "pearl"+ settings.unraid_api_key = "envkey"+ res = await client.post("/api/v1/unraid/test-connection", json={"host": "evil", "port": 443}, headers=headers)+ assert res.status_code == 400+++async def test_env_key_used_for_configured_host(client: AsyncClient, headers: dict) -> None:+ settings.unraid_host = "pearl"+ settings.unraid_api_key = "envkey"+ with patch("app.api.routes.unraid.test_unraid_connection", new=AsyncMock(return_value=(True, "ok"))) as t:+ res = await client.post("/api/v1/unraid/test-connection", json={"host": "Pearl"}, headers=headers)+ assert res.status_code == 200+ assert t.await_args.kwargs["api_key"] == "envkey"+ # Plain HTTP on port 80 by default, like Unraid's own default.+ assert (t.await_args.kwargs["use_https"], t.await_args.kwargs["port"]) == (False, 80)+++async def test_https_defaults_to_port_443(client: AsyncClient, headers: dict) -> None:+ with patch("app.api.routes.unraid.test_unraid_connection", new=AsyncMock(return_value=(True, "ok"))) as t:+ await client.post("/api/v1/unraid/test-connection", json={**BODY, "use_https": True}, headers=headers)+ assert (t.await_args.kwargs["use_https"], t.await_args.kwargs["port"]) == (True, 443)+++async def test_env_key_refused_over_http_when_the_server_uses_https(client: AsyncClient, headers: dict) -> None:+ settings.unraid_host = "pearl"+ settings.unraid_api_key = "envkey"+ settings.unraid_use_https = True+ res = await client.post(+ "/api/v1/unraid/test-connection", json={"host": "pearl", "port": 443}, headers=headers+ )+ assert res.status_code == 400+ assert "requires HTTPS" in res.json()["detail"]+++async def test_env_key_refused_with_tls_verification_off(client: AsyncClient, headers: dict) -> None:+ settings.unraid_host = "pearl"+ settings.unraid_api_key = "envkey"+ settings.unraid_verify_tls = True+ settings.unraid_use_https = True+ res = await client.post(+ "/api/v1/unraid/test-connection",+ json={"host": "pearl", "use_https": True, "verify_tls": False},+ headers=headers,+ )+ assert res.status_code == 400+ assert "TLS verification" in res.json()["detail"]+++async def test_requires_auth(client: AsyncClient) -> None:+ res = await client.post("/api/v1/unraid/import", json=BODY)+ assert res.status_code == 401+++async def test_import_pending_creates_scan_run(client: AsyncClient, headers: dict) -> None:+ with patch("app.api.routes.unraid._background_unraid_import", new_callable=AsyncMock) as bg:+ res = await client.post("/api/v1/unraid/import-pending", json={**BODY, "include_offline": False}, headers=headers)+ assert res.status_code == 200+ assert res.json()["kind"] == "unraid"+ # include_offline is the last positional argument.+ assert bg.call_args.args[-1] is False+++async def test_sync_now_rejected_without_env(client: AsyncClient, headers: dict) -> None:+ res = await client.post("/api/v1/unraid/sync-now", headers=headers)+ assert res.status_code == 400+++async def test_config_omits_key(client: AsyncClient, headers: dict) -> None:+ settings.unraid_api_key = "supersecret"+ res = await client.get("/api/v1/unraid/config", headers=headers)+ assert res.status_code == 200+ assert "supersecret" not in res.text+ assert res.json()["api_key_configured"] is True+++async def test_save_config_persists_only_sync_fields(client: AsyncClient, headers: dict) -> None:+ settings.unraid_host = "pearl"+ settings.unraid_api_key = "k"+ with patch.object(type(settings), "save_overrides", lambda self: None), \+ patch("app.api.routes.unraid.set_unraid_sync_enabled"), \+ patch("app.api.routes.unraid.reschedule_unraid_sync"):+ res = await client.post(+ "/api/v1/unraid/config",+ json={"host": "attacker", "sync_enabled": True, "sync_interval": 900, "include_offline": False},+ headers=headers,+ )+ assert res.status_code == 200+ assert settings.unraid_host == "pearl"+ assert settings.unraid_sync_interval == 900+ assert settings.unraid_sync_include_offline is False+++async def test_save_config_rejects_an_interval_out_of_range(client: AsyncClient, headers: dict) -> None:+ for interval in (100, 100_000):+ res = await client.post(+ "/api/v1/unraid/config", json={"sync_enabled": False, "sync_interval": interval}, headers=headers+ )+ assert res.status_code == 422, interval+++async def test_background_import_broadcasts_refresh() -> None:+ fake_db = AsyncMock()+ fake_db.get = AsyncMock(return_value=None)+ cm = AsyncMock()+ cm.__aenter__.return_value = fake_db+ cm.__aexit__.return_value = False+ with patch("app.api.routes.unraid.AsyncSessionLocal", MagicMock(return_value=cm)), \+ patch("app.api.routes.unraid.fetch_unraid_inventory", new=AsyncMock(return_value=([], [], None))), \+ patch("app.api.routes.unraid._persist_pending_import",+ new=AsyncMock(return_value=SimpleNamespace(device_count=3))), \+ patch("app.api.routes.status.broadcast_scan_update", new=AsyncMock()) as bcast:+ await _background_unraid_import("run1", "h", 443, "k", True, True, True)+ bcast.assert_awaited_once()+++# --- stopped devices on the canvas import -------------------------------------++async def _canvas_import(client: AsyncClient, headers: dict, include_offline: bool) -> dict:+ inv = _fetched(_ct("plex"), _ct("old", status="offline"), _vm("winvm", status="offline"))+ with patch("app.api.routes.unraid.fetch_unraid_inventory", new=AsyncMock(return_value=inv)):+ res = await client.post(+ "/api/v1/unraid/import", json={**BODY, "include_offline": include_offline}, headers=headers+ )+ assert res.status_code == 200+ return res.json()+++async def _stored_names(db_session) -> set[str]:+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ return {r.hostname for r in rows}+++async def test_canvas_import_includes_stopped_devices(client: AsyncClient, headers: dict, db_session) -> None:+ data = await _canvas_import(client, headers, True)+ assert {n["label"] for n in data["nodes"]} == {"Pearl", "plex", "old", "winvm"}+ assert len(data["edges"]) == 3+ # Every node points at the inventory row the import created.+ assert all(n["device_id"] for n in data["nodes"])+ assert await _stored_names(db_session) == {"Pearl", "plex", "old", "winvm"}+++async def test_canvas_import_leaves_stopped_devices_out_of_both(client: AsyncClient, headers: dict, db_session) -> None:+ # What the dialog lists is what reaches the inventory - nothing stopped is+ # saved behind the user's back.+ data = await _canvas_import(client, headers, False)+ assert {n["label"] for n in data["nodes"]} == {"Pearl", "plex"}+ assert len(data["edges"]) == 1+ assert await _stored_names(db_session) == {"Pearl", "plex"}+++async def test_canvas_nodes_carry_the_row_lists(client: AsyncClient, headers: dict) -> None:+ # A dropped node's first save replaces the row's lists with the node's, so+ # the node must already hold what the import wrote.+ plex = {**_ct("plex"), "services": [WEB_UI]}+ with patch("app.api.routes.unraid.fetch_unraid_inventory", new=AsyncMock(return_value=_fetched(plex))):+ res = await client.post("/api/v1/unraid/import", json=BODY, headers=headers)+ node = next(n for n in res.json()["nodes"] if n["label"] == "plex")+ assert node["services"] == [WEB_UI]+ assert {p["key"] for p in node["properties"]} >= {"Image", "Source"}+++async def test_canvas_import_returns_the_vm_notice(client: AsyncClient, headers: dict) -> None:+ inv = _fetched(_ct("plex"), notice="VMs were not imported: no access")+ with patch("app.api.routes.unraid.fetch_unraid_inventory", new=AsyncMock(return_value=inv)):+ res = await client.post("/api/v1/unraid/import", json=BODY, headers=headers)+ assert res.json()["notice"] == "VMs were not imported: no access"+++async def test_background_import_records_the_vm_notice_on_the_run(db_session) -> None:+ from app.db.models import ScanRun++ run = ScanRun(status="running", kind="unraid", ranges=["pearl:443"])+ db_session.add(run)+ await db_session.commit()+ inv = _fetched(_ct("plex"), notice="VMs were not imported: no access")+ with patch("app.api.routes.unraid.fetch_unraid_inventory", new=AsyncMock(return_value=inv)), \+ patch("app.api.routes.status.broadcast_scan_update", new=AsyncMock()):+ await _background_unraid_import(run.id, "pearl", 80, "k", False, False, True)+ await db_session.refresh(run)+ assert run.status == "done"+ assert run.error == "VMs were not imported: no access"+++# --- persistence ---------------------------------------------------------------++async def test_persist_creates_rows_and_links(db_session) -> None:+ nodes, edges = _inventory(_ct("plex"))+ result = await _persist_pending_import(db_session, nodes, edges)+ assert result.pending_created == 2+ assert result.links_recorded == 1+ host = (await db_session.execute(+ select(InventoryDevice).where(InventoryDevice.ieee_address == HOST)+ )).scalar_one()+ assert host.suggested_type == "docker_host"+ assert host.os == "Unraid 7.3.1"+ assert host.discovery_sources == ["unraid"]+++async def test_persist_stores_a_vm_linked_to_its_host(db_session) -> None:+ nodes, edges = _inventory(_vm("winvm"))+ await _persist_pending_import(db_session, nodes, edges)+ vm = (await db_session.execute(+ select(InventoryDevice).where(InventoryDevice.suggested_type == "vm")+ )).scalar_one()+ assert vm.ieee_address == "unraid-abc-vm-winvm-uuid"+ assert {p["key"]: p["value"] for p in vm.properties}["UUID"] == "winvm-uuid"+ link = (await db_session.execute(select(InventoryDeviceLink))).scalar_one()+ assert (link.source_ieee, link.target_ieee) == (HOST, vm.ieee_address)+++async def test_server_web_ui_merges_into_a_scanned_port(db_session) -> None:+ # A scan already found 443 on the server: the import adds the address to+ # that entry rather than a second 443 beside it, and keeps the scan's name.+ scanned = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.231", mac="a0:36:9f:77:f9:44",+ discovery_source="arp", discovery_sources=["arp"], status="pending",+ services=[{"port": 443, "protocol": "tcp", "service_name": "https"}],+ )+ db_session.add(scanned)+ await db_session.commit()+ web_ui = {"port": 443, "protocol": "tcp", "service_name": "Web UI", "host": "https://10.1.1.231", "path": ""}++ await _persist_pending_import(db_session, [{**_host(), "services": [web_ui]}], [])++ await db_session.refresh(scanned)+ assert len(scanned.services) == 1+ assert scanned.services[0]["host"] == "https://10.1.1.231"+ assert scanned.services[0]["service_name"] == "https"+++async def test_persist_merges_host_into_scanned_row(db_session) -> None:+ scanned = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.231", mac="a0:36:9f:77:f9:44",+ discovery_source="arp", discovery_sources=["arp"], status="pending",+ )+ db_session.add(scanned)+ await db_session.commit()++ await _persist_pending_import(db_session, [_host()], [])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 1+ assert rows[0].ieee_address == HOST+ assert set(rows[0].discovery_sources) == {"arp", "unraid"}+++async def test_host_never_merges_into_an_ipvlan_container_row(db_session) -> None:+ # A scan files an ipvlan container as its own IP with the host's MAC. That+ # row is older than the host's own row, which UniFi already claimed (so the+ # unclaimed-IP step skips it); the host must still find its own row.+ container_row = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.198", mac="a0:36:9f:77:f9:44",+ discovery_source="arp", discovery_sources=["arp"], status="pending",+ )+ db_session.add(container_row)+ await db_session.commit()+ host_row = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.231", mac="a0:36:9f:77:f9:44",+ ieee_address="unifi-a0:36:9f:77:f9:44",+ discovery_source="unifi-client", discovery_sources=["unifi-client"], status="pending",+ )+ db_session.add(host_row)+ await db_session.commit()++ await _persist_pending_import(db_session, [_host()], [])++ await db_session.refresh(container_row)+ await db_session.refresh(host_row)+ assert host_row.ieee_address == HOST+ assert container_row.ieee_address is None+++async def test_persist_merges_ipvlan_container_by_ip(db_session) -> None:+ scanned = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.198", discovery_source="arp",+ discovery_sources=["arp"], status="pending",+ )+ db_session.add(scanned)+ await db_session.commit()++ await _persist_pending_import(db_session, [_ct("netdata", ip="10.1.1.198")], [])++ await db_session.refresh(scanned)+ assert scanned.ieee_address == _ct("netdata")["ieee_address"]+ assert scanned.suggested_type == "docker_container"+++async def test_ip_match_skips_rows_another_importer_owns(db_session) -> None:+ guest = InventoryDevice(+ id=str(uuid.uuid4()), ip="10.1.1.198", ieee_address="pve-pve1-101",+ discovery_source="proxmox", discovery_sources=["proxmox"], status="pending",+ )+ db_session.add(guest)+ await db_session.commit()++ await _persist_pending_import(db_session, [_ct("netdata", ip="10.1.1.198")], [])++ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert len(rows) == 2+ await db_session.refresh(guest)+ assert guest.ieee_address == "pve-pve1-101"+++async def test_web_ui_service_is_stored_and_a_rename_survives(db_session) -> None:+ plex = {**_ct("plex"), "services": [WEB_UI]}+ await _persist_pending_import(db_session, [plex], [])+ row = (await db_session.execute(select(InventoryDevice))).scalar_one()+ assert row.services == [WEB_UI]++ row.services = [{**WEB_UI, "service_name": "Plex"}]+ await db_session.commit()+ await _persist_pending_import(db_session, [plex], [])++ await db_session.refresh(row)+ assert len(row.services) == 1+ assert row.services[0]["service_name"] == "Plex"+++async def test_reimport_replaces_a_stored_secret_in_the_web_ui(db_session) -> None:+ # A row imported before credentials were stripped heals on the next import:+ # the service on the same port takes the clean address.+ leaky = {**WEB_UI, "host": "http://admin:[email protected]:32400", "path": "/web?token=abc"}+ await _persist_pending_import(db_session, [{**_ct("plex"), "services": [leaky]}], [])+ await _persist_pending_import(db_session, [{**_ct("plex"), "services": [WEB_UI]}], [])++ row = (await db_session.execute(select(InventoryDevice))).scalar_one()+ assert len(row.services) == 1+ assert row.services[0]["host"] == WEB_UI["host"]+ assert row.services[0]["path"] == WEB_UI["path"]+++async def test_reimport_keeps_status(db_session) -> None:+ nodes, edges = _inventory(_ct("plex"))+ await _persist_pending_import(db_session, nodes, edges)+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ host = next(r for r in rows if r.ieee_address == HOST)+ plex = next(r for r in rows if r.ieee_address != HOST)+ host.status = "approved"+ plex.status = "hidden"+ db_session.add(Node(id=str(uuid.uuid4()), type="docker_host", label="Pearl", device_id=host.id, pos_x=0, pos_y=0))+ await db_session.commit()++ await _persist_pending_import(db_session, nodes, edges)++ await db_session.refresh(host)+ await db_session.refresh(plex)+ assert host.status == "approved"+ assert plex.status == "hidden"+++async def test_approved_but_undrawn_row_is_revived(db_session) -> None:+ nodes, edges = _inventory()+ await _persist_pending_import(db_session, nodes, edges)+ host = (await db_session.execute(select(InventoryDevice))).scalar_one()+ host.status = "approved"+ await db_session.commit()++ await _persist_pending_import(db_session, nodes, edges)++ await db_session.refresh(host)+ assert host.status == "pending"+++async def test_links_replaced_per_host_only(db_session) -> None:+ other = "unraid-host-other"+ db_session.add(InventoryDeviceLink(source_ieee=other, target_ieee="unraid-other-ct-x", discovery_source="unraid"))+ await db_session.commit()++ nodes, edges = _inventory(_ct("plex"))+ await _persist_pending_import(db_session, nodes, edges)+ await _persist_pending_import(db_session, nodes, edges)++ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()+ assert {(link.source_ieee, link.target_ieee) for link in links} == {+ (other, "unraid-other-ct-x"),+ (HOST, _ct("plex")["ieee_address"]),+ }diff --git a/backend/tests/test_unraid_service.py b/backend/tests/test_unraid_service.pynew file mode 100644index 0000000..5a17959--- /dev/null+++ b/backend/tests/test_unraid_service.py@@ -0,0 +1,311 @@+"""Unit tests for the Unraid import service (parsing, properties, errors)."""++from __future__ import annotations++import httpx+import pytest++from app.services import unraid_service as svc++HOST_UUID = "AA67F8CB-8DEA-8A1D-AB9C-D8BBC16C6573"+HOST_KEY = HOST_UUID.lower()+++def _container(name: str, network: str, ip: str = "", mac: str = "", state: str = "RUNNING", **extra) -> dict:+ return {+ "id": f"server:{name}id",+ "names": [f"/{name}"],+ "image": f"img/{name}:latest",+ "state": state,+ "webUiUrl": None,+ "labels": {},+ "lanIpPorts": None,+ "hostConfig": {"networkMode": network},+ "networkSettings": {"Networks": {network: {"IPAddress": ip, "MacAddress": mac}}},+ **extra,+ }+++def _payload(containers: list[dict]) -> dict:+ return {+ "info": {+ "system": {"uuid": HOST_UUID, "manufacturer": "MSI", "model": "MS-7D25"},+ "cpu": {"brand": "Core i5-13600K", "threads": 20},+ "os": {"hostname": "Pearl"},+ "primaryNetwork": {"macAddress": "A0:36:9F:77:F9:44", "ipAddress": "10.1.1.231"},+ "versions": {"core": {"unraid": "7.3.1"}},+ },+ "docker": {+ "networks": [+ {"name": "bridge", "driver": "bridge"},+ {"name": "br0", "driver": "ipvlan"},+ {"name": "mv0", "driver": "macvlan"},+ {"name": "host", "driver": "host"},+ ],+ "containers": containers,+ },+ }+++def test_host_node_from_info() -> None:+ nodes, edges = svc._parse_inventory(_payload([]))+ assert edges == []+ host = nodes[0]+ assert host["ieee_address"] == f"unraid-host-{HOST_KEY}"+ assert host["type"] == "docker_host"+ assert host["ip"] == "10.1.1.231"+ assert host["mac"] == "a0:36:9f:77:f9:44"+ assert host["cpu_count"] == 20+ assert host["model"] == "MSI MS-7D25"+ assert host["os_version"] == "Unraid 7.3.1"+++def test_host_key_falls_back_to_hostname() -> None:+ data = _payload([])+ data["info"]["system"]["uuid"] = None+ nodes, _ = svc._parse_inventory(data)+ assert nodes[0]["ieee_address"] == "unraid-host-pearl"+++def test_server_web_ui_is_the_address_the_import_used() -> None:+ assert svc._server_web_ui("10.1.1.231", 80, False)["host"] == "http://10.1.1.231"+ assert svc._server_web_ui("10.1.1.231", 443, True)["host"] == "https://10.1.1.231"+ custom = svc._server_web_ui("tower.local", 8443, True)+ assert (custom["host"], custom["port"], custom["service_name"]) == ("https://tower.local:8443", 8443, "Web UI")+ assert svc._server_web_ui("fd00::5", 80, False)["host"] == "http://[fd00::5]"+++def test_container_identity_is_host_and_name() -> None:+ nodes, edges = svc._parse_inventory(_payload([_container("plex", "host")]))+ plex = nodes[1]+ assert plex["ieee_address"] == f"unraid-{HOST_KEY}-ct-plex"+ assert plex["type"] == "docker_container"+ assert plex["parent_ieee"] == f"unraid-host-{HOST_KEY}"+ assert edges == [{"source": f"unraid-host-{HOST_KEY}", "target": plex["id"]}]+++def test_bridge_container_gets_no_address() -> None:+ # The 172.x address is internal to the host and the MAC changes on every+ # recreate - neither may identify the container.+ nodes, _ = svc._parse_inventory(_payload([_container("app", "bridge", "172.17.0.3", "12:64:29:75:17:49")]))+ assert nodes[1]["ip"] is None+ assert nodes[1]["mac"] is None+++def test_ipvlan_container_gets_ip_but_never_a_mac() -> None:+ # ipvlan shares the parent interface's MAC with the host.+ nodes, _ = svc._parse_inventory(_payload([_container("netdata", "br0", "10.1.1.198", "a0:36:9f:77:f9:44")]))+ assert nodes[1]["ip"] == "10.1.1.198"+ assert nodes[1]["mac"] is None+++def test_macvlan_container_keeps_its_own_mac() -> None:+ nodes, _ = svc._parse_inventory(_payload([_container("pihole", "mv0", "10.1.1.53", "02:42:0A:01:01:35")]))+ assert nodes[1]["ip"] == "10.1.1.53"+ assert nodes[1]["mac"] == "02:42:0a:01:01:35"+++def test_container_network_mode_resolves_to_a_name() -> None:+ vpn = _container("vpn", "bridge")+ stash = _container("stash", "container:vpnid")+ stash["networkSettings"] = {"Networks": {}}+ nodes, _ = svc._parse_inventory(_payload([vpn, stash]))+ assert nodes[2]["network"] == "container:vpn"+++def test_stopped_container_is_offline() -> None:+ nodes, _ = svc._parse_inventory(_payload([_container("old", "bridge", state="EXITED")]))+ assert nodes[1]["status"] == "offline"+++def test_container_properties() -> None:+ ct = _container(+ "jellyfin", "bridge",+ webUiUrl="http://10.1.1.231:8096",+ lanIpPorts=["10.1.1.231:8096", "10.1.1.231:8096", "10.1.1.231:7359"],+ labels={"com.docker.compose.project": "media"},+ )+ nodes, _ = svc._parse_inventory(_payload([ct]))+ props = {p["key"]: p["value"] for p in svc.build_unraid_properties(nodes[1])}+ assert props["Image"] == "img/jellyfin:latest"+ assert props["Ports"] == "10.1.1.231:7359, 10.1.1.231:8096"+ assert "Web UI" not in props+ assert props["Compose Project"] == "media"+ assert props["Source"] == "Unraid"+++def test_web_ui_becomes_a_service() -> None:+ ct = _container("jellyfin", "bridge", webUiUrl="http://10.1.1.231:8096")+ nodes, _ = svc._parse_inventory(_payload([ct]))+ assert nodes[1]["services"] == [{+ "port": 8096, "protocol": "tcp", "service_name": "Web UI",+ "host": "http://10.1.1.231:8096", "path": "",+ }]+++def test_web_ui_points_at_the_containers_own_lan_ip() -> None:+ # Unraid resolves [IP] to the server, but an ipvlan/macvlan container only+ # answers on its own address.+ ct = _container("netdata", "br0", "10.1.1.198", webUiUrl="http://10.1.1.231:19999")+ nodes, _ = svc._parse_inventory(_payload([ct]))+ assert nodes[1]["services"][0]["host"] == "http://10.1.1.198:19999"+++def test_web_ui_service_unescapes_the_template_query() -> None:+ service = svc._web_ui_service(+ "http://10.1.1.231:6080/vnc.html?resize=remote&host=10.1.1.231&port=6080"+ )+ assert service is not None+ assert service["path"] == "/vnc.html?resize=remote&host=10.1.1.231&port=6080"+++def test_web_ui_service_drops_credentials() -> None:+ service = svc._web_ui_service("http://admin:[email protected]:8080/app?token=abc&lang=en&api_key=xyz") # trufflehog:ignore+ assert service is not None+ assert service["host"] == "http://10.1.1.231:8080"+ assert service["path"] == "/app?lang=en"+ assert "hunter2" not in str(service) and "abc" not in str(service) and "xyz" not in str(service)+++def test_web_ui_service_keeps_ordinary_params() -> None:+ # Whole-name matching: these merely contain a secret-looking fragment.+ service = svc._web_ui_service("http://10.1.1.231:6080/vnc.html?design=1&autoconnect=1&keyboard=us")+ assert service is not None+ assert service["path"] == "/vnc.html?design=1&autoconnect=1&keyboard=us"+++def test_secret_param_names() -> None:+ for name in ("token", "X-Api-Key", "api_key", "access_token", "PASSWORD", "admin_password", "sig"):+ assert svc._is_secret_param(name), name+ for name in ("host", "port", "resize", "design", "autoconnect", "keyboard", "lang"):+ assert not svc._is_secret_param(name), name+++def test_web_ui_service_defaults_the_scheme_port() -> None:+ service = svc._web_ui_service("https://10.1.1.231/")+ assert service is not None+ assert service["port"] == 443+ assert service["host"] == "https://10.1.1.231"+++def test_no_service_without_a_usable_web_ui() -> None:+ assert svc._web_ui_service(None) is None+ assert svc._web_ui_service("ftp://10.1.1.231:21") is None+ assert svc._web_ui_service("http://10.1.1.231:notaport") is None+ nodes, _ = svc._parse_inventory(_payload([_container("redis", "bridge")]))+ assert nodes[1]["services"] == []+++def test_malformed_payload_raises() -> None:+ with pytest.raises(ValueError):+ svc._parse_inventory({"info": None, "docker": {}})+++def test_unauthenticated_graphql_error_is_auth_error() -> None:+ payload = {"errors": [{"message": "API key validation failed", "extensions": {"code": "UNAUTHENTICATED"}}]}+ with pytest.raises(svc.UnraidAuthError):+ svc._graphql_errors(payload)+++def test_other_graphql_error_is_value_error() -> None:+ with pytest.raises(ValueError, match="boom"):+ svc._graphql_errors({"errors": [{"message": "boom"}]})+++def test_client_uses_the_chosen_scheme() -> None:+ assert svc._client("tower", 8080, "k", False, False).base_url.scheme == "http"+ assert svc._client("tower", 8443, "k", False, True).base_url.scheme == "https"+++def test_redirect_to_https_says_to_use_https() -> None:+ req = httpx.Request("POST", "http://tower:80/graphql")+ resp = httpx.Response(302, request=req, headers={"location": "https://tower/graphql"})+ exc = httpx.HTTPStatusError("x", request=req, response=resp)+ assert svc._sanitize_unraid_error(exc) == "This server uses HTTPS - tick 'Use HTTPS'"+++def test_https_to_a_plain_http_port_says_to_untick() -> None:+ exc = httpx.ConnectError("[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1032)")+ assert "untick 'Use HTTPS'" in svc._sanitize_unraid_error(exc)+++def test_sanitizer_hides_details() -> None:+ req = httpx.Request("POST", "https://h/graphql", headers={"x-api-key": "secret"})+ exc = httpx.HTTPStatusError("x", request=req, response=httpx.Response(403, request=req))+ msg = svc._sanitize_unraid_error(exc)+ assert "secret" not in msg+ assert "Authentication failed" in msg+ assert "TLS" in svc._sanitize_unraid_error(httpx.ConnectError("certificate verify failed"))+++VMS = [+ {"id": "server:AC4A600A-C5F8-C5A5-B82A-5F9B46FC8167", "name": "UbuntuServer", "state": "RUNNING"},+ {"id": "server:bde24b48-b75b-24de-0280-c2aacec154b5", "name": "Mhmmint", "state": "SHUTOFF"},+]+++def test_vm_nodes_are_keyed_on_their_uuid() -> None:+ nodes, edges = svc._parse_inventory(_payload([]), VMS)+ ubuntu, mint = nodes[1], nodes[2]+ assert ubuntu["ieee_address"] == f"unraid-{HOST_KEY}-vm-ac4a600a-c5f8-c5a5-b82a-5f9b46fc8167"+ assert ubuntu["type"] == "vm"+ assert ubuntu["status"] == "online"+ assert mint["status"] == "offline"+ # No address of its own in the API: nothing to match a scanned row on.+ assert ubuntu["ip"] is None and ubuntu["mac"] is None+ assert edges[0] == {"source": f"unraid-host-{HOST_KEY}", "target": ubuntu["id"]}+ props = {p["key"]: p["value"] for p in svc.build_unraid_properties(ubuntu)}+ assert props["UUID"] == "ac4a600a-c5f8-c5a5-b82a-5f9b46fc8167"+++def _mock_client(monkeypatch: pytest.MonkeyPatch, vm_response: dict) -> None:+ """Answer the inventory query with one container and the VM query with ``vm_response``."""+ def handler(request: httpx.Request) -> httpx.Response:+ assert request.headers["x-api-key"] == "k"+ query = request.read().decode()+ if "vms" in query:+ return httpx.Response(200, json=vm_response)+ if "versions" in query and "docker" not in query:+ return httpx.Response(200, json={"data": {"info": {+ "os": {"hostname": "Pearl"}, "versions": {"core": {"unraid": "7.3.1"}},+ }}})+ return httpx.Response(200, json={"data": _payload([_container("plex", "host")])})++ def fake_client(host: str, port: int, api_key: str, verify_tls: bool, use_https: bool) -> httpx.AsyncClient:+ return httpx.AsyncClient(+ base_url=f"{'https' if use_https else 'http'}://{host}:{port}",+ headers={"x-api-key": api_key},+ transport=httpx.MockTransport(handler),+ )++ monkeypatch.setattr(svc, "_client", fake_client)+++FORBIDDEN = {"errors": [{"message": "Forbidden", "extensions": {"code": "FORBIDDEN"}}], "data": None}+++async def test_fetch_inventory_round_trip(monkeypatch: pytest.MonkeyPatch) -> None:+ _mock_client(monkeypatch, {"data": {"vms": {"domains": VMS}}})+ nodes, edges, notice = await svc.fetch_unraid_inventory("h", 443, "k", verify_tls=False, use_https=True)+ assert [n["type"] for n in nodes] == ["docker_host", "docker_container", "vm", "vm"]+ assert nodes[0]["services"] == [svc._server_web_ui("h", 443, True)]+ assert len(edges) == 3+ assert notice is None+++async def test_no_vm_access_keeps_the_containers(monkeypatch: pytest.MonkeyPatch) -> None:+ _mock_client(monkeypatch, FORBIDDEN)+ nodes, _, notice = await svc.fetch_unraid_inventory("h", 443, "k", verify_tls=False)+ assert [n["type"] for n in nodes] == ["docker_host", "docker_container"]+ assert notice is not None and "no read access to VMs" in notice+++async def test_connection_test_mentions_missing_vm_access(monkeypatch: pytest.MonkeyPatch) -> None:+ _mock_client(monkeypatch, FORBIDDEN)+ connected, message = await svc.test_unraid_connection("h", 443, "k", verify_tls=False)+ assert connected is True+ assert message.startswith("Connected to Pearl (Unraid 7.3.1)")+ assert "no read access to VMs" in messagediff --git a/docs/unraid-import.md b/docs/unraid-import.mdnew file mode 100644index 0000000..ff8389e--- /dev/null+++ b/docs/unraid-import.md@@ -0,0 +1,125 @@+# Unraid Import++Connects Homelable to an Unraid server, reads the server, its Docker+containers and its VMs over the Unraid API, and brings them into the Device+Inventory (and, optionally, onto the canvas) as typed nodes. It can also+**sync** on a schedule.++> **Server-dependent feature** - requires the Homelable backend. It is hidden in+> the no-backend standalone/demo build.++---++## What is imported++- **The server** as a `docker_host` node: hostname, LAN IP, NIC MAC, board+ maker/model, CPU model and thread count, Unraid version, and a+ **Web UI** service at the address the import connected to.+- **Every Docker container** as a `docker_container` node, linked to the server+ with a `virtual` edge. Each container carries hidden-by-default properties:+ Image, Network, Ports and, for containers started by a Compose plugin,+ Compose Project.+- **The container's web UI** (the WebUI address from its Unraid template) as a+ **Web UI** service on the node, so it shows up as a link and, with service+ checks on, gets checked. Unraid resolves the address to the server IP; a+ container with its own LAN IP gets that IP instead, since that is where it+ answers. Re-imports refresh the address but keep a name or icon you gave it.+- **Every VM** as a `vm` node, linked to the server with a `virtual` edge and+ keyed on its libvirt UUID (a hidden **UUID** property). The Unraid API reports+ a VM's name and run state only - no NIC MAC, IP, vCPUs or RAM - so a VM is+ never matched to a device a network scan already found. If a scan found the+ VM first, merge the two rows from the Device Inventory.++Containers managed by Unraid's own Docker page and containers started by a+Docker Compose plugin are both listed by the API and imported the same way.++If the API key cannot read VMs, the containers still import and the dialog+(or the Scan History entry) says why VMs were left out.++---++## Prerequisites++1. Unraid 7.2 or newer, where the GraphQL API is built in (tested on **Unraid+ 7.3.1**, API 4.37). Earlier releases get the API from the Unraid Connect+ plugin; untested.+2. An **API key**: *Settings > Management Access > API Keys*. Read access to+ **Docker**, **VMs** and **Info** is all the import needs.+3. The server reachable from the Homelable backend over HTTP or HTTPS. Unraid+ serves plain HTTP unless *Settings > Management Access > Use SSL/TLS* is on,+ so **Use HTTPS** is off by default; over HTTP the API key travels+ unencrypted. With HTTPS, Unraid's own certificate is self-signed, so+ **Verify TLS certificate** is off too; tick it when the server has a trusted+ certificate, such as the `myunraid.net` address. Picking the wrong scheme+ gets a message saying which one the server wants.++---++## Importing++Open **Import** in the sidebar and pick **Unraid**. Enter the host, port+(blank for 80, or 443 with **Use HTTPS**) and API key, then choose where devices go:++- **Device inventory only** - runs in the background; follow it in Scan+ History, then approve devices from the Device Inventory. Approving the+ server asks whether to bring its containers and VMs along, placed beside it and+ joined by virtual edges.+- **Inventory + canvas** - fetches immediately, lists the server, containers and VMs,+ and adds the ones you tick to the canvas. They land in the inventory too.++### Stopped containers and VMs++**Include stopped containers and VMs** (on by default) means the same in both+modes: stopped devices are imported like running ones and, in *Inventory ++canvas* mode, listed for the canvas. Untick it to leave them out of both.++As with the Proxmox import, *Inventory + canvas* adds everything it lists to+the Device Inventory when you fetch, including devices you then untick before+adding to the canvas.++---++## Addresses and matching++Docker networking decides what address a container has:++- **Bridge / custom networks** (the default): the container's `172.x` address is+ internal to the server and its MAC changes every time Unraid recreates it, so+ neither is stored. Reach it through the server IP and the published ports in+ the **Ports** property.+- **`br0` / custom macvlan or ipvlan networks**: the container has its own LAN+ IP, which is stored. With **ipvlan** every container shares the server's+ MAC, so the MAC is never used for these.+- **`host`**: no address of its own; it is the server.+- **`container:<name>`**: shares another container's network (e.g. a VPN+ sidecar); the **Network** property names that container.++A container is identified by the server's UUID plus the container *name*, since+Unraid gives a container a new Docker id on every update. Re-importing updates+devices in place and never deletes anything; a hidden device stays hidden.++An existing inventory row is reused, in this order, when it has the same+identity, the same IP and MAC, the same IP (rows no other importer claimed), or+the same MAC - so a server or `br0` container an IP scan found first is merged,+not duplicated.++---++## Auto-sync++Connection settings live in the server `.env` only. The API key is never+written to disk by the app and never returned by the API.++```env+UNRAID_HOST=192.168.1.20+UNRAID_API_KEY=xxxxxxxxxxxxxxxx+UNRAID_USE_HTTPS=false+# UNRAID_PORT=80 # defaults to 80, or 443 with UNRAID_USE_HTTPS=true+UNRAID_VERIFY_TLS=false+```++With those set, **Settings > Unraid auto-sync** turns on a scheduled import into+the pending inventory (minimum 5 minutes), chooses whether stopped containers+and VMs are included, and offers **Re-sync now**. The dialog can use the `.env` key for+the configured host and port only, and never over HTTP when+`UNRAID_USE_HTTPS=true`; any other host needs its own key.diff --git a/frontend/src/App.tsx b/frontend/src/App.tsxindex da23d07..197a469 100644--- a/frontend/src/App.tsx+++ b/frontend/src/App.tsx@@ -30,6 +30,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 { UnraidImportModal } from '@/components/unraid/UnraidImportModal'import { UnifiImportModal } from '@/components/unifi/UnifiImportModal'import { ImportSourceModal, type ImportSourceKey } from '@/components/modals/ImportSourceModal'import { GroupRectModal, type GroupRectFormData } from '@/components/modals/GroupRectModal'@@ -71,6 +72,7 @@ import type { NodeData, EdgeData, CustomStyleDef, DesignType, FloorMapConfig, Noimport type { ZigbeeNode, ZigbeeEdge } from '@/components/zigbee/types'import type { ZwaveNode, ZwaveEdge } from '@/components/zwave/types'import type { ProxmoxNode, ProxmoxEdge, ProxmoxCanvasMode } from '@/components/proxmox/types'+import type { UnraidNode, UnraidEdge } from '@/components/unraid/types'import { buildProxmoxClusterEdges } from '@/components/proxmox/clusterEdges'import { groupProxmoxGuests, layoutProxmoxContainers, measureProxmoxContainers } from '@/utils/proxmoxContainerLayout'@@ -162,6 +164,7 @@ export default function App() {const [zigbeeImportOpen, setZigbeeImportOpen] = useState(false)const [zwaveImportOpen, setZwaveImportOpen] = useState(false)const [proxmoxImportOpen, setProxmoxImportOpen] = useState(false)+ const [unraidImportOpen, setUnraidImportOpen] = useState(false)const [unifiImportOpen, setUnifiImportOpen] = useState(false)const [importPickerOpen, setImportPickerOpen] = useState(false)@@ -374,6 +377,7 @@ export default function App() {if (source === 'zigbee') setZigbeeImportOpen(true)else if (source === 'zwave') setZwaveImportOpen(true)else if (source === 'proxmox') setProxmoxImportOpen(true)+ else if (source === 'unraid') setUnraidImportOpen(true)else setUnifiImportOpen(true)}, [])@@ -1082,6 +1086,71 @@ export default function App() {markUnsaved()}, [addNode, onConnect, snapshotHistory, markUnsaved])+ const handleUnraidAddToCanvas = useCallback((urNodes: UnraidNode[], urEdges: UnraidEdge[]) => {+ snapshotHistory()+ const COLS = 6+ const SPACING_X = 190+ const SPACING_Y = 110+ // The server on its own row, its VMs then its containers in a grid below.+ const hosts = urNodes.filter((n) => n.type === 'docker_host')+ const containers = [+ ...urNodes.filter((n) => n.type === 'vm'),+ ...urNodes.filter((n) => n.type === 'docker_container'),+ ]+ const cols = Math.min(COLS, Math.max(containers.length, 1))+ const rows = Math.ceil(containers.length / COLS) + (hosts.length ? 1 : 0)+ const origin = getCenteredPosition(cols * SPACING_X, rows * SPACING_Y)+ const placement: Record<string, { x: number; y: number }> = {}+ hosts.forEach((n, i) => {+ placement[n.id] = { x: origin.x + ((cols - hosts.length) / 2 + i) * SPACING_X, y: origin.y }+ })+ const top = hosts.length ? SPACING_Y : 0+ containers.forEach((n, i) => {+ placement[n.id] = {+ x: origin.x + (i % COLS) * SPACING_X,+ y: origin.y + top + Math.floor(i / COLS) * SPACING_Y,+ }+ })+ urNodes.forEach((un) => {+ const newNode: import('@xyflow/react').Node<NodeData> = {+ id: un.id,+ type: un.type,+ position: placement[un.id] ?? getCenteredPosition(),+ data: {+ label: un.label,+ type: un.type as NodeData['type'],+ status: (un.status === 'online' ? 'online' : 'unknown') as NodeData['status'],+ // The row's lists, not empty ones: a new node's first save replaces+ // the row's with whatever it holds.+ services: un.services ?? [],+ properties: un.properties ?? [],+ // Same as the Proxmox import: the row exists already, point at it.+ ...(un.device_id ? { device_id: un.device_id } : {}),+ ...(un.ip ? { ip: un.ip } : {}),+ ...(un.hostname ? { hostname: un.hostname } : {}),+ },+ }+ addNode(newNode)+ })+ // Host -> container links render as 'virtual' edges, like Proxmox host -> guest.+ urEdges.forEach((ue) => {+ onConnect({+ source: ue.source,+ sourceHandle: 'bottom',+ target: ue.target,+ targetHandle: 'top-t',+ type: 'virtual',+ } as unknown as import('@xyflow/react').Connection)+ })+ const importedIds = new Set(urNodes.map((un) => un.id))+ useCanvasStore.setState((state) => ({+ nodes: state.nodes.map((n) => ({ ...n, selected: importedIds.has(n.id) })),+ selectedNodeIds: Array.from(importedIds),+ selectedNodeId: importedIds.size === 1 ? Array.from(importedIds)[0] : null,+ }))+ markUnsaved()+ }, [addNode, onConnect, snapshotHistory, markUnsaved])+const handleEdgeConnect = useCallback((connection: Connection) => {setPendingConnection(connection)}, [])@@ -1357,6 +1426,17 @@ export default function App() {/>)}+ {!STANDALONE && (+ <UnraidImportModal+ open={unraidImportOpen}+ onClose={() => setUnraidImportOpen(false)}+ onAddToCanvas={handleUnraidAddToCanvas}+ onInventoryImported={() => {+ toast.success('Unraid import started - check Scan History for results')+ }}+ />+ )}+{!STANDALONE && (<UnifiImportModalopen={unifiImportOpen}diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex bb52bcd..e616f5b 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -335,6 +335,46 @@ export const proxmoxApi = {}>('/proxmox/sync-now'),}+export interface UnraidConnection {+ host: string+ /** Omitted = 443 for HTTPS, 80 for HTTP. */+ port?: number+ api_key?: string+ use_https?: boolean+ verify_tls?: boolean+ /** Import (and list) stopped containers and VMs too. */+ include_offline?: boolean+}++export interface UnraidConfigData {+ host: string+ port: number+ use_https: boolean+ verify_tls: boolean+ sync_enabled: boolean+ sync_interval: number+ include_offline: boolean+ api_key_configured: boolean+}++export const unraidApi = {+ testConnection: (data: UnraidConnection) =>+ api.post<{ connected: boolean; message: string }>('/unraid/test-connection', data),++ importNetwork: (data: UnraidConnection) =>+ api.post<import('@/components/unraid/types').UnraidImportResponse>('/unraid/import', data),++ importToPending: (data: UnraidConnection) =>+ api.post<ScanRunResult>('/unraid/import-pending', data),++ getConfig: () => api.get<UnraidConfigData>('/unraid/config'),+ // Only the auto-sync activation is persisted; connection config is env-only.+ saveConfig: (data: { sync_enabled: boolean; sync_interval: number; include_offline: boolean }) =>+ api.post<UnraidConfigData>('/unraid/config', data),++ syncNow: () => api.post<ScanRunResult>('/unraid/sync-now'),+}+export const designsApi = {list: () => api.get<import('@/types').Design[]>('/designs'),create: (data: { name: string; icon?: string; design_type?: string }) =>diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsxindex b533d95..342b36f 100644--- a/frontend/src/components/modals/DeviceInventoryModal.tsx+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx@@ -22,7 +22,7 @@ import { getCenteredPosition } from '@/utils/viewportCenter'import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/deviceSources'import { isRackable } from '@/utils/rackable'import { isTypingTarget } from '@/utils/keyboard'-import { ProxmoxApproveModal, type ProxmoxApproveChoice } from '@/components/modals/ProxmoxApproveModal'+import { ProxmoxApproveModal, type ProxmoxApproveChoice, type GuestHostSource } from '@/components/modals/ProxmoxApproveModal'import { MergeDevicesModal } from '@/components/modals/MergeDevicesModal'import { layoutProxmoxContainers, measureProxmoxContainers } from '@/utils/proxmoxContainerLayout'@@ -97,6 +97,14 @@ function deviceType(d: InventoryEntry): NodeType | null {return ((d.type ?? d.suggested_type) as NodeType) ?? null}+/** The import whose host -> guest links this device heads, if any. */+function guestHostSource(d: InventoryEntry): GuestHostSource | null {+ const type = deviceType(d)+ if (type === 'proxmox') return 'proxmox'+ if (type === 'docker_host' && sourceBuckets(d).has('unraid')) return 'unraid'+ return null+}+function specialServiceName(d: InventoryEntry): string | undefined {const candidates = (d.services ?? []).filter((s) => s.category != null && s.port != null && !COMMON_PORTS.has(s.port) && s.service_name,@@ -189,7 +197,7 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatusconst [dupPrompt, setDupPrompt] = useState<{ device: InventoryEntry; conflict: DuplicateNodeConflict } | null>(null)// Set when a Proxmox host with guests is about to be placed — the user picks// whether the guests come along, and nested or linked.- const [proxmoxPrompt, setProxmoxPrompt] = useState<{ host: InventoryEntry; children: InventoryEntry[] } | null>(null)+ const [proxmoxPrompt, setProxmoxPrompt] = useState<{ host: InventoryEntry; children: InventoryEntry[]; source: GuestHostSource } | null>(null)// Set when the user asks to merge the selected rows — they pick the survivor.const [mergePrompt, setMergePrompt] = useState<InventoryEntry[] | null>(null)const [merging, setMerging] = useState(false)@@ -422,15 +430,16 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus}}- // A Proxmox host is rarely wanted on its own: ask about its guests first.- // Anything else — and a host with no guests in the inventory — goes straight- // through the normal single-device approve.+ // A Proxmox host or an Unraid server is rarely wanted on its own: ask about+ // its guests first. Anything else - and a host with no guests in the+ // inventory - goes straight through the normal single-device approve.const handleApprove = (device: InventoryEntry) => {- if (deviceType(device) === 'proxmox') { void promptProxmoxChildren(device); return }+ const source = guestHostSource(device)+ if (source) { void promptProxmoxChildren(device, source); return }return approveDevice(device, false)}- const promptProxmoxChildren = async (device: InventoryEntry) => {+ const promptProxmoxChildren = async (device: InventoryEntry, source: GuestHostSource) => {let guests: InventoryEntry[] = []try {guests = (await scanApi.proxmoxChildren(device.id)).data@@ -442,7 +451,7 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus// Close the device-detail modal first: two Base UI dialogs open at once trap// focus on the underlying one and the prompt never shows.setSelected(null)- setProxmoxPrompt({ host: device, children: guests })+ setProxmoxPrompt({ host: device, children: guests, source })}const handleProxmoxConfirm = async ({ childIds, mode }: ProxmoxApproveChoice) => {@@ -517,7 +526,7 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatustoast.info(`${dupes.length} already on this canvas, skipped: ${names}${more}`)}} catch {- toast.error('Failed to add the Proxmox host to the canvas')+ toast.error(`Failed to add the ${prompt.source === 'unraid' ? 'Unraid server' : 'Proxmox host'} to the canvas`)}}@@ -757,6 +766,13 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus>Proxmox</button>+ <button+ onClick={() => setSourceFilter('unraid')}+ className={`px-2.5 py-1.5 transition-colors border-l border-border ${sourceFilter === 'unraid' ? 'bg-[#e22828]/20 text-[#e22828]' : 'bg-[#0d1117] text-muted-foreground hover:text-foreground'}`}+ title="Imported from an Unraid server - Docker containers"+ >+ Unraid+ </button><buttononClick={() => 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'}`}@@ -1032,6 +1048,7 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatusopen={proxmoxPrompt !== null}host={proxmoxPrompt?.host ?? null}guests={proxmoxPrompt?.children ?? []}+ source={proxmoxPrompt?.source}onCancel={() => setProxmoxPrompt(null)}onConfirm={handleProxmoxConfirm}/>diff --git a/frontend/src/components/modals/ImportSourceModal.tsx b/frontend/src/components/modals/ImportSourceModal.tsxindex 1bcd852..521f9f0 100644--- a/frontend/src/components/modals/ImportSourceModal.tsx+++ b/frontend/src/components/modals/ImportSourceModal.tsx@@ -1,9 +1,9 @@-import { Network, RadioTower, Server, Wifi, ArrowRight, Clock } from 'lucide-react'+import { Network, RadioTower, Server, HardDrive, Wifi, ArrowRight, Clock } from 'lucide-react'import type { LucideIcon } from 'lucide-react'import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'import { brandIconUrl } from '@/utils/nodeIcons'-export type ImportSourceKey = 'zigbee' | 'zwave' | 'proxmox' | 'unifi'+export type ImportSourceKey = 'zigbee' | 'zwave' | 'proxmox' | 'unraid' | 'unifi'interface ImportSourceModalProps {open: boolean@@ -63,6 +63,16 @@ const SOURCES: ImportSource[] = [duration: '~10 s',imports: ['Hosts', 'VMs', 'LXC'],},+ {+ key: 'unraid',+ label: 'Unraid',+ brandSlug: 'unraid',+ fallbackIcon: HardDrive,+ accent: '#e22828',+ description: 'Reads the Unraid API for the server and every Docker container and VM it runs.',+ duration: '~5 s',+ imports: ['Server', 'Containers', 'VMs'],+ },{key: 'unifi',label: 'UniFi',@@ -85,7 +95,7 @@ export function ImportSourceModal({ open, onClose, onPick }: ImportSourceModalPr<Dialog open={open} onOpenChange={(v) => !v && onClose()}>{/* The dialog primitive pins `sm:max-w-sm`, and a variant utility outranksevery plain `max-w-*` class — only an inline width actually widens it,- and four tiles need the room. */}+ and five tiles need the room. */}<DialogContentclassName="bg-[#161b22] border-border max-h-[85vh] flex flex-col"style={{ maxWidth: 'min(1120px, calc(100vw - 3rem))' }}@@ -99,7 +109,7 @@ export function ImportSourceModal({ open, onClose, onPick }: ImportSourceModalPr</DialogHeader><div className="flex-1 overflow-y-auto min-h-0 py-2">- <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3">+ <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">{SOURCES.map((source) => (<ImportSourceTile key={source.key} source={source} onPick={() => onPick(source.key)} />))}diff --git a/frontend/src/components/modals/ProxmoxApproveModal.tsx b/frontend/src/components/modals/ProxmoxApproveModal.tsxindex 2c11977..51b9333 100644--- a/frontend/src/components/modals/ProxmoxApproveModal.tsx+++ b/frontend/src/components/modals/ProxmoxApproveModal.tsx@@ -5,7 +5,21 @@ import { Button } from '@/components/ui/button'import type { InventoryEntry } from '@/types'import type { ProxmoxCanvasMode } from '@/components/proxmox/types'-const ACCENT = '#e57000'+/** The import that recorded the host's guests decides the wording and colour. */+export type GuestHostSource = 'proxmox' | 'unraid'++const SOURCE_COPY: Record<GuestHostSource, { accent: string; noun: string; detail: string }> = {+ proxmox: {+ accent: '#e57000',+ noun: 'guest',+ detail: 'VMs and LXC containers this host runs, as recorded by the Proxmox import.',+ },+ unraid: {+ accent: '#e22828',+ noun: 'guest',+ detail: 'Docker containers and VMs this server runs, as recorded by the Unraid import.',+ },+}export interface ProxmoxApproveChoice {/** Guest inventory ids to place alongside the host. Empty = host only. */@@ -19,6 +33,8 @@ interface ProxmoxApproveModalProps {/** Guests the host runs, from `scanApi.proxmoxChildren`. Deliberately not* named `children` — React would treat the array as renderable child nodes. */guests: InventoryEntry[]+ /** Unraid guests are always drawn linked, never nested. */+ source?: GuestHostSourceonCancel: () => voidonConfirm: (choice: ProxmoxApproveChoice) => void}@@ -30,7 +46,8 @@ function label(d: InventoryEntry): string {/*** Asked before a Proxmox host from the Device Inventory reaches a canvas: bring* its VMs/LXCs along, and if so draw them nested inside the host- * (`container_mode`) or as separate nodes joined by virtual edges.+ * (`container_mode`) or as separate nodes joined by virtual edges. An Unraid+ * server gets the same question about its containers and VMs, always drawn linked.** Only shown when the host actually has guests in the inventory — a host with* none is approved straight away.@@ -39,6 +56,7 @@ export function ProxmoxApproveModal({open,host,guests,+ source = 'proxmox',onCancel,onConfirm,}: ProxmoxApproveModalProps) {@@ -47,10 +65,13 @@ export function ProxmoxApproveModal({if (!host) return null+ const { accent, noun, detail } = SOURCE_COPY[source]+ const canNest = source === 'proxmox'+const confirm = () => {onConfirm({childIds: includeChildren ? guests.map((c) => c.id) : [],- mode: includeChildren ? mode : 'linked',+ mode: includeChildren && canNest ? mode : 'linked',})// Next host starts from the defaults again.setIncludeChildren(true)@@ -62,7 +83,7 @@ export function ProxmoxApproveModal({<DialogContent className="bg-[#161b22] border-border max-w-lg"><DialogHeader><DialogTitle className="text-foreground flex items-center gap-2">- <Server size={16} style={{ color: ACCENT }} />+ <Server size={16} style={{ color: accent }} />Add {label(host)} to canvas</DialogTitle></DialogHeader>@@ -74,19 +95,17 @@ export function ProxmoxApproveModal({checked={includeChildren}onChange={(e) => setIncludeChildren(e.target.checked)}className="w-3 h-3 mt-0.5 cursor-pointer shrink-0"- style={{ accentColor: ACCENT }}+ style={{ accentColor: accent }}/><span><span className="block text-foreground">- Also add its {guests.length} guest{guests.length !== 1 ? 's' : ''}- </span>- <span className="block text-[11px] text-muted-foreground">- VMs and LXC containers this host runs, as recorded by the Proxmox import.+ Also add its {guests.length} {noun}{guests.length !== 1 ? 's' : ''}</span>+ <span className="block text-[11px] text-muted-foreground">{detail}</span></span></label>- {includeChildren && (+ {includeChildren && canNest && (<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">Draw the guests as</span><label className="flex items-start gap-2 text-xs cursor-pointer text-foreground">@@ -96,7 +115,7 @@ export function ProxmoxApproveModal({checked={mode === 'container'}onChange={() => setMode('container')}className="mt-0.5 cursor-pointer shrink-0"- style={{ accentColor: ACCENT }}+ style={{ accentColor: accent }}/><span>Nested inside the host@@ -112,7 +131,7 @@ export function ProxmoxApproveModal({checked={mode === 'linked'}onChange={() => setMode('linked')}className="mt-0.5 cursor-pointer shrink-0"- style={{ accentColor: ACCENT }}+ style={{ accentColor: accent }}/><span>Separate nodes linked to the host@@ -128,7 +147,7 @@ export function ProxmoxApproveModal({<div className="max-h-48 overflow-y-auto space-y-1">{guests.map((c) => {const type = (c.type ?? c.suggested_type) ?? 'vm'- const Icon = type === 'lxc' ? Container : Box+ const Icon = type === 'lxc' || type === 'docker_container' ? Container : Boxconst color = type === 'lxc' ? '#39d353' : '#00d4ff'return (<div@@ -153,7 +172,7 @@ export function ProxmoxApproveModal({<Button variant="ghost" onClick={onCancel}>Cancel</Button><ButtononClick={confirm}- style={{ background: ACCENT, color: '#0d1117' }}+ style={{ background: accent, color: '#0d1117' }}className="gap-1.5"><Plus size={13} />diff --git a/frontend/src/components/modals/ScanHistoryModal.tsx b/frontend/src/components/modals/ScanHistoryModal.tsxindex e5f743d..9dccfc4 100644--- a/frontend/src/components/modals/ScanHistoryModal.tsx+++ b/frontend/src/components/modals/ScanHistoryModal.tsx@@ -1,5 +1,5 @@import { useState, useEffect, useCallback, useRef } from 'react'-import { RefreshCw, X, Loader2, StopCircle, Clock, ScanLine, Network, RadioTower, Server, Wifi, Inbox } from 'lucide-react'+import { RefreshCw, X, Loader2, StopCircle, Clock, ScanLine, Network, RadioTower, Server, Wifi, HardDrive, Inbox } from 'lucide-react'import { Dialog, DialogClose, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip'import { scanApi } from '@/api/client'@@ -24,14 +24,15 @@ interface ScanHistoryModalProps {demoRuns?: ScanRun[]}-type KindFilter = 'all' | 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unifi'+type KindFilter = 'all' | 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unifi' | 'unraid'/** Normalise a ScanRun.kind into one of the known display kinds. */-function runKind(kind: string | undefined): 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unifi' {+function runKind(kind: string | undefined): 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unifi' | 'unraid' {return kind === 'zigbee' ? 'zigbee': kind === 'zwave' ? 'zwave': kind === 'proxmox' ? 'proxmox': kind === 'unifi' ? 'unifi'+ : kind === 'unraid' ? 'unraid': 'ip'}@@ -41,6 +42,7 @@ const KIND_META = {zwave: { label: 'Z-Wave', color: '#ff6e00' },proxmox: { label: 'Proxmox', color: '#e57000' },unifi: { label: 'UniFi', color: '#0559c9' },+ unraid: { label: 'Unraid', color: '#e22828' },} as consttype StatusFilter = 'all' | 'running' | 'done' | 'error' | 'cancelled'@@ -59,6 +61,7 @@ const KIND_FILTERS: { key: KindFilter; label: string }[] = [{ key: 'zwave', label: 'Z-Wave' },{ key: 'proxmox', label: 'Proxmox' },{ key: 'unifi', label: 'UniFi' },+ { key: 'unraid', label: 'Unraid' },]function statusColor(s: string): string {@@ -114,7 +117,7 @@ export function ScanHistoryModal({ open, onClose, demoRuns }: ScanHistoryModalPrtoast.error(`Scan failed: ${run.error ?? 'unknown error'}`)}if (prev?.status === 'running' && run.status === 'done') {- if (run.kind === 'zigbee' || run.kind === 'zwave' || run.kind === 'proxmox' || run.kind === 'unifi') {+ if (run.kind === 'zigbee' || run.kind === 'zwave' || run.kind === 'proxmox' || run.kind === 'unifi' || run.kind === 'unraid') {const label = KIND_META[runKind(run.kind)].label// A done run can still carry a non-fatal advisory (e.g. Proxmox// imported hosts but the token couldn't see any VMs/LXC).@@ -250,7 +253,7 @@ export function ScanHistoryModal({ open, onClose, demoRuns }: ScanHistoryModalPr{filtered.map((r) => {const kind = runKind(r.kind)const meta = KIND_META[kind]- const KindIcon = kind === 'zigbee' ? Network : kind === 'zwave' ? RadioTower : kind === 'proxmox' ? Server : kind === 'unifi' ? Wifi : ScanLine+ const KindIcon = kind === 'zigbee' ? Network : kind === 'zwave' ? RadioTower : kind === 'proxmox' ? Server : kind === 'unifi' ? Wifi : kind === 'unraid' ? HardDrive : ScanLinereturn (<div key={r.id} className="rounded-lg border border-border bg-[#161b22] p-3"><div className="flex items-center gap-2">diff --git a/frontend/src/components/modals/SettingsModal.tsx b/frontend/src/components/modals/SettingsModal.tsxindex be26825..783f129 100644--- a/frontend/src/components/modals/SettingsModal.tsx+++ b/frontend/src/components/modals/SettingsModal.tsx@@ -4,10 +4,12 @@ import { Button } from '@/components/ui/button'import {settingsApi,proxmoxApi,+ unraidApi,zigbeeApi,zwaveApi,unifiApi,type ProxmoxConfigData,+ type UnraidConfigData,type ZigbeeConfigData,type ZwaveConfigData,type UnifiConfigData,@@ -123,6 +125,9 @@ function MeshAutoSync({// Mirrors UnifiSyncConfig.sync_interval (ge=300, le=86400) on the backend.const UNIFI_MIN_INTERVAL = 300const UNIFI_MAX_INTERVAL = 86400+// Mirrors UnraidSyncConfig.sync_interval (ge=300, le=86400) on the backend.+const UNRAID_MIN_INTERVAL = 300+const UNRAID_MAX_INTERVAL = 86400const UNIFI_SOURCES: { key: keyof UnifiImportModes; label: string; hint: string }[] = [{ key: 'infrastructure', label: 'Infrastructure', hint: 'stat/device — adopted APs, switches, gateways.' },@@ -142,6 +147,11 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {const [pmSyncEnabled, setPmSyncEnabled] = useState(false)const [pmInterval, setPmInterval] = useState(3600)const [pmSyncing, setPmSyncing] = useState(false)+ const [urConfig, setUrConfig] = useState<UnraidConfigData | null>(null)+ const [urSyncEnabled, setUrSyncEnabled] = useState(false)+ const [urInterval, setUrInterval] = useState(3600)+ const [urIncludeOffline, setUrIncludeOffline] = useState(true)+ const [urSyncing, setUrSyncing] = useState(false)const [zbConfig, setZbConfig] = useState<ZigbeeConfigData | null>(null)const [zbSyncEnabled, setZbSyncEnabled] = useState(false)const [zbInterval, setZbInterval] = useState(3600)@@ -186,6 +196,14 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {setPmInterval(res.data.sync_interval)}).catch(() => {/* proxmox not configured */})+ unraidApi.getConfig()+ .then((res) => {+ setUrConfig(res.data)+ setUrSyncEnabled(res.data.sync_enabled)+ setUrInterval(res.data.sync_interval)+ setUrIncludeOffline(res.data.include_offline)+ })+ .catch(() => {/* unraid not configured */})zigbeeApi.getConfig().then((res) => {setZbConfig(res.data)@@ -238,6 +256,18 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {}}+ const handleUrSyncNow = async () => {+ setUrSyncing(true)+ try {+ await unraidApi.syncNow()+ toast.success('Unraid sync started')+ } catch {+ toast.error('Failed to start Unraid sync')+ } finally {+ setUrSyncing(false)+ }+ }+const handleUnSyncNow = async () => {setUnSyncing(true)try {@@ -297,6 +327,18 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {sync_interval: pmInterval,})}+ if (urConfig) {+ // Connection config (host/port/key/verify) is env-only. Clamped as for+ // UniFi: the input's min/max never stop a typed value, and a 422 here+ // would abort the save after the configs above already persisted.+ const clamped = Math.min(UNRAID_MAX_INTERVAL, Math.max(UNRAID_MIN_INTERVAL, Math.round(urInterval)))+ if (clamped !== urInterval) setUrInterval(clamped)+ await unraidApi.saveConfig({+ sync_enabled: urSyncEnabled,+ sync_interval: clamped,+ include_offline: urIncludeOffline,+ })+ }if (zbConfig) {// MQTT connection config is env-only; only the activation is persisted.await zigbeeApi.saveConfig({@@ -615,6 +657,72 @@ export function SettingsModal({ open, onClose }: SettingsModalProps) {)}</div>)}+ {/* Unraid auto-sync */}+ {!STANDALONE && urConfig && (+ <div className="pt-3 border-t border-border space-y-2">+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">Unraid auto-sync</span>+ {!(urConfig.api_key_configured && urConfig.host) ? (+ <p className="text-[10px] text-[#e3b341] leading-tight">+ No Unraid server configured. Set <span className="font-mono">UNRAID_HOST</span> and{' '}+ <span className="font-mono">UNRAID_API_KEY</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 Unraid containers and VMs</span>+ <input+ type="checkbox"+ checked={urSyncEnabled}+ onChange={(e) => setUrSyncEnabled(e.target.checked)}+ className="cursor-pointer accent-[#e22828]"+ aria-label="Toggle Unraid auto-sync"+ />+ </label>+ <div className={urSyncEnabled ? '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={urInterval}+ onChange={(e) => { const v = Number(e.target.value); if (!isNaN(v)) setUrInterval(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-[#e22828]"+ aria-label="Unraid sync interval"+ />+ <span className="text-xs text-muted-foreground">seconds</span>+ </div>+ <p className="text-[10px] text-muted-foreground leading-tight">+ Re-imports the server, its containers and VMs into the pending inventory. Min 300s (5 min).+ </p>+ </div>+ <label className="flex items-center justify-between gap-2 cursor-pointer">+ <span className="text-xs text-foreground">Include stopped containers and VMs</span>+ <input+ type="checkbox"+ checked={urIncludeOffline}+ onChange={(e) => setUrIncludeOffline(e.target.checked)}+ className="cursor-pointer accent-[#e22828]"+ aria-label="Include stopped Unraid containers and VMs"+ />+ </label>+ <div className="flex items-center gap-2 pt-1">+ <Button+ variant="outline"+ onClick={handleUrSyncNow}+ disabled={urSyncing}+ className="h-7 text-xs border-[#e22828] text-[#e22828] hover:bg-[#e22828]/10"+ >+ {urSyncing ? '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>+ </>+ )}+ </div>+ )}{/* UniFi auto-sync */}{!STANDALONE && unConfig && (<div className="pt-3 border-t border-border space-y-2">diff --git a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsxindex b5df795..02b6590 100644--- a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx@@ -931,6 +931,52 @@ async function openProxmoxPrompt() {await waitFor(() => expect(screen.getByRole('button', { name: /add 3 to canvas/i })).toBeInTheDocument())}+describe('DeviceInventoryModal - Unraid server approval', () => {+ const SERVER = {+ ...PVE_HOST,+ id: 'dev-unraid',+ hostname: 'tower',+ friendly_name: 'tower',+ suggested_type: 'docker_host',+ discovery_source: 'unraid',+ discovery_sources: ['unraid'],+ ieee_address: 'unraid-host-abc',+ }+ const CONTAINERS = [+ { ...SERVER, id: 'dev-c1', friendly_name: 'plex', suggested_type: 'docker_container', ieee_address: 'unraid-abc-ct-plex' },+ ]++ it('asks about the containers and places them linked, not nested', async () => {+ mockPending.mockResolvedValue({ data: [SERVER] })+ mockProxmoxChildren.mockResolvedValue({ data: CONTAINERS })+ mockBulkApprove.mockResolvedValue({+ data: {+ approved: 2, node_ids: ['n-host', 'n-c1'], device_ids: ['dev-unraid', 'dev-c1'],+ edges: [], edges_created: 0, skipped: 0, skipped_devices: [],+ },+ })+ render(<DeviceInventoryModal {...baseProps} />)+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-unraid')).toBeInTheDocument())+ fireEvent.click(screen.getByTestId('pending-card-dev-unraid'))+ fireEvent.click(screen.getByTestId('do-approve'))+ fireEvent.click(await screen.findByRole('button', { name: /add 2 to canvas/i }))+ await waitFor(() => expect(mockBulkApprove).toHaveBeenCalledWith(['dev-unraid', 'dev-c1'], null))+ const added = mockAddNode.mock.calls.map((c) => c[0])+ expect(added.find((n) => n.id === 'n-host').data.container_mode).toBeUndefined()+ added.forEach((n) => expect(n.data.parent_id).toBeUndefined())+ })++ it('approves a docker host from another source without asking', async () => {+ mockPending.mockResolvedValue({ data: [{ ...SERVER, discovery_source: 'arp', discovery_sources: ['arp'] }] })+ render(<DeviceInventoryModal {...baseProps} />)+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-unraid')).toBeInTheDocument())+ fireEvent.click(screen.getByTestId('pending-card-dev-unraid'))+ fireEvent.click(screen.getByTestId('do-approve'))+ await waitFor(() => expect(mockApprove).toHaveBeenCalled())+ expect(mockProxmoxChildren).not.toHaveBeenCalled()+ })+})+describe('DeviceInventoryModal — Proxmox host approval', () => {beforeEach(() => {mockBulkApprove.mockResolvedValue({diff --git a/frontend/src/components/modals/__tests__/ProxmoxApproveModal.test.tsx b/frontend/src/components/modals/__tests__/ProxmoxApproveModal.test.tsxindex 8faf831..645bcb4 100644--- a/frontend/src/components/modals/__tests__/ProxmoxApproveModal.test.tsx+++ b/frontend/src/components/modals/__tests__/ProxmoxApproveModal.test.tsx@@ -66,3 +66,23 @@ describe('ProxmoxApproveModal', () => {expect(props.onConfirm).not.toHaveBeenCalled()})})++describe('ProxmoxApproveModal - Unraid server', () => {+ const server = { id: 'h2', label: 'tower', type: 'docker_host', status: 'pending', services: [] } as unknown as InventoryEntry+ const containers = [+ { id: 'c1', label: 'plex', type: 'docker_container', status: 'pending', services: [] },+ { id: 'v1', label: 'ubuntu', type: 'vm', status: 'pending', services: [] },+ ] as unknown as InventoryEntry[]++ beforeEach(() => {+ props.onConfirm.mockReset()+ })++ it('asks about containers and VMs and offers no nesting', () => {+ render(<ProxmoxApproveModal {...props} host={server} guests={containers} source="unraid" />)+ expect(screen.getByRole('checkbox', { name: /also add its 2 guestsdocker containers and vms/i })).toBeDefined()+ expect(screen.queryByRole('radio')).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: /add 3 to canvas/i }))+ expect(props.onConfirm).toHaveBeenCalledWith({ childIds: ['c1', 'v1'], mode: 'linked' })+ })+})diff --git a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx b/frontend/src/components/modals/__tests__/SettingsModal.test.tsxindex 95cac55..32e89b9 100644--- a/frontend/src/components/modals/__tests__/SettingsModal.test.tsx+++ b/frontend/src/components/modals/__tests__/SettingsModal.test.tsx@@ -28,9 +28,14 @@ vi.mock('@/api/client', () => ({saveConfig: vi.fn(),syncNow: vi.fn(),},+ unraidApi: {+ getConfig: vi.fn(),+ saveConfig: vi.fn(),+ syncNow: vi.fn(),+ },}))-import { settingsApi, proxmoxApi, zigbeeApi, zwaveApi, unifiApi } from '@/api/client'+import { settingsApi, proxmoxApi, zigbeeApi, zwaveApi, unifiApi, unraidApi } from '@/api/client'import { toast } from 'sonner'import { useCanvasStore } from '@/stores/canvasStore'@@ -40,6 +45,7 @@ describe('SettingsModal', () => {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: { interval_seconds: 60, service_check_enabled: false, service_check_interval: 300 } } as never)vi.mocked(proxmoxApi.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(unraidApi.getConfig).mockRejectedValue(new Error('not configured'))vi.mocked(proxmoxApi.saveConfig).mockResolvedValue({ data: {} } as never)// Zigbee/Z-Wave default to "not configured" so the mesh sections stay hidden// unless a test opts in — keeps the single Proxmox "Re-sync now" unambiguous.@@ -276,6 +282,7 @@ describe('SettingsModal — UniFi', () => {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(unraidApi.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)@@ -410,3 +417,65 @@ describe('SettingsModal — UniFi', () => {)})})++describe('SettingsModal - Unraid', () => {+ 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.getConfig).mockRejectedValue(new Error('not configured'))+ vi.mocked(unraidApi.saveConfig).mockResolvedValue({ data: {} } as never)+ vi.mocked(unraidApi.syncNow).mockResolvedValue({ data: { status: 'running' } } as never)+ vi.mocked(toast.success).mockReset()+ })++ const config = (over = {}) => ({+ data: {+ host: 'tower', port: 443, verify_tls: true, sync_enabled: true,+ sync_interval: 3600, include_offline: true, api_key_configured: true, ...over,+ },+ })++ it('persists the stopped-devices choice with the sync fields', async () => {+ vi.mocked(unraidApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ const offline = await screen.findByLabelText('Include stopped Unraid containers and VMs')+ await waitFor(() => expect(offline).toBeChecked())+ fireEvent.click(offline)+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => {+ expect(unraidApi.saveConfig).toHaveBeenCalledWith({ sync_enabled: true, sync_interval: 3600, include_offline: false })+ })+ })++ it('clamps a typed sync interval into the range the backend accepts', async () => {+ vi.mocked(unraidApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ const input = await screen.findByLabelText('Unraid sync interval')+ await waitFor(() => expect(input).toHaveValue(3600))+ fireEvent.change(input, { target: { value: '100' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(unraidApi.saveConfig).toHaveBeenCalled())+ expect(vi.mocked(unraidApi.saveConfig).mock.calls[0][0].sync_interval).toBe(300)+ })++ it('shows the env vars to set when no server is configured', async () => {+ vi.mocked(unraidApi.getConfig).mockResolvedValue(config({ api_key_configured: false }) as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ await screen.findByText('UNRAID_API_KEY')+ expect(screen.queryByLabelText('Toggle Unraid auto-sync')).toBeNull()+ })++ it('triggers an immediate sync from Re-sync now', async () => {+ vi.mocked(unraidApi.getConfig).mockResolvedValue(config() as never)+ render(<SettingsModal open onClose={vi.fn()} />)+ fireEvent.click(await screen.findByRole('button', { name: 'Re-sync now' }))+ await waitFor(() => {+ expect(unraidApi.syncNow).toHaveBeenCalledOnce()+ expect(toast.success).toHaveBeenCalledWith('Unraid sync started')+ })+ })+})diff --git a/frontend/src/components/unraid/UnraidImportModal.tsx b/frontend/src/components/unraid/UnraidImportModal.tsxnew file mode 100644index 0000000..dc670e7--- /dev/null+++ b/frontend/src/components/unraid/UnraidImportModal.tsx@@ -0,0 +1,422 @@+import { useState } from 'react'+import { Server, Container, Box, HardDrive, CheckCircle2, XCircle, Loader2, Plus } 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 { unraidApi, type UnraidConnection } from '@/api/client'+import { toast } from 'sonner'+import type { UnraidNode, UnraidEdge, UnraidNodeType } from './types'++interface UnraidImportModalProps {+ open: boolean+ onClose: () => void+ onAddToCanvas: (nodes: UnraidNode[], edges: UnraidEdge[]) => void+ onInventoryImported?: () => void+}++type ImportMode = 'pending' | 'canvas'++const ACCENT = '#e22828'++interface ConnectionForm {+ host: string+ /** Blank = the scheme's default port. */+ port: string+ api_key: string+ use_https: boolean+ verify_tls: boolean+}++const DEFAULT_FORM: ConnectionForm = {+ host: '',+ port: '',+ api_key: '',+ // Off, like Unraid's own "Use SSL/TLS" default.+ use_https: false,+ // Unraid's own certificate is self-signed.+ verify_tls: false,+}++const DEVICE_TYPE_ICON: Record<UnraidNodeType, typeof Server> = {+ docker_host: Server,+ docker_container: Container,+ vm: Box,+}++const DEVICE_TYPE_LABEL: Record<UnraidNodeType, string> = {+ docker_host: 'Server',+ docker_container: 'Containers',+ vm: 'Virtual Machines',+}++const DEVICE_TYPE_COLOR: Record<UnraidNodeType, string> = {+ docker_host: ACCENT,+ docker_container: '#00d4ff',+ vm: '#a855f7',+}++function plural(n: number, noun: string): string {+ return `${n} ${noun}${n !== 1 ? 's' : ''}`+}++export function UnraidImportModal({ open, onClose, onAddToCanvas, onInventoryImported }: UnraidImportModalProps) {+ const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)+ const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')+ const [connectionMsg, setConnectionMsg] = useState('')+ const [loading, setLoading] = useState(false)+ const [devices, setDevices] = useState<UnraidNode[]>([])+ const [edges, setEdges] = useState<UnraidEdge[]>([])+ const [checked, setChecked] = useState<Set<string>>(new Set())+ const [importMode, setImportMode] = useState<ImportMode>('pending')+ // Same meaning in both modes: stopped devices are imported and listed, or neither.+ const [includeOffline, setIncludeOffline] = useState(true)++ const updateField = (field: keyof ConnectionForm, value: string) =>+ setForm((f) => ({ ...f, [field]: value }))++ const buildPayload = (): UnraidConnection => ({+ host: form.host.trim(),+ port: Number(form.port) || undefined,+ api_key: form.api_key.trim() || undefined,+ use_https: form.use_https,+ verify_tls: form.use_https && form.verify_tls,+ include_offline: includeOffline,+ })++ const extractError = (err: unknown): string | undefined => {+ if (err && typeof err === 'object' && 'response' in err) {+ return (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ }+ return undefined+ }++ const handleTestConnection = async () => {+ if (!form.host.trim()) { toast.error('Enter an Unraid host'); return }+ setConnectionStatus('testing')+ try {+ const res = await unraidApi.testConnection(buildPayload())+ setConnectionStatus(res.data.connected ? 'ok' : 'fail')+ setConnectionMsg(res.data.message)+ } catch (err) {+ setConnectionStatus('fail')+ setConnectionMsg(extractError(err) ?? 'Request failed - check host address')+ }+ }++ const handleFetchDevices = async () => {+ if (!form.host.trim()) { toast.error('Enter an Unraid host'); return }+ setLoading(true)+ try {+ if (importMode === 'pending') {+ await unraidApi.importToPending(buildPayload())+ onInventoryImported?.()+ handleClose()+ } else {+ const res = await unraidApi.importNetwork(buildPayload())+ setDevices(res.data.nodes)+ setEdges(res.data.edges)+ setChecked(new Set(res.data.nodes.map((n) => n.id)))+ const count = (type: UnraidNodeType, noun: string) =>+ plural(res.data.nodes.filter((d) => d.type === type).length, noun)+ if (res.data.nodes.every((n) => n.type === 'docker_host')) {+ toast.info('No containers or VMs found')+ } else {+ toast.success(`Found ${count('docker_container', 'container')} and ${count('vm', 'VM')}`)+ }+ if (res.data.notice) toast.warning(res.data.notice)+ }+ } catch (err: unknown) {+ toast.error(extractError(err) ?? 'Failed to fetch Unraid devices')+ } finally {+ setLoading(false)+ }+ }++ const toggleCheck = (id: string) =>+ setChecked((prev) => {+ const next = new Set(prev)+ if (next.has(id)) next.delete(id); else next.add(id)+ return next+ })++ const toggleAll = () => {+ setChecked(checked.size === devices.length ? new Set() : new Set(devices.map((d) => d.id)))+ }++ const handleAddToCanvas = () => {+ const selectedDevices = devices.filter((d) => checked.has(d.id))+ const selectedIds = new Set(selectedDevices.map((d) => d.id))+ const selectedEdges = edges.filter((e) => selectedIds.has(e.source) && selectedIds.has(e.target))+ onAddToCanvas(selectedDevices, selectedEdges)+ toast.success(`Added ${selectedDevices.length} device${selectedDevices.length !== 1 ? 's' : ''} to canvas`)+ handleClose()+ }++ const handleClose = () => {+ setDevices([])+ setEdges([])+ setChecked(new Set())+ setConnectionStatus('idle')+ setConnectionMsg('')+ setImportMode('pending')+ setIncludeOffline(true)+ onClose()+ }++ // Key order is display order. VMs go before the containers: a server runs a+ // handful of VMs and dozens of containers, and listed last they sat below+ // the fold where nobody scrolled to them.+ const groupedDevices: Record<UnraidNodeType, UnraidNode[]> = {+ docker_host: devices.filter((d) => d.type === 'docker_host'),+ vm: devices.filter((d) => d.type === 'vm'),+ docker_container: devices.filter((d) => d.type === 'docker_container'),+ }++ 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">+ <HardDrive size={16} style={{ color: ACCENT }} />+ Unraid 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="space-y-1">+ <Label className="text-xs text-muted-foreground">Unraid Host</Label>+ <Input+ value={form.host}+ onChange={(e) => updateField('host', e.target.value)}+ placeholder="192.168.1.x or tower.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={form.use_https ? '443' : '80'}+ type="number"+ className="font-mono text-sm bg-[#0d1117] border-border"+ />+ </div>+ <div className="col-span-2 space-y-1">+ <Label className="text-xs text-muted-foreground">API Key</Label>+ <Input+ value={form.api_key}+ onChange={(e) => updateField('api_key', e.target.value)}+ 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.use_https}+ onChange={(e) => setForm((f) => ({ ...f, use_https: e.target.checked }))}+ className="w-3 h-3 cursor-pointer"+ style={{ accentColor: ACCENT }}+ />+ Use HTTPS+ </label>+ {form.use_https && (+ <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 cursor-pointer"+ style={{ accentColor: ACCENT }}+ />+ Verify TLS certificate+ </label>+ )}+ </div>+ {!form.use_https && (+ <p className="col-span-2 text-[11px] text-[#e3b341]">+ Over HTTP the API key is sent unencrypted. Tick Use HTTPS if the server has SSL turned on.+ </p>+ )}+ </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">Send devices to</span>+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-xs">+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">+ <input+ type="radio"+ name="unraid-import-mode"+ checked={importMode === 'pending'}+ onChange={() => setImportMode('pending')}+ className="cursor-pointer"+ style={{ accentColor: ACCENT }}+ />+ Device inventory only+ </label>+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">+ <input+ type="radio"+ name="unraid-import-mode"+ checked={importMode === 'canvas'}+ onChange={() => setImportMode('canvas')}+ className="cursor-pointer"+ style={{ accentColor: ACCENT }}+ />+ Inventory + canvas+ </label>+ </div>+ </div>++ <label className="flex items-center gap-2 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5 text-xs cursor-pointer text-foreground">+ <input+ type="checkbox"+ checked={includeOffline}+ onChange={(e) => setIncludeOffline(e.target.checked)}+ className="w-3 h-3 cursor-pointer"+ style={{ accentColor: ACCENT }}+ />+ Include stopped containers and VMs+ </label>++ <div className="flex flex-wrap gap-2 pt-1">+ <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' || loading}+ >+ {connectionStatus === 'testing'+ ? <Loader2 size={13} className="animate-spin" />+ : <CheckCircle2 size={13} />}+ Test Connection+ </Button>+ <Button+ size="sm"+ style={{ background: ACCENT, color: '#0d1117' }}+ className="gap-1.5"+ onClick={handleFetchDevices}+ disabled={loading || connectionStatus === 'testing'}+ >+ {loading ? <Loader2 size={13} className="animate-spin" /> : <HardDrive size={13} />}+ {importMode === 'pending' ? 'Import to Inventory' : 'Fetch Devices'}+ </Button>+ </div>+ <p className="text-[11px] text-muted-foreground italic">+ Leave the API key blank to use the key configured on the server (.env).+ Create one under Settings > Management Access > API Keys with read access to Docker, VMs and Info.+ </p>+ </div>++ {devices.length > 0 && (+ <div className="space-y-2">+ <div className="flex items-center gap-1.5">+ <input+ type="checkbox"+ checked={checked.size === devices.length}+ ref={(el) => { if (el) el.indeterminate = checked.size > 0 && checked.size < devices.length }}+ onChange={toggleAll}+ className="w-3 h-3 cursor-pointer"+ style={{ accentColor: ACCENT }}+ title="Select all"+ />+ <span className="text-xs font-medium text-muted-foreground uppercase tracking-wider">+ Devices ({checked.size}/{devices.length} selected)+ </span>+ </div>++ {(Object.entries(groupedDevices) as [UnraidNodeType, UnraidNode[]][])+ .filter(([, group]) => group.length > 0)+ .map(([type, group]) => {+ const Icon = DEVICE_TYPE_ICON[type]+ const color = DEVICE_TYPE_COLOR[type]+ return (+ <div key={type}>+ <div className="flex items-center gap-1.5 mb-1">+ <Icon size={11} style={{ color }} />+ <span className="text-[10px] font-medium uppercase tracking-wider" style={{ color }}>+ {DEVICE_TYPE_LABEL[type]} ({group.length})+ </span>+ </div>+ {type === 'vm' && (+ <p className="text-[11px] text-muted-foreground mb-1">+ Unraid does not report a VM's IP or MAC, so these come in without one. If a+ network scan already found a VM, merge the two in the Device Inventory.+ </p>+ )}+ {group.map((device) => (+ <div+ key={device.id}+ className={`flex items-start gap-2 p-2 mb-1 rounded-md text-xs cursor-pointer transition-colors border ${+ checked.has(device.id)+ ? 'bg-[#21262d] border-[#e22828]/40'+ : 'bg-[#21262d] border-transparent hover:bg-[#30363d]'+ }`}+ onClick={() => toggleCheck(device.id)}+ >+ <input+ type="checkbox"+ checked={checked.has(device.id)}+ onChange={() => toggleCheck(device.id)}+ onClick={(e) => e.stopPropagation()}+ className="w-3 h-3 mt-0.5 cursor-pointer shrink-0"+ style={{ accentColor: ACCENT }}+ />+ <div className="flex-1 min-w-0">+ <div className="text-foreground font-medium truncate">{device.label}</div>+ {device.ip && (+ <div className="font-mono text-[10px] text-muted-foreground truncate">{device.ip}</div>+ )}+ <div className="text-[10px] text-muted-foreground truncate">+ {[device.model, device.status].filter(Boolean).join(' - ')}+ </div>+ </div>+ </div>+ ))}+ </div>+ )+ })}+ </div>+ )}+ </div>++ <DialogFooter className="gap-2 shrink-0 pt-2 border-t border-border">+ <Button variant="ghost" onClick={handleClose}>Cancel</Button>+ {devices.length > 0 && (+ <Button+ onClick={handleAddToCanvas}+ disabled={checked.size === 0}+ style={{ background: ACCENT, color: '#0d1117' }}+ className="gap-1.5"+ >+ <Plus size={13} />+ Add {checked.size} to Canvas+ </Button>+ )}+ </DialogFooter>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/unraid/__tests__/UnraidImportModal.test.tsx b/frontend/src/components/unraid/__tests__/UnraidImportModal.test.tsxnew file mode 100644index 0000000..7bcc0eb--- /dev/null+++ b/frontend/src/components/unraid/__tests__/UnraidImportModal.test.tsx@@ -0,0 +1,183 @@+import { describe, it, expect, vi, beforeEach } from 'vitest'+import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { UnraidImportModal } from '../UnraidImportModal'++vi.mock('@/api/client', () => ({+ unraidApi: {+ testConnection: vi.fn(),+ importNetwork: vi.fn(),+ importToPending: vi.fn(),+ },+}))+vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())++import { unraidApi } from '@/api/client'+import { toast } from 'sonner'++const defaultProps = {+ open: true,+ onClose: vi.fn(),+ onAddToCanvas: vi.fn(),+ onInventoryImported: vi.fn(),+}++const HOST_INPUT = '192.168.1.x or tower.local'++const sampleNodes = [+ {+ id: 'unraid-host-abc', label: 'Tower', type: 'docker_host' as const,+ ieee_address: 'unraid-host-abc', hostname: 'Tower', ip: '10.0.0.2', status: 'online',+ vendor: 'Unraid', model: 'MSI', parent_ieee: null,+ },+ {+ id: 'unraid-abc-ct-plex', label: 'plex', type: 'docker_container' as const,+ ieee_address: 'unraid-abc-ct-plex', hostname: 'plex', ip: null, status: 'online',+ vendor: 'Docker', model: 'linuxserver/plex', parent_ieee: 'unraid-host-abc',+ },+]+const sampleEdges = [{ source: 'unraid-host-abc', target: 'unraid-abc-ct-plex' }]++function fillHost() {+ fireEvent.change(screen.getByPlaceholderText(HOST_INPUT), { target: { value: 'tower' } })+}++describe('UnraidImportModal', () => {+ beforeEach(() => {+ vi.mocked(unraidApi.testConnection).mockReset()+ vi.mocked(unraidApi.importNetwork).mockReset()+ vi.mocked(unraidApi.importToPending).mockReset()+ vi.mocked(unraidApi.importToPending).mockResolvedValue({ data: { id: 'run-1', status: 'running' } } as never)+ vi.mocked(unraidApi.importNetwork).mockResolvedValue({+ data: { nodes: sampleNodes, edges: sampleEdges, device_count: 2 },+ } as never)+ vi.mocked(toast.success).mockReset()+ vi.mocked(toast.error).mockReset()+ defaultProps.onClose.mockReset()+ defaultProps.onAddToCanvas.mockReset()+ defaultProps.onInventoryImported.mockReset()+ })++ it('renders a masked API key input', () => {+ render(<UnraidImportModal {...defaultProps} />)+ expect(screen.getByText('Unraid Import')).toBeDefined()+ expect(document.querySelector('input[type="password"]')).not.toBeNull()+ })++ it('errors when testing without a host', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fireEvent.click(screen.getByRole('button', { name: /test connection/i }))+ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Enter an Unraid host'))+ expect(unraidApi.testConnection).not.toHaveBeenCalled()+ })++ it('includes stopped containers and VMs by default', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))+ await waitFor(() => expect(unraidApi.importToPending).toHaveBeenCalled())+ expect(vi.mocked(unraidApi.importToPending).mock.calls[0][0].include_offline).toBe(true)+ expect(defaultProps.onInventoryImported).toHaveBeenCalled()+ })++ it('leaves stopped devices out when the checkbox is cleared, in either mode', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Inventory + canvas', { selector: 'input[name="unraid-import-mode"]' }))+ // One checkbox, the same in both modes - no separate canvas-only choice.+ expect(screen.queryByRole('radio', { name: /skip/i })).toBeNull()+ fireEvent.click(screen.getByLabelText('Include stopped containers and VMs'))+ fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))+ await waitFor(() => expect(unraidApi.importNetwork).toHaveBeenCalled())+ expect(vi.mocked(unraidApi.importNetwork).mock.calls[0][0].include_offline).toBe(false)+ })++ it('adds the selected server and containers to the canvas', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Inventory + canvas', { selector: 'input[name="unraid-import-mode"]' }))+ fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))+ fireEvent.click(await screen.findByRole('button', { name: /add 2 to canvas/i }))+ expect(defaultProps.onAddToCanvas).toHaveBeenCalledWith(sampleNodes, sampleEdges)+ })++ it('sends the API key from the form', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ const key = document.querySelector('input[type="password"]') as HTMLInputElement+ fireEvent.change(key, { target: { value: 'secret' } })+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))+ await waitFor(() => expect(unraidApi.importToPending).toHaveBeenCalled())+ expect(vi.mocked(unraidApi.importToPending).mock.calls[0][0].api_key).toBe('secret')+ // Unraid ships a self-signed certificate, so verification starts off.+ expect(vi.mocked(unraidApi.importToPending).mock.calls[0][0].verify_tls).toBe(false)+ })++ it('lists VMs in their own group and warns when VMs were skipped', async () => {+ const vm = {+ id: 'unraid-abc-vm-u1', label: 'UbuntuServer', type: 'vm' as const,+ ieee_address: 'unraid-abc-vm-u1', status: 'online', model: 'KVM', parent_ieee: 'unraid-host-abc',+ }+ vi.mocked(unraidApi.importNetwork).mockResolvedValue({+ data: { nodes: [...sampleNodes, vm], edges: sampleEdges, device_count: 3, notice: 'VMs were not imported: x' },+ } as never)+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Inventory + canvas', { selector: 'input[name="unraid-import-mode"]' }))+ fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))+ const vmHeading = await screen.findByText('Virtual Machines (1)')+ // VMs come before the containers, not below a long container list.+ const containerHeading = screen.getByText('Containers (1)')+ expect(vmHeading.compareDocumentPosition(containerHeading) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()+ expect(toast.success).toHaveBeenCalledWith('Found 1 container and 1 VM')+ expect(toast.warning).toHaveBeenCalledWith('VMs were not imported: x')+ })++ it('explains that VMs come without an IP', async () => {+ const vm = {+ id: 'unraid-abc-vm-u1', label: 'UbuntuServer', type: 'vm' as const,+ ieee_address: 'unraid-abc-vm-u1', status: 'online', model: 'KVM', parent_ieee: 'unraid-host-abc',+ }+ vi.mocked(unraidApi.importNetwork).mockResolvedValue({+ data: { nodes: [...sampleNodes, vm], edges: sampleEdges, device_count: 3 },+ } as never)+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Inventory + canvas', { selector: 'input[name="unraid-import-mode"]' }))+ fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))+ expect(await screen.findByText(/does not report a VM's IP or MAC/)).toBeDefined()+ })++ it('shows no VM note when there are no VMs', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Inventory + canvas', { selector: 'input[name="unraid-import-mode"]' }))+ fireEvent.click(screen.getByRole('button', { name: /fetch devices/i }))+ await screen.findByRole('button', { name: /add 2 to canvas/i })+ expect(screen.queryByText(/does not report a VM's IP/)).toBeNull()+ })++ it('talks plain HTTP on the default port unless Use HTTPS is ticked', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ expect(screen.getByText(/API key is sent unencrypted/)).toBeDefined()+ expect(screen.queryByLabelText('Verify TLS certificate')).toBeNull()+ expect(screen.getByPlaceholderText('80')).toBeDefined()+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))+ await waitFor(() => expect(unraidApi.importToPending).toHaveBeenCalled())+ const sent = vi.mocked(unraidApi.importToPending).mock.calls[0][0]+ expect([sent.use_https, sent.port, sent.verify_tls]).toEqual([false, undefined, false])+ })++ it('offers TLS verification once HTTPS is ticked', async () => {+ render(<UnraidImportModal {...defaultProps} />)+ fillHost()+ fireEvent.click(screen.getByLabelText('Use HTTPS'))+ expect(screen.queryByText(/API key is sent unencrypted/)).toBeNull()+ expect(screen.getByPlaceholderText('443')).toBeDefined()+ fireEvent.click(screen.getByLabelText('Verify TLS certificate'))+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))+ await waitFor(() => expect(unraidApi.importToPending).toHaveBeenCalled())+ const sent = vi.mocked(unraidApi.importToPending).mock.calls[0][0]+ expect([sent.use_https, sent.verify_tls]).toEqual([true, true])+ })+})diff --git a/frontend/src/components/unraid/types.ts b/frontend/src/components/unraid/types.tsnew file mode 100644index 0000000..d29795d--- /dev/null+++ b/frontend/src/components/unraid/types.ts@@ -0,0 +1,38 @@+/** Shared Unraid import type definitions for the frontend. */++import type { NodeProperty, ServiceInfo } from '@/types'++export type UnraidNodeType = 'docker_host' | 'docker_container' | 'vm'++export interface UnraidNode {+ id: string+ label: string+ type: UnraidNodeType+ ieee_address: string+ hostname?: string | null+ ip?: string | null+ status: string+ vendor?: string | null+ /** Image for a container, board maker + model for the host, KVM for a VM. */+ model?: string | null+ parent_ieee?: string | null+ /** Device Inventory row this node draws - stamped by the import so the+ * canvas save links to it instead of minting a second row. */+ device_id?: string | null+ /** The inventory row's lists - a container's web UI is one of the services. */+ services?: ServiceInfo[]+ properties?: NodeProperty[]+}++export interface UnraidEdge {+ source: string+ target: string+}++export interface UnraidImportResponse {+ nodes: UnraidNode[]+ edges: UnraidEdge[]+ device_count: number+ /** Why VMs were left out (e.g. the API key has no VM access). */+ notice?: string | null+}diff --git a/frontend/src/utils/__tests__/deviceSources.test.ts b/frontend/src/utils/__tests__/deviceSources.test.tsindex 25c0e36..825707a 100644--- a/frontend/src/utils/__tests__/deviceSources.test.ts+++ b/frontend/src/utils/__tests__/deviceSources.test.ts@@ -24,6 +24,10 @@ describe('sourceBuckets', () => {expect([...buckets].sort()).toEqual(['ip', 'proxmox'])})+ it('files an Unraid container under its own bucket, not the IP scan', () => {+ expect(orderedSources(device({ discovery_sources: ['unraid', 'arp'] }))).toEqual(['ip', 'unraid'])+ })+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.diff --git a/frontend/src/utils/deviceSources.ts b/frontend/src/utils/deviceSources.tsindex 2aa67d4..de11502 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' | 'unifi' | 'rack' | 'canvas'+export type SourceBucket = 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'unraid' | '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' },+ unraid: { color: '#e22828', label: 'UNRAID' },unifi: { color: '#0559c9', label: 'UNIFI' },ip: { color: '#a855f7', label: 'IP' },rack: { color: '#39d353', label: 'RACK' },@@ -21,7 +22,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', 'unifi', 'zigbee', 'zwave', 'rack', 'canvas']+const SOURCE_ORDER: SourceBucket[] = ['ip', 'proxmox', 'unraid', '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}. */@@ -34,6 +35,7 @@ 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')+ else if (s === 'unraid') buckets.add('unraid')// 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')