Skip to content

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

feat(rack): link a mount to any Device Inventory entry

Pouzor9954fccf759a
diff --git a/backend/app/api/routes/proxmox.py b/backend/app/api/routes/proxmox.py
index 6c2e562..9e2283a 100644
--- a/backend/app/api/routes/proxmox.py
+++ b/backend/app/api/routes/proxmox.py
@@ -21,7 +21,7 @@ from app.api.deps import get_current_user
from app.core.config import settings
from app.core.scheduler import reschedule_proxmox_sync, set_proxmox_sync_enabled
from app.db.database import AsyncSessionLocal, get_db
-from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
+from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
from app.schemas.proxmox import (
ProxmoxConfig,
ProxmoxConnectionRequest,
@@ -245,7 +245,7 @@ async def _persist_pending_import(
nodes_raw: list[dict[str, Any]],
edges_raw: list[dict[str, Any]],
) -> ProxmoxImportPendingResponse:
- """Upsert Proxmox nodes/edges into pending_devices + pending_device_links.
+ """Upsert Proxmox nodes/edges into device_inventory + device_inventory_links.
Two-tier identity (order matters):
1. Match an existing canvas Node or pending row by **IP** (merge into a
@@ -328,14 +328,14 @@ async def _persist_pending_import(
async def _find_pending(
db: AsyncSession, ieee: str, ip: str | None, mac: str | None
-) -> PendingDevice | None:
- filters = [PendingDevice.ieee_address == ieee]
+) -> InventoryDevice | None:
+ filters = [InventoryDevice.ieee_address == ieee]
if ip:
- filters.append(PendingDevice.ip == ip)
+ filters.append(InventoryDevice.ip == ip)
if mac:
- filters.append(PendingDevice.mac == mac)
+ filters.append(InventoryDevice.mac == mac)
return (
- await db.execute(select(PendingDevice).where(or_(*filters)))
+ await db.execute(select(InventoryDevice).where(or_(*filters)))
).scalars().first()
@@ -346,8 +346,8 @@ def _new_pending(
n: dict[str, Any],
props: list[dict[str, Any]],
status: str,
-) -> PendingDevice:
- return PendingDevice(
+) -> InventoryDevice:
+ return InventoryDevice(
ieee_address=ieee,
ip=ip,
mac=mac,
@@ -363,7 +363,7 @@ def _new_pending(
)
-def _sources_after_merge(row: PendingDevice) -> list[str]:
+def _sources_after_merge(row: InventoryDevice) -> list[str]:
"""Discovery sources for an inventory row after a Proxmox import merges in.
Must run BEFORE the ``pve-`` ieee is adopted onto the row, so it can tell
@@ -381,7 +381,7 @@ def _sources_after_merge(row: PendingDevice) -> list[str]:
def _refresh_pending(
- pending: PendingDevice,
+ pending: InventoryDevice,
ieee: str,
ip: str | None,
mac: str | None,
@@ -441,8 +441,8 @@ async def _replace_links(
(``proxmox_cluster`` → 'cluster' edges).
"""
await db.execute(
- sa_delete(PendingDeviceLink).where(
- PendingDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE])
+ sa_delete(InventoryDeviceLink).where(
+ InventoryDeviceLink.discovery_source.in_([_PROXMOX_GUEST_SOURCE, _PROXMOX_CLUSTER_SOURCE])
)
)
recorded = 0
@@ -453,7 +453,7 @@ async def _replace_links(
if not src or not tgt or (src, tgt) in seen:
return
seen.add((src, tgt))
- db.add(PendingDeviceLink(source_ieee=src, target_ieee=tgt, discovery_source=source))
+ db.add(InventoryDeviceLink(source_ieee=src, target_ieee=tgt, discovery_source=source))
recorded += 1
for e in edges_raw:
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.py
index 2d0ebbf..3af0291 100644
--- a/backend/app/api/routes/racks.py
+++ b/backend/app/api/routes/racks.py
@@ -7,7 +7,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.db.database import get_db
-from app.db.models import CanvasState, Design, Node, PendingDevice, Rack, RackCable, RackDevice
+from app.db.models import CanvasState, Design, InventoryDevice, Node, Rack, RackCable, RackDevice
from app.schemas.racks import (
RackCableResponse,
RackDeviceResponse,
@@ -48,7 +48,7 @@ _UNRACKABLE_TYPES = {
_COMMON_PORTS = {22, 80, 443}
-def _service_name(device: PendingDevice) -> str | None:
+def _service_name(device: InventoryDevice) -> str | None:
"""Name a device after the app it runs, the way the Device Inventory does.
Ports everyone exposes (ssh, http, https) say nothing, and the generic web
@@ -72,10 +72,10 @@ def _service_name(device: PendingDevice) -> str | None:
return str(name) if name else None
-def _device_label(device: PendingDevice) -> str:
+def _device_label(device: InventoryDevice) -> str:
"""Inventory naming, mirrored: friendly name, host, app, IP, IEEE, id.
- Must stay in step with `deviceLabel` in `PendingDevicesModal.tsx` — a device
+ Must stay in step with `deviceLabel` in `InventoryDevicesModal.tsx` — a device
the user picked out of the inventory by one name should not turn up in the
rack picker under another.
"""
@@ -265,26 +265,30 @@ async def rack_inventory(
) -> RackInventoryResponse:
"""Device Inventory entries that can be racked, flagged with what is already mounted.
- Reads `pending_devices` — the inventory survives approval and node deletion,
+ Reads `device_inventory` — the inventory survives approval and node deletion,
so unracking or deleting a canvas node never removes the entry here.
"""
await _require_design(db, design_id)
devices = (
- await db.execute(select(PendingDevice).where(PendingDevice.status != "hidden"))
+ await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
).scalars().all()
- mounted = {
- row
- for row in (
- await db.execute(
- select(RackDevice.device_id).where(RackDevice.design_id == design_id)
+ mounts = (
+ await db.execute(
+ select(RackDevice.device_id, RackDevice.node_id).where(
+ RackDevice.design_id == design_id
)
- ).scalars().all()
- if row
- }
+ )
+ ).all()
+ mounted = {device_id for device_id, _ in mounts if device_id}
+ # A mount can name its canvas node itself, when the user linked one by hand
+ # in the rack. That beats the IEEE/IP guess below: the guess is what failed
+ # to find anything in the first place.
+ pinned = {device_id: node_id for device_id, node_id in mounts if device_id and node_id}
# Correlate against canvas nodes for live status: IEEE first (stable), then IP.
nodes = (await db.execute(select(Node))).scalars().all()
+ by_id = {n.id: n for n in nodes}
by_ieee = {n.ieee_address: n for n in nodes if n.ieee_address}
by_ip: dict[str, Node] = {}
for node in nodes:
@@ -300,7 +304,11 @@ async def rack_inventory(
for device in devices:
if device.suggested_type in _UNRACKABLE_TYPES:
continue
- linked: Node | None = by_ieee.get(device.ieee_address) if device.ieee_address else None
+ # A node the user linked by hand wins; a deleted one falls back to the
+ # guess rather than reporting a node that no longer exists.
+ linked: Node | None = by_id.get(pinned.get(device.id) or "")
+ if linked is None and device.ieee_address:
+ linked = by_ieee.get(device.ieee_address)
if linked is None:
linked = next((by_ip[t] for t in _ip_tokens(device.ip) if t in by_ip), None)
# The node is the richer record once a device has been approved onto a
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.py
index 56a91a5..b626b98 100644
--- a/backend/app/api/routes/scan.py
+++ b/backend/app/api/routes/scan.py
@@ -12,9 +12,17 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.api.deps import get_current_user
from app.core.config import settings
from app.db.database import AsyncSessionLocal, get_db
-from app.db.models import Design, Edge, Node, PendingDevice, PendingDeviceLink, ScanRun
+from app.db.models import (
+ Design,
+ Edge,
+ InventoryDevice,
+ InventoryDeviceLink,
+ Node,
+ RackDevice,
+ ScanRun,
+)
from app.schemas.nodes import NodeCreate
-from app.schemas.scan import PendingDeviceCreate, PendingDeviceResponse, ScanRunResponse
+from app.schemas.scan import InventoryDeviceCreate, InventoryDeviceResponse, ScanRunResponse
from app.services.mac_utils import normalize_mac
from app.services.node_dedupe import dedupe_nodes_by_ieee, find_duplicate_node
from app.services.scanner import DeepScanOptions, _valid_port_range, request_cancel, run_scan
@@ -39,7 +47,7 @@ def _ip_tokens(ip: str | None) -> list[str]:
return [t.strip() for t in ip.split(",") if t.strip()] if ip else []
-def _is_rack_only(device: PendingDevice) -> bool:
+def _is_rack_only(device: InventoryDevice) -> bool:
"""True for inventory entries created from a rack canvas.
They describe a mount — a patch panel, a shelf, a chassis — not a host to
@@ -234,7 +242,7 @@ def _agg(values: list[datetime], *, newest: bool) -> datetime | None:
async def _canvas_correlation(
- db: AsyncSession, devices: list[PendingDevice]
+ db: AsyncSession, devices: list[InventoryDevice]
) -> dict[str, dict[str, Any]]:
"""Correlate each device to existing canvas nodes by ``ieee_address``, ``mac``
or ``ip``.
@@ -300,8 +308,8 @@ async def _canvas_correlation(
async def _with_canvas_counts(
- db: AsyncSession, devices: list[PendingDevice]
-) -> list[PendingDevice]:
+ db: AsyncSession, devices: list[InventoryDevice]
+) -> list[InventoryDevice]:
"""Attach transient canvas count + linked-node timestamps for the response."""
info = await _canvas_correlation(db, devices)
for d in devices:
@@ -314,26 +322,26 @@ async def _with_canvas_counts(
return devices
[email protected]("/pending", response_model=list[PendingDeviceResponse])
-async def list_pending(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[PendingDevice]:
[email protected]("/pending", response_model=list[InventoryDeviceResponse])
+async def list_pending(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[InventoryDevice]:
# Inventory: every scanned device except the user-hidden ones. Approved devices
# stay listed so they keep showing with a canvas-presence badge.
- result = await db.execute(select(PendingDevice).where(PendingDevice.status != "hidden"))
+ result = await db.execute(select(InventoryDevice).where(InventoryDevice.status != "hidden"))
return await _with_canvas_counts(db, list(result.scalars().all()))
[email protected]("/pending", response_model=PendingDeviceResponse, status_code=201)
[email protected]("/pending", response_model=InventoryDeviceResponse, status_code=201)
async def create_pending(
- body: PendingDeviceCreate,
+ body: InventoryDeviceCreate,
db: AsyncSession = Depends(get_db),
_: str = Depends(get_current_user),
-) -> PendingDevice:
+) -> InventoryDevice:
"""Add an inventory entry by hand, for hardware no scan can discover.
Lands as ``status="pending"`` like a discovery would, so the existing approve
/ hide / restore flows apply unchanged.
"""
- device = PendingDevice(
+ device = InventoryDevice(
hostname=body.hostname,
ip=body.ip,
# Canonical form, like every other write path: dedup compares MACs by
@@ -360,14 +368,45 @@ async def clear_pending(
_: str = Depends(get_current_user),
) -> dict[str, int]:
from sqlalchemy import delete as sa_delete
- result = await db.execute(sa_delete(PendingDevice).where(PendingDevice.status == "pending"))
+ result = await db.execute(sa_delete(InventoryDevice).where(InventoryDevice.status == "pending"))
await db.commit()
return {"deleted": result.rowcount}
[email protected]("/hidden", response_model=list[PendingDeviceResponse])
-async def list_hidden(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[PendingDevice]:
- result = await db.execute(select(PendingDevice).where(PendingDevice.status == "hidden"))
[email protected]("/pending/{device_id}", response_model=dict)
+async def delete_pending(
+ device_id: str,
+ db: AsyncSession = Depends(get_db),
+ _: str = Depends(get_current_user),
+) -> dict[str, bool]:
+ """Remove one inventory entry.
+
+ Used by the rack canvas to drop the placeholder it created for a plate once
+ that plate is pointed at a real inventory row. Refuses while a rack still
+ mounts the device: SQLite runs with foreign keys off here, so the mount's
+ ``device_id`` would be left naming a row that no longer exists rather than
+ being cleared by the ``ON DELETE SET NULL`` the schema declares.
+ """
+ device = (
+ await db.execute(select(InventoryDevice).where(InventoryDevice.id == device_id))
+ ).scalar_one_or_none()
+ if not device:
+ raise HTTPException(status_code=404, detail="Device not found")
+
+ mounted = (
+ await db.execute(select(RackDevice.id).where(RackDevice.device_id == device_id).limit(1))
+ ).scalar_one_or_none()
+ if mounted:
+ raise HTTPException(status_code=409, detail="Device is mounted in a rack")
+
+ await db.delete(device)
+ await db.commit()
+ return {"deleted": True}
+
+
[email protected]("/hidden", response_model=list[InventoryDeviceResponse])
+async def list_hidden(db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)) -> list[InventoryDevice]:
+ result = await db.execute(select(InventoryDevice).where(InventoryDevice.status == "hidden"))
return await _with_canvas_counts(db, list(result.scalars().all()))
@@ -392,9 +431,9 @@ async def bulk_approve_devices(
# node was later deleted) must still be placeable on THIS design. Duplicates
# are guarded per-design below, not by the global status flag.
result = await db.execute(
- select(PendingDevice).where(
- PendingDevice.id.in_(payload.device_ids),
- PendingDevice.status != "hidden",
+ select(InventoryDevice).where(
+ InventoryDevice.id.in_(payload.device_ids),
+ InventoryDevice.status != "hidden",
)
)
devices = result.scalars().all()
@@ -420,7 +459,7 @@ async def bulk_approve_devices(
placed_ieee: dict[str, Any] = {ieee: nid for nid, _, _, ieee in existing if ieee}
created_nodes: list[Node] = []
- approved_devices: list[PendingDevice] = []
+ approved_devices: list[InventoryDevice] = []
skipped_devices: list[dict[str, Any]] = []
for device in devices:
# Rack-only gear belongs to a rack canvas, never to a logical one.
@@ -527,9 +566,9 @@ async def bulk_hide_devices(
_: str = Depends(get_current_user),
) -> dict[str, Any]:
result = await db.execute(
- select(PendingDevice).where(
- PendingDevice.id.in_(payload.device_ids),
- PendingDevice.status == "pending",
+ select(InventoryDevice).where(
+ InventoryDevice.id.in_(payload.device_ids),
+ InventoryDevice.status == "pending",
)
)
devices = result.scalars().all()
@@ -545,7 +584,7 @@ async def restore_device(
db: AsyncSession = Depends(get_db),
_: str = Depends(get_current_user),
) -> dict[str, Any]:
- device = await db.get(PendingDevice, device_id)
+ device = await db.get(InventoryDevice, device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
if device.status != "hidden":
@@ -562,9 +601,9 @@ async def bulk_restore_devices(
_: str = Depends(get_current_user),
) -> dict[str, Any]:
result = await db.execute(
- select(PendingDevice).where(
- PendingDevice.id.in_(payload.device_ids),
- PendingDevice.status == "hidden",
+ select(InventoryDevice).where(
+ InventoryDevice.id.in_(payload.device_ids),
+ InventoryDevice.status == "hidden",
)
)
devices = result.scalars().all()
@@ -587,7 +626,7 @@ async def approve_device(
first = (await db.execute(select(Design).order_by(Design.created_at).limit(1))).scalar()
node_design_id = first.id if first else None
- device = await db.get(PendingDevice, device_id)
+ device = await db.get(InventoryDevice, device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
# A device's status is GLOBAL — it flips to "approved" the moment it lands on
@@ -676,10 +715,10 @@ async def _is_proxmox_cluster_member(db: AsyncSession, ieee: str | None) -> bool
return False
found = (
await db.execute(
- select(PendingDeviceLink.id)
+ select(InventoryDeviceLink.id)
.where(
- PendingDeviceLink.discovery_source == "proxmox_cluster",
- (PendingDeviceLink.source_ieee == ieee) | (PendingDeviceLink.target_ieee == ieee),
+ InventoryDeviceLink.discovery_source == "proxmox_cluster",
+ (InventoryDeviceLink.source_ieee == ieee) | (InventoryDeviceLink.target_ieee == ieee),
)
.limit(1)
)
@@ -690,7 +729,7 @@ async def _is_proxmox_cluster_member(db: AsyncSession, ieee: str | None) -> bool
async def _resolve_pending_links_for_ieee(
db: AsyncSession, ieee: str | None, design_id: str | None
) -> list[dict[str, str]]:
- """Materialize edges for any pending_device_links involving ``ieee`` on the
+ """Materialize edges for any device_inventory_links involving ``ieee`` on the
canvas identified by ``design_id``.
For each link where the other endpoint already exists as a Node *on this
@@ -704,9 +743,9 @@ async def _resolve_pending_links_for_ieee(
return []
links_q = await db.execute(
- select(PendingDeviceLink).where(
- (PendingDeviceLink.source_ieee == ieee)
- | (PendingDeviceLink.target_ieee == ieee)
+ select(InventoryDeviceLink).where(
+ (InventoryDeviceLink.source_ieee == ieee)
+ | (InventoryDeviceLink.target_ieee == ieee)
)
)
links = list(links_q.scalars().all())
@@ -806,7 +845,7 @@ async def _resolve_pending_links_for_ieee(
async def hide_device(
device_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)
) -> dict[str, bool]:
- device = await db.get(PendingDevice, device_id)
+ device = await db.get(InventoryDevice, device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
device.status = "hidden"
@@ -818,7 +857,7 @@ async def hide_device(
async def ignore_device(
device_id: str, db: AsyncSession = Depends(get_db), _: str = Depends(get_current_user)
) -> dict[str, bool]:
- device = await db.get(PendingDevice, device_id)
+ device = await db.get(InventoryDevice, device_id)
if not device:
raise HTTPException(status_code=404, detail="Device not found")
await db.delete(device)
diff --git a/backend/app/api/routes/stats.py b/backend/app/api/routes/stats.py
index e3979f6..6705269 100644
--- a/backend/app/api/routes/stats.py
+++ b/backend/app/api/routes/stats.py
@@ -6,7 +6,7 @@ from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.db.database import get_db
-from app.db.models import Node, PendingDevice, ScanRun
+from app.db.models import InventoryDevice, Node, ScanRun
router = APIRouter()
@@ -38,8 +38,8 @@ async def summary(
pending = (
await db.execute(
select(func.count())
- .select_from(PendingDevice)
- .where(PendingDevice.status == "pending")
+ .select_from(InventoryDevice)
+ .where(InventoryDevice.status == "pending")
)
).scalar_one()
@@ -58,6 +58,8 @@ async def summary(
"online": counts.get("online", 0),
"offline": counts.get("offline", 0),
"unknown": counts.get("unknown", 0),
+ # Wire key kept from before the table was renamed to `device_inventory`:
+ # the stats payload is a published contract, and the MCP server reads it.
"pending_devices": pending,
"zigbee_devices": zigbee,
"last_scan_at": last_scan_at.isoformat() if last_scan_at else None,
diff --git a/backend/app/api/routes/zigbee.py b/backend/app/api/routes/zigbee.py
index 474666e..15055e8 100644
--- a/backend/app/api/routes/zigbee.py
+++ b/backend/app/api/routes/zigbee.py
@@ -13,7 +13,7 @@ from app.api.deps import get_current_user
from app.core.config import settings
from app.core.scheduler import reschedule_zigbee_sync, set_zigbee_sync_enabled
from app.db.database import AsyncSessionLocal, get_db
-from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
+from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
from app.schemas.scan import ScanRunResponse
from app.schemas.zigbee import (
ZigbeeConfig,
@@ -185,7 +185,7 @@ async def _persist_pending_import(
nodes_raw: list[dict[str, Any]],
edges_raw: list[dict[str, Any]],
) -> ZigbeeImportPendingResponse:
- """Upsert nodes/edges into pending_devices + pending_device_links.
+ """Upsert nodes/edges into device_inventory + device_inventory_links.
Coordinator auto-approves to a canvas Node. Other devices upsert by IEEE.
All zigbee-source links are wiped and re-inserted from the new map.
@@ -230,12 +230,12 @@ async def _persist_pending_import(
)
inv = (
await db.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == ieee)
+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
)
).scalar_one_or_none()
if inv is None:
db.add(
- PendingDevice(
+ InventoryDevice(
ieee_address=ieee,
friendly_name=n.get("friendly_name"),
hostname=n.get("friendly_name"),
@@ -263,12 +263,12 @@ async def _persist_pending_import(
continue
result = await db.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == ieee)
+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
)
pending = result.scalar_one_or_none()
if pending is None:
db.add(
- PendingDevice(
+ InventoryDevice(
ieee_address=ieee,
friendly_name=n.get("friendly_name"),
hostname=n.get("friendly_name"),
@@ -303,7 +303,7 @@ async def _persist_pending_import(
# Replace all zigbee-source links with the freshly discovered set.
await db.execute(
- sa_delete(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "zigbee")
+ sa_delete(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "zigbee")
)
links_recorded = 0
@@ -315,7 +315,7 @@ async def _persist_pending_import(
continue
seen.add((src, tgt))
db.add(
- PendingDeviceLink(
+ InventoryDeviceLink(
source_ieee=src,
target_ieee=tgt,
discovery_source="zigbee",
diff --git a/backend/app/api/routes/zwave.py b/backend/app/api/routes/zwave.py
index 46b874f..22db66c 100644
--- a/backend/app/api/routes/zwave.py
+++ b/backend/app/api/routes/zwave.py
@@ -13,7 +13,7 @@ from app.api.deps import get_current_user
from app.core.config import settings
from app.core.scheduler import reschedule_zwave_sync, set_zwave_sync_enabled
from app.db.database import AsyncSessionLocal, get_db
-from app.db.models import Node, PendingDevice, PendingDeviceLink, ScanRun
+from app.db.models import InventoryDevice, InventoryDeviceLink, Node, ScanRun
from app.schemas.scan import ScanRunResponse
from app.schemas.zwave import (
ZwaveConfig,
@@ -182,7 +182,7 @@ async def _persist_pending_import(
nodes_raw: list[dict[str, Any]],
edges_raw: list[dict[str, Any]],
) -> ZwaveImportPendingResponse:
- """Upsert nodes/edges into pending_devices + pending_device_links.
+ """Upsert nodes/edges into device_inventory + device_inventory_links.
Coordinator auto-approves to a canvas Node. Other devices upsert by Z-Wave
identity. All zwave-source links are wiped and re-inserted from the new map.
@@ -225,12 +225,12 @@ async def _persist_pending_import(
)
inv = (
await db.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == ieee)
+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
)
).scalar_one_or_none()
if inv is None:
db.add(
- PendingDevice(
+ InventoryDevice(
ieee_address=ieee,
friendly_name=n.get("friendly_name"),
hostname=n.get("friendly_name"),
@@ -257,12 +257,12 @@ async def _persist_pending_import(
continue
result = await db.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == ieee)
+ select(InventoryDevice).where(InventoryDevice.ieee_address == ieee)
)
pending = result.scalar_one_or_none()
if pending is None:
db.add(
- PendingDevice(
+ InventoryDevice(
ieee_address=ieee,
friendly_name=n.get("friendly_name"),
hostname=n.get("friendly_name"),
@@ -292,7 +292,7 @@ async def _persist_pending_import(
# Replace all zwave-source links with the freshly discovered set.
await db.execute(
- sa_delete(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "zwave")
+ sa_delete(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "zwave")
)
links_recorded = 0
@@ -304,7 +304,7 @@ async def _persist_pending_import(
continue
seen.add((src, tgt))
db.add(
- PendingDeviceLink(
+ InventoryDeviceLink(
source_ieee=src,
target_ieee=tgt,
discovery_source="zwave",
diff --git a/backend/app/db/database.py b/backend/app/db/database.py
index df0889b..e8c9fab 100644
--- a/backend/app/db/database.py
+++ b/backend/app/db/database.py
@@ -60,9 +60,67 @@ def _backup_db() -> None:
logger.warning("Could not create DB backup at %s", backup_path)
+# Tables renamed in 3.2.0. "Pending devices" was the scanner's word for a queue
+# of finds awaiting approval; the same rows outlive approval, are edited by hand
+# and are what a rack mounts, so the product calls them the Device Inventory.
+# Only the names moved — every column, every row and every route is unchanged.
+_RENAMED_TABLES: list[tuple[str, str]] = [
+ ("pending_devices", "device_inventory"),
+ ("pending_device_links", "device_inventory_links"),
+]
+
+
+async def _rename_legacy_tables(conn: AsyncConnection) -> None:
+ """Rename the pre-3.2.0 inventory tables. Must run before `create_all`.
+
+ Order matters: `create_all` would otherwise create an empty
+ `device_inventory` beside the populated `pending_devices`, and every device
+ the user ever scanned would look lost.
+
+ Foreign keys are switched on for the rename so SQLite rewrites the
+ ``REFERENCES pending_devices`` clause in `rack_devices` too; enforcement is
+ off at runtime, so a missed rewrite costs nothing today, but it would leave
+ the schema naming a table that no longer exists.
+ """
+ for old, new in _RENAMED_TABLES:
+ rows = (
+ await conn.exec_driver_sql(
+ "SELECT name FROM sqlite_master WHERE type='table' AND name IN (?, ?)",
+ (old, new),
+ )
+ ).fetchall()
+ names = {r[0] for r in rows}
+ if old not in names:
+ continue # Fresh install, or already migrated.
+ if new in names:
+ # A start that ran `create_all` before this migration existed left an
+ # empty new table beside the populated old one, and the app read the
+ # empty one. Clear it out of the way rather than stranding the data;
+ # a new table with rows in it means the rename already happened and
+ # something re-created the old one, which is not ours to resolve.
+ count = (await conn.exec_driver_sql(f"SELECT COUNT(*) FROM {new}")).scalar()
+ if count:
+ logger.warning(
+ "Both %s and %s hold rows; leaving them alone. Merge them by hand.", old, new
+ )
+ continue
+ logger.info("Dropping the empty %s left by an earlier start", new)
+ await _try_migrate(conn, f"DROP TABLE {new}", label=f"{new}.drop_empty")
+ logger.info("Migrating table %s -> %s", old, new)
+ with suppress(OperationalError):
+ await conn.exec_driver_sql("PRAGMA foreign_keys = ON")
+ await _try_migrate(conn, f"ALTER TABLE {old} RENAME TO {new}", label=f"{new}.rename")
+ # The index rides the rename under its old name; the model asks for the new
+ # one, so drop the stale duplicate rather than carrying both.
+ await _try_migrate(
+ conn, "DROP INDEX IF EXISTS ix_pending_devices_ieee_address", label="device_inventory.index",
+ )
+
+
async def init_db() -> None:
_backup_db()
async with engine.begin() as conn:
+ await _rename_legacy_tables(conn)
await conn.run_sync(Base.metadata.create_all)
# Add columns introduced after initial schema (idempotent)
with suppress(OperationalError):
@@ -114,11 +172,11 @@ async def init_db() -> None:
with suppress(OperationalError):
await conn.exec_driver_sql("ALTER TABLE nodes ADD COLUMN right_handles INTEGER NOT NULL DEFAULT 0")
with suppress(OperationalError):
- await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN discovery_source TEXT")
+ await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN discovery_source TEXT")
with suppress(OperationalError):
- await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN properties JSON")
+ await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN properties JSON")
with suppress(OperationalError):
- await conn.exec_driver_sql("UPDATE pending_devices SET properties = '[]' WHERE properties IS NULL")
+ await conn.exec_driver_sql("UPDATE device_inventory SET properties = '[]' WHERE properties IS NULL")
with suppress(OperationalError):
await conn.exec_driver_sql("ALTER TABLE scan_runs ADD COLUMN kind TEXT NOT NULL DEFAULT 'ip'")
# --- Zigbee schema migrations (logged variant per CLAUDE.md feedback) ---
@@ -128,32 +186,32 @@ async def init_db() -> None:
"nodes.ieee_address.index",
"CREATE INDEX IF NOT EXISTS ix_nodes_ieee_address ON nodes(ieee_address)",
),
- ("pending_devices.ieee_address", "ALTER TABLE pending_devices ADD COLUMN ieee_address TEXT"),
+ ("device_inventory.ieee_address", "ALTER TABLE device_inventory ADD COLUMN ieee_address TEXT"),
(
- "pending_devices.ieee_address.index",
- "CREATE INDEX IF NOT EXISTS ix_pending_devices_ieee_address "
- "ON pending_devices(ieee_address)",
+ "device_inventory.ieee_address.index",
+ "CREATE INDEX IF NOT EXISTS ix_device_inventory_ieee_address "
+ "ON device_inventory(ieee_address)",
),
- ("pending_devices.friendly_name", "ALTER TABLE pending_devices ADD COLUMN friendly_name TEXT"),
- ("pending_devices.device_subtype", "ALTER TABLE pending_devices ADD COLUMN device_subtype TEXT"),
- ("pending_devices.model", "ALTER TABLE pending_devices ADD COLUMN model TEXT"),
- ("pending_devices.vendor", "ALTER TABLE pending_devices ADD COLUMN vendor TEXT"),
- ("pending_devices.lqi", "ALTER TABLE pending_devices ADD COLUMN lqi INTEGER"),
+ ("device_inventory.friendly_name", "ALTER TABLE device_inventory ADD COLUMN friendly_name TEXT"),
+ ("device_inventory.device_subtype", "ALTER TABLE device_inventory ADD COLUMN device_subtype TEXT"),
+ ("device_inventory.model", "ALTER TABLE device_inventory ADD COLUMN model TEXT"),
+ ("device_inventory.vendor", "ALTER TABLE device_inventory ADD COLUMN vendor TEXT"),
+ ("device_inventory.lqi", "ALTER TABLE device_inventory ADD COLUMN lqi INTEGER"),
]
for label, sql in zigbee_migrations:
await _try_migrate(conn, sql, label=label)
- # Drop NOT NULL on pending_devices.ip (Zigbee devices have no IP).
+ # Drop NOT NULL on device_inventory.ip (Zigbee devices have no IP).
# SQLite can't ALTER column nullability — rebuild the table if needed.
try:
- info = await conn.exec_driver_sql("PRAGMA table_info(pending_devices)")
+ info = await conn.exec_driver_sql("PRAGMA table_info(device_inventory)")
cols = info.fetchall()
ip_col = next((c for c in cols if c[1] == "ip"), None)
# PRAGMA table_info row layout: (cid, name, type, notnull, dflt, pk)
if ip_col and ip_col[3] == 1:
- logger.info("Migrating pending_devices: dropping NOT NULL on ip column")
+ logger.info("Migrating device_inventory: dropping NOT NULL on ip column")
await conn.exec_driver_sql("PRAGMA foreign_keys = OFF")
await conn.exec_driver_sql(
- "CREATE TABLE pending_devices_new ("
+ "CREATE TABLE device_inventory_new ("
"id VARCHAR PRIMARY KEY,"
"ip VARCHAR,"
"mac VARCHAR, hostname VARCHAR, os VARCHAR, services JSON,"
@@ -171,25 +229,25 @@ async def init_db() -> None:
")"
)
await conn.exec_driver_sql(
- "INSERT INTO pending_devices_new "
+ "INSERT INTO device_inventory_new "
"(id, ip, mac, hostname, os, services, suggested_type, status, "
"discovery_source, ieee_address, friendly_name, device_subtype, "
"model, vendor, lqi, discovered_at) "
"SELECT id, ip, mac, hostname, os, services, suggested_type, status, "
"discovery_source, ieee_address, friendly_name, device_subtype, "
- "model, vendor, lqi, discovered_at FROM pending_devices"
+ "model, vendor, lqi, discovered_at FROM device_inventory"
)
- await conn.exec_driver_sql("DROP TABLE pending_devices")
+ await conn.exec_driver_sql("DROP TABLE device_inventory")
await conn.exec_driver_sql(
- "ALTER TABLE pending_devices_new RENAME TO pending_devices"
+ "ALTER TABLE device_inventory_new RENAME TO device_inventory"
)
await conn.exec_driver_sql(
- "CREATE INDEX IF NOT EXISTS ix_pending_devices_ieee_address "
- "ON pending_devices(ieee_address)"
+ "CREATE INDEX IF NOT EXISTS ix_device_inventory_ieee_address "
+ "ON device_inventory(ieee_address)"
)
await conn.exec_driver_sql("PRAGMA foreign_keys = ON")
except OperationalError as exc:
- logger.warning("pending_devices ip-nullable rebuild failed: %s", exc)
+ logger.warning("device_inventory ip-nullable rebuild failed: %s", exc)
# --- end Zigbee schema migrations -------------------------------------
# --- Electrical designs schema migrations -----------------------------
# Create designs table (idempotent)
@@ -341,28 +399,28 @@ async def init_db() -> None:
# Proxmox import carries every source. Backfill from the legacy single
# discovery_source so existing rows show under their filter.
with suppress(OperationalError):
- await conn.exec_driver_sql("ALTER TABLE pending_devices ADD COLUMN discovery_sources JSON")
+ await conn.exec_driver_sql("ALTER TABLE device_inventory ADD COLUMN discovery_sources JSON")
with suppress(OperationalError):
await conn.exec_driver_sql(
- "UPDATE pending_devices SET discovery_sources = json_array(discovery_source) "
+ "UPDATE device_inventory SET discovery_sources = json_array(discovery_source) "
"WHERE discovery_sources IS NULL AND discovery_source IS NOT NULL"
)
# Legacy IP-scanned rows predating discovery_source have a NULL scalar
# but a real IP — treat them as an ARP scan so they keep the IP tag.
with suppress(OperationalError):
await conn.exec_driver_sql(
- "UPDATE pending_devices SET discovery_sources = json_array('arp') "
+ "UPDATE device_inventory SET discovery_sources = json_array('arp') "
"WHERE discovery_sources IS NULL AND discovery_source IS NULL AND ip IS NOT NULL"
)
with suppress(OperationalError):
await conn.exec_driver_sql(
- "UPDATE pending_devices SET discovery_sources = '[]' WHERE discovery_sources IS NULL"
+ "UPDATE device_inventory SET discovery_sources = '[]' WHERE discovery_sources IS NULL"
)
# Canonicalize stored MACs (lowercase, ':' separators) so cross-source
# dedup can match a Proxmox NIC MAC against an ARP-scanned one by equality.
with suppress(OperationalError):
await conn.exec_driver_sql(
- "UPDATE pending_devices SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL"
+ "UPDATE device_inventory SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL"
)
with suppress(OperationalError):
await conn.exec_driver_sql(
diff --git a/backend/app/db/models.py b/backend/app/db/models.py
index 79ae719..9fc193a 100644
--- a/backend/app/db/models.py
+++ b/backend/app/db/models.py
@@ -138,7 +138,7 @@ class RackDevice(Base):
Two independent, both-optional links back to the rest of the app:
- * `device_id` — the Device Inventory entry (`pending_devices`). This is the
+ * `device_id` — the Device Inventory entry (`device_inventory`). This is the
primary link: inventory rows survive approval *and* node deletion, so
unracking or deleting a canvas node never removes the inventory entry.
* `node_id` — the logical-canvas node, when one exists. Only used to resolve
@@ -154,7 +154,7 @@ class RackDevice(Base):
design_id: Mapped[str] = mapped_column(String, ForeignKey("designs.id", ondelete="CASCADE"), nullable=False)
rack_id: Mapped[str] = mapped_column(String, ForeignKey("racks.id", ondelete="CASCADE"), nullable=False)
device_id: Mapped[str | None] = mapped_column(
- String, ForeignKey("pending_devices.id", ondelete="SET NULL"), nullable=True
+ String, ForeignKey("device_inventory.id", ondelete="SET NULL"), nullable=True
)
node_id: Mapped[str | None] = mapped_column(String, ForeignKey("nodes.id", ondelete="SET NULL"), nullable=True)
label: Mapped[str] = mapped_column(String, nullable=False)
@@ -203,8 +203,8 @@ class RackCable(Base):
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)
-class PendingDevice(Base):
- __tablename__ = "pending_devices"
+class InventoryDevice(Base):
+ __tablename__ = "device_inventory"
# Permit the plain (non-Mapped[]) annotations on the transient request-only
# attributes below; without this SQLAlchemy 2.0 tries to map them as columns.
__allow_unmapped__ = True
@@ -247,16 +247,16 @@ class PendingDevice(Base):
node_last_seen: datetime | None = None
-class PendingDeviceLink(Base):
+class InventoryDeviceLink(Base):
"""Link between two Zigbee endpoints discovered during import.
Endpoints are addressed by IEEE (stable across re-imports). Either side may
already exist as a canvas Node (resolved via Node.ieee_address) or still be
- a PendingDevice. On approval, the matching Edge is auto-created when both
+ a InventoryDevice. On approval, the matching Edge is auto-created when both
endpoints exist as canvas Nodes.
"""
- __tablename__ = "pending_device_links"
+ __tablename__ = "device_inventory_links"
id: Mapped[str] = mapped_column(String, primary_key=True, default=_uuid)
source_ieee: Mapped[str] = mapped_column(String, nullable=False, index=True)
diff --git a/backend/app/schemas/scan.py b/backend/app/schemas/scan.py
index 018567a..66a390b 100644
--- a/backend/app/schemas/scan.py
+++ b/backend/app/schemas/scan.py
@@ -4,7 +4,7 @@ from typing import Any
from pydantic import BaseModel, field_validator
-class PendingDeviceResponse(BaseModel):
+class InventoryDeviceResponse(BaseModel):
id: str
ip: str | None
mac: str | None
@@ -56,7 +56,7 @@ on the network, so they are never placed on a logical canvas.
MANUAL_SOURCES = {"manual", "rack"}
-class PendingDeviceCreate(BaseModel):
+class InventoryDeviceCreate(BaseModel):
"""Manually add an entry to the Device Inventory.
Used when the user documents hardware no scan can find — a dumb switch, a
diff --git a/backend/app/services/discovery_sources.py b/backend/app/services/discovery_sources.py
index e0e5344..f6a46ee 100644
--- a/backend/app/services/discovery_sources.py
+++ b/backend/app/services/discovery_sources.py
@@ -1,4 +1,4 @@
-"""Helpers for the multi-valued ``PendingDevice.discovery_sources`` set.
+"""Helpers for the multi-valued ``InventoryDevice.discovery_sources`` set.
A device discovered by more than one path (e.g. an IP scan *and* a Proxmox
import) accumulates every source that has seen it, so it surfaces under each
diff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.py
index cb70362..dc6bd95 100644
--- a/backend/app/services/scanner.py
+++ b/backend/app/services/scanner.py
@@ -15,7 +15,7 @@ from sqlalchemy import or_, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
-from app.db.models import Node, PendingDevice, ScanRun
+from app.db.models import InventoryDevice, Node, ScanRun
from app.services.discovery_sources import add_source
from app.services.fingerprint import fingerprint_ports, suggest_node_type
from app.services.http_probe import probe_open_ports
@@ -476,12 +476,12 @@ async def _dedupe_pending_by_ip(db: AsyncSession) -> int:
otherwise the oldest row, and deletes the rest. Returns the number deleted.
"""
rows = (await db.execute(
- select(PendingDevice)
- .where(PendingDevice.status != "hidden", PendingDevice.ip.isnot(None))
- .order_by(PendingDevice.discovered_at)
+ select(InventoryDevice)
+ .where(InventoryDevice.status != "hidden", InventoryDevice.ip.isnot(None))
+ .order_by(InventoryDevice.discovered_at)
)).scalars().all()
- by_ip: dict[str, list[PendingDevice]] = {}
+ by_ip: dict[str, list[InventoryDevice]] = {}
for row in rows:
if row.ip is None: # guarded by the query, but keeps the type checker happy
continue
@@ -507,7 +507,7 @@ async def run_scan(
run_id: str,
deep_scan: DeepScanOptions | None = None,
) -> None:
- """Execute scan for given CIDR ranges and populate pending_devices."""
+ """Execute scan for given CIDR ranges and populate device_inventory."""
from app.api.routes.status import broadcast_scan_update
deep_scan = deep_scan or DeepScanOptions()
@@ -527,7 +527,7 @@ async def run_scan(
# Devices already on a canvas are intentionally NOT suppressed: they stay
# in the inventory and are badged "In N canvas" via per-request correlation.
hidden_ips_result = await db.execute(
- select(PendingDevice.ip).where(PendingDevice.status == "hidden")
+ select(InventoryDevice.ip).where(InventoryDevice.status == "hidden")
)
hidden_ips: set[str] = {row[0] for row in hidden_ips_result.fetchall()}
@@ -570,13 +570,13 @@ async def run_scan(
# a duplicate — and so a device previously imported from Proxmox (which
# may have no IP but a known NIC MAC) reconciles with this scan instead
# of doubling up. Hidden rows are already skipped above.
- match_cond = [PendingDevice.ip == ip]
+ match_cond = [InventoryDevice.ip == ip]
if norm_mac:
- match_cond.append(PendingDevice.mac == norm_mac)
+ match_cond.append(InventoryDevice.mac == norm_mac)
existing_rows = (await db.execute(
- select(PendingDevice)
- .where(or_(*match_cond), PendingDevice.status != "hidden")
- .order_by(PendingDevice.discovered_at)
+ select(InventoryDevice)
+ .where(or_(*match_cond), InventoryDevice.status != "hidden")
+ .order_by(InventoryDevice.discovered_at)
)).scalars().all()
if existing_rows:
@@ -600,7 +600,7 @@ async def run_scan(
keep.discovery_sources = add_source(keep.discovery_sources, discovery_source)
# status preserved — an approved device stays approved.
else:
- db.add(PendingDevice(
+ db.add(InventoryDevice(
ip=ip,
mac=norm_mac,
hostname=host.get("hostname"),
diff --git a/backend/tests/scan/conftest.py b/backend/tests/scan/conftest.py
index e366270..0c56ef5 100644
--- a/backend/tests/scan/conftest.py
+++ b/backend/tests/scan/conftest.py
@@ -3,13 +3,13 @@ import uuid
import pytest
-from app.db.models import PendingDevice
+from app.db.models import InventoryDevice
@pytest.fixture
async def pending_device(db_session):
import uuid
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()),
ip="192.168.1.100",
mac="aa:bb:cc:dd:ee:ff",
@@ -39,10 +39,10 @@ async def mem_db():
@pytest.fixture
-async def two_pending_devices(db_session):
+async def two_device_inventory(db_session):
devices = []
for i in range(2):
- d = PendingDevice(
+ d = InventoryDevice(
id=str(uuid.uuid4()),
ip=f"192.168.1.{10 + i}",
mac=None,
@@ -62,7 +62,7 @@ async def two_pending_devices(db_session):
@pytest.fixture
async def zigbee_pending_device(db_session):
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()),
ip=None,
mac=None,
diff --git a/backend/tests/scan/helpers.py b/backend/tests/scan/helpers.py
index dd87ea3..a078f14 100644
--- a/backend/tests/scan/helpers.py
+++ b/backend/tests/scan/helpers.py
@@ -1,7 +1,7 @@
"""Shared builders for scan test suite (pure helpers, no fixtures)."""
import uuid
-from app.db.models import Design, Node, PendingDevice
+from app.db.models import Design, InventoryDevice, Node
async def _add_design(db_session, name: str) -> str:
@@ -21,7 +21,7 @@ def _node(design_id: str, *, ip=None, ieee=None, mac=None) -> Node:
async def _seed_zigbee_pending_pair(db_session):
"""Create a coordinator Node + a pending device + a link between them."""
- from app.db.models import Node, PendingDeviceLink
+ from app.db.models import InventoryDeviceLink, Node
coord = Node(
label="Coordinator",
@@ -31,7 +31,7 @@ async def _seed_zigbee_pending_pair(db_session):
)
db_session.add(coord)
- pending = PendingDevice(
+ pending = InventoryDevice(
ieee_address="0xR1",
friendly_name="router_1",
suggested_type="zigbee_router",
@@ -42,7 +42,7 @@ async def _seed_zigbee_pending_pair(db_session):
db_session.add(pending)
db_session.add(
- PendingDeviceLink(
+ InventoryDeviceLink(
source_ieee="0xCOORD",
target_ieee="0xR1",
discovery_source="zigbee",
diff --git a/backend/tests/scan/test_scan_approve.py b/backend/tests/scan/test_scan_approve.py
index ae12cc5..ebd2aad 100644
--- a/backend/tests/scan/test_scan_approve.py
+++ b/backend/tests/scan/test_scan_approve.py
@@ -5,7 +5,7 @@ import pytest
from httpx import AsyncClient
from sqlalchemy import select
-from app.db.models import Design, Node, PendingDevice
+from app.db.models import Design, InventoryDevice, Node
from tests.scan.helpers import _add_design, _node
@@ -62,7 +62,7 @@ async def test_approve_device_conflicts_on_existing_ieee_same_design(
services=[], design_id=design.id,
)
db_session.add(existing)
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()), ieee_address="0xZZZ", suggested_type="zigbee_enddevice",
status="pending", discovery_source="zigbee",
)
@@ -103,7 +103,7 @@ async def test_approve_device_force_creates_duplicate_ieee(
label="sensor", type="zigbee_enddevice", ieee_address="0xZZZ",
services=[], design_id=design.id,
))
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()), ieee_address="0xZZZ", suggested_type="zigbee_enddevice",
status="pending", discovery_source="zigbee",
)
@@ -274,7 +274,7 @@ async def test_approve_device_places_already_approved_on_another_design(
target = await _add_design(db_session, "Network Topology")
# Device is on `other` already (its global status is "approved").
db_session.add(_node(other, ieee="0x00158d0005292b83"))
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()), ieee_address="0x00158d0005292b83",
suggested_type="zigbee_enddevice", status="approved",
discovery_source="zigbee",
@@ -399,8 +399,8 @@ async def test_ignore_device(client: AsyncClient, headers, pending_device):
@pytest.mark.asyncio
-async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids}, headers=headers)
assert res.status_code == 200
data = res.json()
@@ -418,7 +418,7 @@ async def test_bulk_approve_approves_devices(client: AsyncClient, headers, two_p
@pytest.mark.asyncio
async def test_bulk_approve_places_already_approved_device_on_another_design(
- client: AsyncClient, headers, db_session, two_pending_devices
+ client: AsyncClient, headers, db_session, two_device_inventory
):
"""Regression: a device already approved (status='approved', e.g. placed on
another canvas) must still get a node on the design being approved onto.
@@ -426,7 +426,7 @@ async def test_bulk_approve_places_already_approved_device_on_another_design(
Previously bulk-approve filtered status=='pending', so selecting an
already-approved device created no node — the user saw fewer nodes than
they selected."""
- ids = [d.id for d in two_pending_devices]
+ ids = [d.id for d in two_device_inventory]
design_a = await _add_design(db_session, "Canvas A")
design_b = await _add_design(db_session, "Canvas B")
@@ -458,10 +458,10 @@ async def test_bulk_approve_places_already_approved_device_on_another_design(
@pytest.mark.asyncio
async def test_bulk_approve_skips_device_already_on_target_design(
- client: AsyncClient, headers, db_session, two_pending_devices
+ client: AsyncClient, headers, db_session, two_device_inventory
):
"""A device already on the target canvas (same ip) is not placed twice."""
- ids = [d.id for d in two_pending_devices]
+ ids = [d.id for d in two_device_inventory]
design = await _add_design(db_session, "Canvas")
# First device already sits on the canvas (matched by ip).
db_session.add(_node(design, ip="192.168.1.10"))
@@ -487,11 +487,11 @@ async def test_bulk_approve_skips_device_already_on_target_design(
@pytest.mark.asyncio
async def test_bulk_approve_skips_device_matching_ip_in_comma_list(
- client: AsyncClient, headers, db_session, two_pending_devices
+ client: AsyncClient, headers, db_session, two_device_inventory
):
"""The on-canvas node's ip holds an IPv6 before the IPv4; the device scanned
as the plain IPv4 is still recognised as already placed (issue #258)."""
- ids = [d.id for d in two_pending_devices]
+ ids = [d.id for d in two_device_inventory]
design = await _add_design(db_session, "Canvas")
db_session.add(_node(design, ip="fe80::1, 192.168.1.10"))
await db_session.commit()
@@ -509,11 +509,11 @@ async def test_bulk_approve_skips_device_matching_ip_in_comma_list(
@pytest.mark.asyncio
async def test_bulk_approve_reports_skipped_devices(
- client: AsyncClient, headers, db_session, two_pending_devices
+ client: AsyncClient, headers, db_session, two_device_inventory
):
"""Bulk can't prompt per-device, so it reports each duplicate it skipped
(with the existing node id) instead of silently dropping it."""
- ids = [d.id for d in two_pending_devices]
+ ids = [d.id for d in two_device_inventory]
design = await _add_design(db_session, "Canvas")
existing = _node(design, ip="192.168.1.10")
db_session.add(existing)
@@ -568,7 +568,7 @@ async def test_bulk_approve_copies_mac_to_node_and_properties(
from sqlalchemy import select
from app.db.models import Node as NodeModel
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()),
ip="192.168.1.55",
mac="11:22:33:44:55:66",
@@ -597,12 +597,12 @@ async def test_bulk_approve_copies_mac_to_node_and_properties(
@pytest.mark.asyncio
-async def test_bulk_approve_sets_default_check_method(client: AsyncClient, headers, two_pending_devices, db_session):
+async def test_bulk_approve_sets_default_check_method(client: AsyncClient, headers, two_device_inventory, db_session):
"""Approved devices with an IP must default to ping; otherwise scheduler skips them."""
from sqlalchemy import select
from app.db.models import Node as NodeModel
- ids = [d.id for d in two_pending_devices]
+ ids = [d.id for d in two_device_inventory]
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids}, headers=headers)
assert res.status_code == 200
nodes = (await db_session.execute(select(NodeModel))).scalars().all()
@@ -628,8 +628,8 @@ async def test_approve_device_sets_default_check_method(client: AsyncClient, hea
@pytest.mark.asyncio
-async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
# Approve first device individually first
await client.post(
f"/api/v1/scan/pending/{ids[0]}/approve",
@@ -645,15 +645,15 @@ async def test_bulk_approve_skips_already_approved(client: AsyncClient, headers,
@pytest.mark.asyncio
-async def test_bulk_approve_requires_auth(client: AsyncClient, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_approve_requires_auth(client: AsyncClient, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
res = await client.post("/api/v1/scan/pending/bulk-approve", json={"device_ids": ids})
assert res.status_code == 401
@pytest.mark.asyncio
-async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
res = await client.post("/api/v1/scan/pending/bulk-hide", json={"device_ids": ids}, headers=headers)
assert res.status_code == 200
data = res.json()
@@ -665,8 +665,8 @@ async def test_bulk_hide_hides_devices(client: AsyncClient, headers, two_pending
@pytest.mark.asyncio
-async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
# Hide first device individually first
await client.post(f"/api/v1/scan/pending/{ids[0]}/hide", headers=headers)
# Bulk hide both — first is already hidden (not pending anymore)
@@ -678,8 +678,8 @@ async def test_bulk_hide_skips_non_pending(client: AsyncClient, headers, two_pen
@pytest.mark.asyncio
-async def test_bulk_hide_requires_auth(client: AsyncClient, two_pending_devices):
- ids = [d.id for d in two_pending_devices]
+async def test_bulk_hide_requires_auth(client: AsyncClient, two_device_inventory):
+ ids = [d.id for d in two_device_inventory]
res = await client.post("/api/v1/scan/pending/bulk-hide", json={"device_ids": ids})
assert res.status_code == 401
@@ -690,7 +690,7 @@ async def test_bulk_approve_targets_requested_design(client, headers, db_session
first design — otherwise approved devices land on the wrong canvas."""
first = await _add_design(db_session, "Default") # first design (fallback)
active = await _add_design(db_session, "zwave") # the design the user is on
- dev = PendingDevice(
+ dev = InventoryDevice(
id=str(uuid.uuid4()),
ieee_address="zwave-H-2",
friendly_name="Living Room Plug",
diff --git a/backend/tests/scan/test_scan_properties.py b/backend/tests/scan/test_scan_properties.py
index 8289472..323aa6f 100644
--- a/backend/tests/scan/test_scan_properties.py
+++ b/backend/tests/scan/test_scan_properties.py
@@ -5,7 +5,7 @@ import pytest
from httpx import AsyncClient
from sqlalchemy import select
-from app.db.models import Node, PendingDevice
+from app.db.models import InventoryDevice, Node
from tests.scan.helpers import _add_design, _seed_zigbee_pending_pair
@@ -184,7 +184,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
"""Re-running the resolution does not create a second edge for the same pair."""
from sqlalchemy import select
- from app.db.models import Edge, PendingDevice, PendingDeviceLink
+ from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
coord, pending = await _seed_zigbee_pending_pair(db_session)
body = {"label": "router_1", "type": "zigbee_router", "ip": None, "status": "unknown", "services": []}
@@ -193,7 +193,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
# Simulate a second pending row + link between same coord and a new device,
# but keep an existing edge in place to verify dedupe also handles
# the swapped-direction case.
- new_pending = PendingDevice(
+ new_pending = InventoryDevice(
ieee_address="0xR1B",
friendly_name="r1b",
suggested_type="zigbee_router",
@@ -202,7 +202,7 @@ async def test_approve_zigbee_skips_duplicate_edge(
)
db_session.add(new_pending)
db_session.add(
- PendingDeviceLink(source_ieee="0xCOORD", target_ieee="0xR1B", discovery_source="zigbee")
+ InventoryDeviceLink(source_ieee="0xCOORD", target_ieee="0xR1B", discovery_source="zigbee")
)
await db_session.commit()
res = await client.post(
@@ -220,16 +220,16 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
"""Both endpoints pending → no edge yet, link row preserved for later."""
from sqlalchemy import select
- from app.db.models import Edge, PendingDevice, PendingDeviceLink
+ from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
- a = PendingDevice(
+ a = InventoryDevice(
ieee_address="0xA",
friendly_name="a",
suggested_type="zigbee_router",
status="pending",
discovery_source="zigbee",
)
- b = PendingDevice(
+ b = InventoryDevice(
ieee_address="0xB",
friendly_name="b",
suggested_type="zigbee_enddevice",
@@ -238,7 +238,7 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
)
db_session.add_all([a, b])
db_session.add(
- PendingDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
+ InventoryDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
)
await db_session.commit()
@@ -258,7 +258,7 @@ async def test_approve_zigbee_skips_when_other_endpoint_still_pending(
edges = (await db_session.execute(select(Edge))).scalars().all()
assert edges == []
- links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
+ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
assert len(links) == 1 # preserved for later resolution
@@ -271,16 +271,16 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
be re-approved onto another canvas — it's topology, wiped only on reimport."""
from sqlalchemy import select
- from app.db.models import Edge, PendingDevice, PendingDeviceLink
+ from app.db.models import Edge, InventoryDevice, InventoryDeviceLink
- a = PendingDevice(
+ a = InventoryDevice(
ieee_address="0xA",
friendly_name="a",
suggested_type="zigbee_router",
status="pending",
discovery_source="zigbee",
)
- b = PendingDevice(
+ b = InventoryDevice(
ieee_address="0xB",
friendly_name="b",
suggested_type="zigbee_enddevice",
@@ -289,7 +289,7 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
)
db_session.add_all([a, b])
db_session.add(
- PendingDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
+ InventoryDeviceLink(source_ieee="0xA", target_ieee="0xB", discovery_source="zigbee")
)
await db_session.commit()
@@ -300,14 +300,14 @@ async def test_approve_zigbee_resolves_link_after_second_approval(
edges = (await db_session.execute(select(Edge))).scalars().all()
assert len(edges) == 1
- links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
+ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
assert len(links) == 1 # retained for re-approval onto other canvases
@pytest.mark.asyncio
async def test_single_approve_zwave_sets_wireless_fields(client, headers, db_session):
active = await _add_design(db_session, "zwave")
- dev = PendingDevice(
+ dev = InventoryDevice(
id=str(uuid.uuid4()),
ieee_address="zwave-H-9",
friendly_name="Door Sensor",
diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.py
index 012b1b6..4c3c19f 100644
--- a/backend/tests/scan/test_scan_routes.py
+++ b/backend/tests/scan/test_scan_routes.py
@@ -6,7 +6,7 @@ from unittest.mock import AsyncMock, patch
import pytest
from httpx import AsyncClient
-from app.db.models import PendingDevice
+from app.db.models import InventoryDevice
from tests.scan.helpers import _add_design, _node
@@ -91,7 +91,7 @@ async def test_canvas_count_counts_distinct_designs_by_ip(client, headers, db_se
@pytest.mark.asyncio
async def test_canvas_count_correlates_by_ieee(client, headers, db_session):
- device = PendingDevice(
+ device = InventoryDevice(
id=str(uuid.uuid4()), ieee_address="0x00124b001", discovery_source="zigbee",
suggested_type="zigbee_enddevice", services=[], status="pending",
)
@@ -289,3 +289,82 @@ async def test_create_pending_keeps_a_missing_mac_null(client: AsyncClient, head
)
assert res.status_code == 201, res.text
assert res.json()["mac"] is None
+
+
+async def test_delete_pending_removes_one_entry(client: AsyncClient, headers, pending_device):
+ # The rack canvas drops the placeholder it created for a plate once that
+ # plate is pointed at a real inventory row.
+ res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}", headers=headers)
+ assert res.status_code == 200, res.text
+ assert res.json() == {"deleted": True}
+
+ listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
+ assert listed == []
+
+
+async def test_delete_pending_unknown_is_404(client: AsyncClient, headers):
+ res = await client.delete(f"/api/v1/scan/pending/{uuid.uuid4()}", headers=headers)
+ assert res.status_code == 404
+
+
+async def test_delete_pending_requires_auth(client: AsyncClient, pending_device):
+ res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}")
+ assert res.status_code == 401
+
+
+async def test_delete_pending_refuses_a_mounted_device(client: AsyncClient, headers, pending_device):
+ # `rack_devices.device_id` is ON DELETE SET NULL: without this guard the
+ # delete would strip the mount of its device instead of erroring.
+ design = (
+ await client.post(
+ "/api/v1/designs",
+ json={"name": "Rack Room", "icon": "server", "design_type": "rack"},
+ headers=headers,
+ )
+ ).json()["id"]
+ saved = await client.post(
+ "/api/v1/racks/save",
+ json={
+ "design_id": design,
+ "racks": [
+ {
+ "id": "rack-1",
+ "name": "Main",
+ "u_height": 12,
+ "width_standard": "19",
+ "numbering": "bottom-up",
+ "style": {},
+ "pos_x": 0,
+ "pos_y": 0,
+ }
+ ],
+ "devices": [
+ {
+ "id": "dev-1",
+ "rack_id": "rack-1",
+ "device_id": pending_device.id,
+ "label": "my-server",
+ "u_start": 1,
+ "u_height": 1,
+ "col_start": 0,
+ "col_span": 12,
+ "faceplate_id": "server-1u",
+ "status": "unknown",
+ "ports": [],
+ }
+ ],
+ "cables": [],
+ "viewport": {"x": 0, "y": 0, "zoom": 1},
+ },
+ headers=headers,
+ )
+ assert saved.status_code == 200, saved.text
+
+ res = await client.delete(f"/api/v1/scan/pending/{pending_device.id}", headers=headers)
+ assert res.status_code == 409
+ listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()
+ assert [d["id"] for d in listed] == [pending_device.id]
diff --git a/backend/tests/scan/test_scan_run.py b/backend/tests/scan/test_scan_run.py
index 0994265..96d3925 100644
--- a/backend/tests/scan/test_scan_run.py
+++ b/backend/tests/scan/test_scan_run.py
@@ -7,7 +7,7 @@ from httpx import AsyncClient
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
-from app.db.models import Node, PendingDevice, ScanRun
+from app.db.models import InventoryDevice, Node, ScanRun
from app.services.scanner import _cancelled_runs, request_cancel, run_scan
@@ -118,7 +118,7 @@ async def test_run_scan_creates_new_pending_device(db_session: AsyncSession):
await run_scan(["192.168.1.0/24"], db_session, run_id)
result = await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
)
device = result.scalar_one_or_none()
assert device is not None
@@ -141,7 +141,7 @@ async def test_run_scan_keeps_stale_pending_for_canvas_nodes(db_session: AsyncSe
pos_x=0.0,
pos_y=0.0,
)
- stale = PendingDevice(
+ stale = InventoryDevice(
id=str(uuid.uuid4()),
ip="192.168.1.50",
mac=None,
@@ -167,7 +167,7 @@ async def test_run_scan_keeps_stale_pending_for_canvas_nodes(db_session: AsyncSe
await run_scan(["192.168.1.0/24"], db_session, run_id)
result = await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
)
assert result.scalar_one_or_none() is not None
@@ -201,7 +201,7 @@ async def test_run_scan_records_ip_already_in_canvas(db_session: AsyncSession):
await run_scan(["192.168.1.0/24"], db_session, run_id)
result = await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
)
device = result.scalar_one_or_none()
assert device is not None
@@ -212,7 +212,7 @@ async def test_run_scan_records_ip_already_in_canvas(db_session: AsyncSession):
async def test_run_scan_refreshes_approved_device_without_duplicating(db_session: AsyncSession):
"""Re-scanning an already-approved device updates its row in place instead of
spawning a fresh pending duplicate, and keeps it approved."""
- approved = PendingDevice(
+ approved = InventoryDevice(
id=str(uuid.uuid4()), ip="192.168.1.50", mac=None, hostname="old",
os=None, services=[], suggested_type="server", status="approved",
)
@@ -228,7 +228,7 @@ async def test_run_scan_refreshes_approved_device_without_duplicating(db_session
await run_scan(["192.168.1.0/24"], db_session, run_id)
rows = (await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
)).scalars().all()
assert len(rows) == 1
assert rows[0].status == "approved"
@@ -240,7 +240,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
"""Pre-existing duplicate inventory rows for one IP are collapsed to a single
row at scan start, even if the device is not re-discovered."""
for status in ("approved", "pending", "pending"):
- db_session.add(PendingDevice(
+ db_session.add(InventoryDevice(
id=str(uuid.uuid4()), ip="192.168.1.77", mac=None, hostname=None,
os=None, services=[], suggested_type="server", status=status,
))
@@ -255,7 +255,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
await run_scan(["192.168.1.0/24"], db_session, run_id)
rows = (await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.77")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.77")
)).scalars().all()
assert len(rows) == 1
assert rows[0].status == "approved" # approved row is the one kept
@@ -264,7 +264,7 @@ async def test_run_scan_collapses_existing_duplicate_rows(db_session: AsyncSessi
@pytest.mark.asyncio
async def test_run_scan_skips_hidden_device(db_session: AsyncSession):
"""Devices previously hidden by the user must not re-appear in pending on re-scan."""
- hidden = PendingDevice(
+ hidden = InventoryDevice(
id=str(uuid.uuid4()),
ip="192.168.1.50",
mac=None,
@@ -289,9 +289,9 @@ async def test_run_scan_skips_hidden_device(db_session: AsyncSession):
await run_scan(["192.168.1.0/24"], db_session, run_id)
result = await db_session.execute(
- select(PendingDevice).where(
- PendingDevice.ip == "192.168.1.50",
- PendingDevice.status == "pending",
+ select(InventoryDevice).where(
+ InventoryDevice.ip == "192.168.1.50",
+ InventoryDevice.status == "pending",
)
)
assert result.scalar_one_or_none() is None
@@ -395,7 +395,7 @@ async def test_run_scan_cancelled_mid_scan_skips_remaining_cidrs(db_session: Asy
async def test_run_scan_updates_existing_pending_device(db_session: AsyncSession):
"""Re-scanning the same IP updates services instead of creating a duplicate."""
# Pre-existing pending device with no services
- existing = PendingDevice(
+ existing = InventoryDevice(
id=str(uuid.uuid4()),
ip="192.168.1.50",
mac=None,
@@ -421,7 +421,7 @@ async def test_run_scan_updates_existing_pending_device(db_session: AsyncSession
# Should still be only one device
result = await db_session.execute(
- select(PendingDevice).where(PendingDevice.ip == "192.168.1.50")
+ select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50")
)
devices = list(result.scalars().all())
assert len(devices) == 1
diff --git a/backend/tests/test_db_migrations.py b/backend/tests/test_db_migrations.py
new file mode 100644
index 0000000..83af610
--- /dev/null
+++ b/backend/tests/test_db_migrations.py
@@ -0,0 +1,131 @@
+"""The pending_devices -> device_inventory rename, run at startup.
+
+It is the one migration that must happen *before* `create_all`, so it gets its
+own suite: get the order wrong and every device a user ever scanned reads as
+gone, because the app looks at a freshly created empty table.
+"""
+import pytest
+from sqlalchemy.ext.asyncio import create_async_engine
+
+from app.db.database import _rename_legacy_tables
+
+pytestmark = pytest.mark.asyncio
+
+
+def _legacy_ddl(table: str) -> str:
+ return f"CREATE TABLE {table} (id VARCHAR PRIMARY KEY, hostname VARCHAR)"
+
+
+async def _engine(tmp_path, *, statements: list[str]):
+ engine = create_async_engine(f"sqlite+aiosqlite:///{tmp_path / 'test.db'}")
+ async with engine.begin() as conn:
+ for sql in statements:
+ await conn.exec_driver_sql(sql)
+ return engine
+
+
+async def _tables(engine) -> set[str]:
+ async with engine.begin() as conn:
+ rows = (
+ await conn.exec_driver_sql("SELECT name FROM sqlite_master WHERE type='table'")
+ ).fetchall()
+ return {r[0] for r in rows}
+
+
+async def _rename(engine) -> None:
+ async with engine.begin() as conn:
+ await _rename_legacy_tables(conn)
+
+
+async def test_renames_the_legacy_tables_keeping_their_rows(tmp_path):
+ engine = await _engine(
+ tmp_path,
+ statements=[
+ _legacy_ddl("pending_devices"),
+ _legacy_ddl("pending_device_links"),
+ "INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'nas')",
+ ],
+ )
+
+ await _rename(engine)
+
+ assert await _tables(engine) == {"device_inventory", "device_inventory_links"}
+ async with engine.begin() as conn:
+ rows = (await conn.exec_driver_sql("SELECT hostname FROM device_inventory")).fetchall()
+ assert [r[0] for r in rows] == ["nas"]
+ await engine.dispose()
+
+
+async def test_rewrites_the_reference_from_rack_devices(tmp_path):
+ # `rack_devices.device_id` names the inventory table. Left pointing at the
+ # old name, the schema references a table that no longer exists.
+ engine = await _engine(
+ tmp_path,
+ statements=[
+ _legacy_ddl("pending_devices"),
+ "CREATE TABLE rack_devices (id VARCHAR PRIMARY KEY, device_id VARCHAR "
+ "REFERENCES pending_devices(id) ON DELETE SET NULL)",
+ ],
+ )
+
+ await _rename(engine)
+
+ async with engine.begin() as conn:
+ ddl = (
+ await conn.exec_driver_sql(
+ "SELECT sql FROM sqlite_master WHERE name='rack_devices'"
+ )
+ ).scalar()
+ assert "device_inventory" in ddl
+ assert "pending_devices" not in ddl
+ await engine.dispose()
+
+
+async def test_replaces_an_empty_table_left_by_an_earlier_start(tmp_path):
+ # A start that ran `create_all` before this migration existed created the new
+ # table empty, and the app read that one instead of the user's devices.
+ engine = await _engine(
+ tmp_path,
+ statements=[
+ _legacy_ddl("pending_devices"),
+ _legacy_ddl("device_inventory"),
+ "INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'nas')",
+ ],
+ )
+
+ await _rename(engine)
+
+ assert await _tables(engine) == {"device_inventory"}
+ async with engine.begin() as conn:
+ count = (await conn.exec_driver_sql("SELECT COUNT(*) FROM device_inventory")).scalar()
+ assert count == 1
+ await engine.dispose()
+
+
+async def test_leaves_two_populated_tables_alone(tmp_path):
+ # Rows on both sides is not a state this migration created, and dropping
+ # either one would lose data.
+ engine = await _engine(
+ tmp_path,
+ statements=[
+ _legacy_ddl("pending_devices"),
+ _legacy_ddl("device_inventory"),
+ "INSERT INTO pending_devices (id, hostname) VALUES ('d1', 'old')",
+ "INSERT INTO device_inventory (id, hostname) VALUES ('d2', 'new')",
+ ],
+ )
+
+ await _rename(engine)
+
+ assert await _tables(engine) == {"pending_devices", "device_inventory"}
+ await engine.dispose()
+
+
+async def test_is_a_no_op_on_a_fresh_database(tmp_path):
+ engine = await _engine(tmp_path, statements=[_legacy_ddl("device_inventory")])
+
+ await _rename(engine)
+ await _rename(engine) # And still a no-op the second time round.
+
+ assert await _tables(engine) == {"device_inventory"}
+ await engine.dispose()
diff --git a/backend/tests/test_proxmox_router.py b/backend/tests/test_proxmox_router.py
index 71b90d6..de616e3 100644
--- a/backend/tests/test_proxmox_router.py
+++ b/backend/tests/test_proxmox_router.py
@@ -17,7 +17,7 @@ from app.api.routes.proxmox import (
)
from app.api.routes.scan import _is_proxmox_cluster_member, _resolve_pending_links_for_ieee
from app.core.config import settings
-from app.db.models import Design, Edge, Node, PendingDevice, PendingDeviceLink
+from app.db.models import Design, Edge, InventoryDevice, InventoryDeviceLink, Node
@pytest.fixture(autouse=True)
@@ -212,7 +212,7 @@ async def test_persist_creates_pending(db_session) -> None:
result = await _persist_pending_import(db_session, nodes, edges)
assert result.pending_created == 2
assert result.links_recorded == 1
- rows = (await db_session.execute(select(PendingDevice))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
assert {r.suggested_type for r in rows} == {"proxmox", "vm"}
# Specs carried as properties.
vm = next(r for r in rows if r.suggested_type == "vm")
@@ -239,14 +239,14 @@ async def test_persist_merges_existing_scanned_node_by_ip(db_session) -> None:
assert merged.cpu_count == 2
assert any(p["key"] == "CPU Cores" for p in (merged.properties or []))
# Inventory row exists as approved (already on canvas).
- inv = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalar_one()
+ inv = (await db_session.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101"))).scalar_one()
assert inv.status == "approved"
@pytest.mark.asyncio
async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
# Device previously found by an IP scan: arp source, MAC known, no ieee.
- db_session.add(PendingDevice(
+ db_session.add(InventoryDevice(
id=str(uuid.uuid4()), ip="10.0.0.5", mac="bc:24:11:aa:bb:cc",
suggested_type="generic", status="pending",
discovery_source="arp", discovery_sources=["arp"],
@@ -257,7 +257,7 @@ async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
# different casing. Must merge, not duplicate.
await _persist_pending_import(db_session, [_guest_node(101, None, mac="BC:24:11:AA:BB:CC")], [])
- rows = (await db_session.execute(select(PendingDevice))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
assert len(rows) == 1
row = rows[0]
assert row.ieee_address == "pve-pve1-101" # adopted proxmox identity
@@ -269,7 +269,7 @@ async def test_persist_merges_pending_scan_row_by_mac(db_session) -> None:
async def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -> None:
# Legacy inventory row from an old IP scan, before discovery_source(s) were
# recorded: scalar NULL, sources empty — but it has an IP + MAC.
- db_session.add(PendingDevice(
+ db_session.add(InventoryDevice(
id=str(uuid.uuid4()), ip="192.168.1.108", mac="bc:24:11:6c:96:52",
suggested_type="lxc", status="pending",
discovery_source=None, discovery_sources=[],
@@ -280,7 +280,7 @@ async def test_persist_preserves_ip_tag_for_legacy_null_source_row(db_session) -
db_session, [_guest_node(108, "192.168.1.108", mac="BC:24:11:6C:96:52")], []
)
- rows = (await db_session.execute(select(PendingDevice))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
assert len(rows) == 1
# The IP tag must survive the proxmox merge even with no recorded origin.
assert set(rows[0].discovery_sources) == {"arp", "proxmox"}
@@ -295,7 +295,7 @@ async def test_persist_preserves_ip_tag_on_canvas_merge_legacy_row(db_session) -
ip="192.168.1.108", mac="bc:24:11:6c:96:52",
status="online", pos_x=0, pos_y=0,
)
- inv = PendingDevice(
+ inv = InventoryDevice(
id=str(uuid.uuid4()), ip="192.168.1.108", mac="bc:24:11:6c:96:52",
suggested_type="lxc", status="approved",
discovery_source=None, discovery_sources=[],
@@ -308,7 +308,7 @@ async def test_persist_preserves_ip_tag_on_canvas_merge_legacy_row(db_session) -
)
inv_row = (await db_session.execute(
- select(PendingDevice).where(PendingDevice.mac == "bc:24:11:6c:96:52")
+ select(InventoryDevice).where(InventoryDevice.mac == "bc:24:11:6c:96:52")
)).scalar_one()
assert set(inv_row.discovery_sources) == {"arp", "proxmox"}
@@ -320,7 +320,7 @@ async def test_persist_does_not_add_ip_tag_to_pure_proxmox_guest(db_session) ->
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], []) # re-sync
row = (await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101")
)).scalar_one()
assert set(row.discovery_sources) == {"proxmox"}
@@ -351,27 +351,27 @@ async def test_persist_resync_updates_in_place(db_session) -> None:
await _persist_pending_import(db_session, nodes, [])
# Second sync: same device, new IP. Should update, not duplicate.
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.9")], [])
- rows = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101"))).scalars().all()
assert len(rows) == 1
assert rows[0].ip == "10.0.0.9"
@pytest.mark.asyncio
async def test_persist_keeps_hidden_hidden(db_session) -> None:
- db_session.add(PendingDevice(
+ db_session.add(InventoryDevice(
id=str(uuid.uuid4()), ieee_address="pve-pve1-101", ip="10.0.0.5",
suggested_type="vm", status="hidden", discovery_source="proxmox",
))
await db_session.commit()
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
- row = (await db_session.execute(select(PendingDevice).where(PendingDevice.ieee_address == "pve-pve1-101"))).scalar_one()
+ row = (await db_session.execute(select(InventoryDevice).where(InventoryDevice.ieee_address == "pve-pve1-101"))).scalar_one()
assert row.status == "hidden"
@pytest.mark.asyncio
async def test_pending_endpoint_tolerates_legacy_null_properties(client: AsyncClient, headers: dict, db_session) -> None:
# Legacy row: properties column NULL (added by migration on older DBs).
- dev = PendingDevice(
+ dev = InventoryDevice(
id=str(uuid.uuid4()), ip="192.168.1.9", suggested_type="server",
status="pending", discovery_source="arp",
)
@@ -396,7 +396,7 @@ async def test_persist_records_cluster_links_between_hosts(db_session) -> None:
edges = [{"source": "pve-node-pve1", "target": "pve-pve1-101"}]
await _persist_pending_import(db_session, nodes, edges)
- links = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
+ links = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
cluster = [ln for ln in links if ln.discovery_source == "proxmox_cluster"]
assert len(cluster) == 1
assert (cluster[0].source_ieee, cluster[0].target_ieee) == ("pve-node-a", "pve-node-b")
@@ -410,7 +410,7 @@ async def test_persist_records_cluster_links_between_hosts(db_session) -> None:
async def test_single_host_records_no_cluster_link(db_session) -> None:
await _persist_pending_import(db_session, [_host_node()], [])
links = (await db_session.execute(
- select(PendingDeviceLink).where(PendingDeviceLink.discovery_source == "proxmox_cluster")
+ select(InventoryDeviceLink).where(InventoryDeviceLink.discovery_source == "proxmox_cluster")
)).scalars().all()
assert links == []
@@ -427,7 +427,7 @@ async def test_cluster_link_resolves_to_cluster_edge(db_session) -> None:
status="online", pos_x=0, pos_y=0, design_id=design.id,
left_handles=1, right_handles=1)
db_session.add_all([a, b])
- db_session.add(PendingDeviceLink(
+ db_session.add(InventoryDeviceLink(
id=str(uuid.uuid4()), source_ieee="pve-node-a", target_ieee="pve-node-b",
discovery_source="proxmox_cluster",
))
@@ -459,7 +459,7 @@ async def test_link_survives_and_resolves_onto_second_design(db_session) -> None
Node(id=str(uuid.uuid4()), type="iot", label="y", ieee_address="0xBBBB",
status="online", pos_x=0, pos_y=0, design_id=d.id),
])
- db_session.add(PendingDeviceLink(
+ db_session.add(InventoryDeviceLink(
id=str(uuid.uuid4()), source_ieee="0xAAAA", target_ieee="0xBBBB",
discovery_source="zigbee",
))
@@ -476,7 +476,7 @@ async def test_link_survives_and_resolves_onto_second_design(db_session) -> None
assert {e.design_id for e in edges} == {da.id, db_.id}
assert all(e.type == "iot" for e in edges)
# The link row is still present for any further design.
- assert (await db_session.execute(select(PendingDeviceLink))).scalars().one()
+ assert (await db_session.execute(select(InventoryDeviceLink))).scalars().one()
@pytest.mark.asyncio
@@ -484,6 +484,6 @@ async def test_persist_never_deletes(db_session) -> None:
await _persist_pending_import(db_session, [_guest_node(101, "10.0.0.5")], [])
# A later sync that no longer includes vm101 must not remove it.
await _persist_pending_import(db_session, [_guest_node(202, "10.0.0.6")], [])
- rows = (await db_session.execute(select(PendingDevice))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()
ieees = {r.ieee_address for r in rows}
assert "pve-pve1-101" in ieees and "pve-pve1-202" in ieees
diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.py
index 1e52421..f3ee776 100644
--- a/backend/tests/test_racks.py
+++ b/backend/tests/test_racks.py
@@ -2,7 +2,7 @@ import pytest
from httpx import AsyncClient
from sqlalchemy import text
-from app.db.models import PendingDevice
+from app.db.models import InventoryDevice
pytestmark = pytest.mark.asyncio
@@ -390,7 +390,7 @@ class TestInventory:
"""
design_id = await _design(client, headers)
db_session.add(
- PendingDevice(
+ InventoryDevice(
id="pd-services",
ip="192.168.1.63",
services=[
@@ -400,11 +400,11 @@ class TestInventory:
suggested_type="server",
)
)
- db_session.add(PendingDevice(id="pd-bare", ip="192.168.1.64", suggested_type="server"))
+ db_session.add(InventoryDevice(id="pd-bare", ip="192.168.1.64", suggested_type="server"))
# A portless service is no fingerprint: the inventory skips it, so must
# this — `None not in _COMMON_PORTS` is True and used to let it through.
db_session.add(
- PendingDevice(
+ InventoryDevice(
id="pd-portless",
ip="192.168.1.65",
services=[{"port": None, "category": "media", "service_name": "jellyfin"}],
@@ -486,7 +486,7 @@ class TestInventory:
# Straight to the table: the manual-create schema carries no os/services,
# and a scan find does.
db_session.add(
- PendingDevice(
+ InventoryDevice(
id="pd-nas",
hostname="nas",
ip="192.168.1.9",
@@ -525,7 +525,7 @@ class TestInventory:
headers=headers,
)
).json()
- db_session.add(PendingDevice(id="pd-seen", ip="192.168.1.77", suggested_type="server"))
+ db_session.add(InventoryDevice(id="pd-seen", ip="192.168.1.77", suggested_type="server"))
await db_session.execute(
text("UPDATE nodes SET last_seen = :ts WHERE id = :id"),
{"ts": "2026-08-08 10:00:00.000000", "id": node["id"]},
@@ -538,6 +538,79 @@ class TestInventory:
entry = next(i for i in items if i["id"] == "pd-seen")
assert entry["node_last_seen"].endswith(("Z", "+00:00"))
+ async def test_prefers_the_node_the_mount_names(self, client: AsyncClient, headers):
+ """A link the user picked in the rack beats the IEEE/IP guess.
+
+ The guess is what failed on gear with no MAC and no address, and it is
+ wrong — not merely absent — when two hosts have swapped IPs.
+ """
+ design_id = await _design(client, headers)
+ picked = (
+ await client.post(
+ "/api/v1/nodes",
+ json={"type": "pdu", "label": "pdu-main", "status": "online"},
+ headers=headers,
+ )
+ ).json()
+ guessed = (
+ await client.post(
+ "/api/v1/nodes",
+ json={"type": "server", "label": "someone-else", "ip": "192.168.1.90"},
+ headers=headers,
+ )
+ ).json()
+ device = (
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "pdu", "ip": "192.168.1.90", "suggested_type": "generic"},
+ headers=headers,
+ )
+ ).json()
+
+ payload = _state(design_id)
+ payload["devices"][0]["device_id"] = device["id"]
+ payload["devices"][0]["node_id"] = picked["id"]
+ await client.post("/api/v1/racks/save", json=payload, headers=headers)
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ entry = next(i for i in items if i["id"] == device["id"])
+ assert entry["node_id"] == picked["id"] != guessed["id"]
+ assert entry["node_label"] == "pdu-main"
+ assert entry["node_status"] == "online"
+
+ async def test_falls_back_when_the_named_node_is_gone(self, client: AsyncClient, headers):
+ """A mount keeps its `node_id` in the payload the client last sent, so a
+ node deleted meanwhile must not report a node that no longer exists.
+ """
+ design_id = await _design(client, headers)
+ guessed = (
+ await client.post(
+ "/api/v1/nodes",
+ json={"type": "server", "label": "nas", "ip": "192.168.1.91"},
+ headers=headers,
+ )
+ ).json()
+ device = (
+ await client.post(
+ "/api/v1/scan/pending",
+ json={"hostname": "nas", "ip": "192.168.1.91", "suggested_type": "nas"},
+ headers=headers,
+ )
+ ).json()
+
+ payload = _state(design_id)
+ payload["devices"][0]["device_id"] = device["id"]
+ payload["devices"][0]["node_id"] = "node-that-was-deleted"
+ await client.post("/api/v1/racks/save", json=payload, headers=headers)
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ entry = next(i for i in items if i["id"] == device["id"])
+ assert entry["node_id"] == guessed["id"]
+
async def test_leaves_the_node_fields_empty_without_a_match(
self, client: AsyncClient, headers
):
@@ -571,7 +644,7 @@ class TestInventory:
headers=headers,
)
db_session.add(
- PendingDevice(id="pd-noservices", ip="192.168.1.63", suggested_type="server")
+ InventoryDevice(id="pd-noservices", ip="192.168.1.63", suggested_type="server")
)
await db_session.commit()
diff --git a/backend/tests/test_scanner.py b/backend/tests/test_scanner.py
index a34832b..ab3210c 100644
--- a/backend/tests/test_scanner.py
+++ b/backend/tests/test_scanner.py
@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_asyn
from sqlalchemy.pool import StaticPool
from app.db.database import Base
-from app.db.models import Node, PendingDevice, ScanRun
+from app.db.models import InventoryDevice, Node, ScanRun
# ---------------------------------------------------------------------------
# Helpers
@@ -588,7 +588,7 @@ async def test_run_scan_adds_nmap_devices_as_pending(mem_db):
await run_scan(["192.168.1.0/24"], session, run_id)
async with mem_db() as session:
- result = await session.execute(sa_select(PendingDevice))
+ result = await session.execute(sa_select(InventoryDevice))
devices = result.scalars().all()
assert any(d.ip == "192.168.1.5" for d in devices)
@@ -674,7 +674,7 @@ async def test_run_scan_leaves_last_scan_untouched_on_unmatched_node(mem_db):
@pytest.mark.asyncio
async def test_run_scan_mdns_only_device_added(mem_db):
- """Devices found only by mDNS (not nmap) should appear in pending_devices."""
+ """Devices found only by mDNS (not nmap) should appear in device_inventory."""
from app.services.scanner import run_scan
run_id = _make_run_id()
@@ -691,7 +691,7 @@ async def test_run_scan_mdns_only_device_added(mem_db):
await run_scan(["192.168.1.0/24"], session, run_id)
async with mem_db() as session:
- result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.80"))
+ result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.80"))
device = result.scalar_one_or_none()
assert device is not None
@@ -709,7 +709,7 @@ async def test_run_scan_merges_proxmox_row_by_mac(mem_db):
async with mem_db() as session:
session.add(_make_scan_run(run_id))
# Previously imported from Proxmox: no IP, known NIC MAC, vm type.
- session.add(PendingDevice(
+ session.add(InventoryDevice(
id="pve-row", ieee_address="pve-pve1-101", ip=None,
mac="bc:24:11:aa:bb:cc", suggested_type="vm", status="pending",
discovery_source="proxmox", discovery_sources=["proxmox"],
@@ -727,7 +727,7 @@ async def test_run_scan_merges_proxmox_row_by_mac(mem_db):
await run_scan(["192.168.1.0/24"], session, run_id)
async with mem_db() as session:
- rows = (await session.execute(sa_select(PendingDevice))).scalars().all()
+ rows = (await session.execute(sa_select(InventoryDevice))).scalars().all()
assert len(rows) == 1 # merged, not duplicated
row = rows[0]
@@ -756,7 +756,7 @@ async def test_run_scan_mdns_skipped_if_already_in_nmap(mem_db):
await run_scan(["192.168.1.0/24"], session, run_id)
async with mem_db() as session:
- result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.10"))
+ result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.10"))
devices = result.scalars().all()
assert len(devices) == 1 # not duplicated
@@ -787,7 +787,7 @@ async def test_run_scan_keeps_canvas_nodes(mem_db):
await run_scan(["192.168.1.0/24"], session, run_id)
async with mem_db() as session:
- result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.100"))
+ result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.100"))
device = result.scalar_one_or_none()
assert device is not None
assert device.status == "pending"
@@ -801,7 +801,7 @@ async def test_run_scan_skips_hidden_devices(mem_db):
run_id = _make_run_id()
async with mem_db() as session:
session.add(_make_scan_run(run_id))
- hidden = PendingDevice(ip="192.168.1.55", status="hidden")
+ hidden = InventoryDevice(ip="192.168.1.55", status="hidden")
session.add(hidden)
await session.commit()
@@ -815,7 +815,7 @@ async def test_run_scan_skips_hidden_devices(mem_db):
async with mem_db() as session:
result = await session.execute(
- sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.55", PendingDevice.status == "pending")
+ sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.55", InventoryDevice.status == "pending")
)
assert result.scalar_one_or_none() is None
@@ -943,7 +943,7 @@ async def test_run_scan_probe_enriches_services(mem_db):
)
async with mem_db() as session:
- result = await session.execute(sa_select(PendingDevice).where(PendingDevice.ip == "192.168.1.50"))
+ result = await session.execute(sa_select(InventoryDevice).where(InventoryDevice.ip == "192.168.1.50"))
device = result.scalar_one_or_none()
assert device is not None
diff --git a/backend/tests/test_stats.py b/backend/tests/test_stats.py
index 77e033a..f9d009e 100644
--- a/backend/tests/test_stats.py
+++ b/backend/tests/test_stats.py
@@ -9,7 +9,7 @@ from httpx import AsyncClient
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
-from app.db.models import Node, PendingDevice, ScanRun
+from app.db.models import InventoryDevice, Node, ScanRun
@pytest.fixture(autouse=True)
@@ -75,9 +75,9 @@ async def test_summary_aggregates_counts(
Node(type="server", label="D", status="unknown"),
Node(type="iot", label="Z1", status="online", ieee_address="0x1"),
Node(type="iot", label="Z2", status="online", ieee_address="0x2"),
- PendingDevice(ip="10.0.0.1", status="pending"),
- PendingDevice(ip="10.0.0.2", status="pending"),
- PendingDevice(ip="10.0.0.3", status="hidden"), # excluded
+ InventoryDevice(ip="10.0.0.1", status="pending"),
+ InventoryDevice(ip="10.0.0.2", status="pending"),
+ InventoryDevice(ip="10.0.0.3", status="hidden"), # excluded
ScanRun(status="success", finished_at=finished),
ScanRun(status="success",
finished_at=datetime(2026, 5, 13, 10, 0, tzinfo=timezone.utc)),
diff --git a/backend/tests/test_zigbee_router.py b/backend/tests/test_zigbee_router.py
index 49facb0..fc533cc 100644
--- a/backend/tests/test_zigbee_router.py
+++ b/backend/tests/test_zigbee_router.py
@@ -338,7 +338,7 @@ async def test_persist_pending_import_coordinator_goes_to_pending(
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
assert result.device_count == 3
@@ -354,7 +354,7 @@ async def test_persist_pending_import_coordinator_goes_to_pending(
# Coordinator sits in the pending inventory.
coord = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
)
).scalar_one()
assert coord.status == "pending"
@@ -385,14 +385,14 @@ async def test_persist_pending_import_replaces_links(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import PendingDeviceLink
+ from app.db.models import InventoryDeviceLink
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
new_edges = [{"source": "0xCOORD", "target": "0xR1"}]
await _persist_pending_import(db_session, _PENDING_NODES[:2], new_edges)
- rows = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
assert len(rows) == 1
assert (rows[0].source_ieee, rows[0].target_ieee) == ("0xCOORD", "0xR1")
@@ -403,7 +403,7 @@ async def test_persist_pending_import_sets_coordinator_pending_fields(db_session
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
nodes_with_meta = [dict(n) for n in _PENDING_NODES]
nodes_with_meta[0]["vendor"] = "TI"
@@ -413,7 +413,7 @@ async def test_persist_pending_import_sets_coordinator_pending_fields(db_session
coord = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
)
).scalar_one()
assert coord.vendor == "TI"
@@ -432,10 +432,10 @@ async def test_persist_pending_import_backfills_inventory_for_approved_node(
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
# Simulate: router was approved earlier → exists as a canvas Node, but with
- # no matching pending_devices row (e.g. a legacy auto-placed device).
+ # no matching device_inventory row (e.g. a legacy auto-placed device).
approved = Node(
label="router_1",
type="zigbee_router",
@@ -455,7 +455,7 @@ async def test_persist_pending_import_backfills_inventory_for_approved_node(
# An inventory row is backfilled as "approved" (it is on a canvas).
inv = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
)
).scalar_one()
assert inv.status == "approved"
@@ -481,13 +481,13 @@ async def test_persist_pending_import_preserves_hidden_inventory_for_approved_no
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
db_session.add(Node(
label="router_1", type="zigbee_router", status="online",
check_method="none", ieee_address="0xR1", services=[], properties=[],
))
- db_session.add(PendingDevice(
+ db_session.add(InventoryDevice(
ieee_address="0xR1", friendly_name="router_1", suggested_type="zigbee_router",
device_subtype="Router", status="hidden", discovery_source="zigbee",
))
@@ -497,7 +497,7 @@ async def test_persist_pending_import_preserves_hidden_inventory_for_approved_no
inv = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
)
).scalar_one()
assert inv.status == "hidden" # stays hidden
@@ -509,7 +509,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
) -> None:
"""Regression for #167: approve → delete node → re-import must re-list device.
- When a device was approved (PendingDevice.status="approved") and its canvas
+ When a device was approved (InventoryDevice.status="approved") and its canvas
Node was later deleted, the orphaned "approved" row must be reset to
"pending" on re-import so it shows up in the Pending list again — instead of
being silently swallowed (re-import reports "found" but Pending stays empty).
@@ -517,11 +517,11 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
- # Simulate prior approve: a PendingDevice marked approved, but NO matching
+ # Simulate prior approve: a InventoryDevice marked approved, but NO matching
# Node exists (the user deleted the canvas node afterwards).
- orphan = PendingDevice(
+ orphan = InventoryDevice(
ieee_address="0xR1",
friendly_name="router_1",
hostname="router_1",
@@ -541,7 +541,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
# No new row created for 0xR1 — the existing one was updated/revived.
revived = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
)
).scalar_one()
assert revived.status == "pending"
@@ -552,7 +552,7 @@ async def test_persist_pending_import_revives_orphaned_approved_device(
# It is now visible to the Pending list (status filter == "pending").
listed = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.status == "pending")
+ select(InventoryDevice).where(InventoryDevice.status == "pending")
)
).scalars().all()
assert {p.ieee_address for p in listed} == {"0xCOORD", "0xR1", "0xE1"}
@@ -566,9 +566,9 @@ async def test_persist_pending_import_keeps_hidden_hidden_on_reimport(
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
- hidden = PendingDevice(
+ hidden = InventoryDevice(
ieee_address="0xR1",
friendly_name="router_1",
suggested_type="zigbee_router",
@@ -583,7 +583,7 @@ async def test_persist_pending_import_keeps_hidden_hidden_on_reimport(
still_hidden = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xR1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xR1")
)
).scalar_one()
assert still_hidden.status == "hidden"
@@ -644,9 +644,9 @@ async def test_persist_pending_import_refreshes_approved_coordinator_node(
from sqlalchemy import select
from app.api.routes.zigbee import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
- # Legacy: coordinator auto-placed as a canvas Node, no pending_devices row.
+ # Legacy: coordinator auto-placed as a canvas Node, no device_inventory row.
db_session.add(Node(
label="Coordinator", type="zigbee_coordinator", status="online",
check_method="none", ieee_address="0xCOORD", services=[], properties=[],
@@ -669,7 +669,7 @@ async def test_persist_pending_import_refreshes_approved_coordinator_node(
# Inventory row backfilled as approved → now visible in the inventory list.
inv = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "0xCOORD")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0xCOORD")
)
).scalar_one()
assert inv.status == "approved"
diff --git a/backend/tests/test_zwave_router.py b/backend/tests/test_zwave_router.py
index 506dd55..c26c866 100644
--- a/backend/tests/test_zwave_router.py
+++ b/backend/tests/test_zwave_router.py
@@ -294,7 +294,7 @@ async def test_persist_coordinator_goes_to_pending(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
assert result.device_count == 3
@@ -308,7 +308,7 @@ async def test_persist_coordinator_goes_to_pending(db_session) -> None:
assert nodes == []
coord = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-1")
)
).scalar_one()
assert coord.status == "pending"
@@ -333,12 +333,12 @@ async def test_persist_replaces_links(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import PendingDeviceLink
+ from app.db.models import InventoryDeviceLink
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
new_edges = [{"source": "zwave-0xh-1", "target": "zwave-0xh-2"}]
await _persist_pending_import(db_session, _PENDING_NODES[:2], new_edges)
- rows = (await db_session.execute(select(PendingDeviceLink))).scalars().all()
+ rows = (await db_session.execute(select(InventoryDeviceLink))).scalars().all()
assert len(rows) == 1
assert (rows[0].source_ieee, rows[0].target_ieee) == ("zwave-0xh-1", "zwave-0xh-2")
@@ -349,7 +349,7 @@ async def test_persist_sets_coordinator_pending_fields(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
nodes = [dict(n) for n in _PENDING_NODES]
nodes[0]["vendor"] = "Aeotec"
@@ -357,7 +357,7 @@ async def test_persist_sets_coordinator_pending_fields(db_session) -> None:
await _persist_pending_import(db_session, nodes, _PENDING_EDGES)
coord = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-1")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-1")
)
).scalar_one()
assert coord.vendor == "Aeotec"
@@ -372,7 +372,7 @@ async def test_persist_backfills_inventory_for_approved_node(db_session) -> None
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import Node, PendingDevice
+ from app.db.models import InventoryDevice, Node
approved = Node(
label="Wall Plug",
@@ -390,7 +390,7 @@ async def test_persist_backfills_inventory_for_approved_node(db_session) -> None
inv = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
)
).scalar_one()
assert inv.status == "approved"
@@ -407,9 +407,9 @@ async def test_persist_revives_orphaned_approved_device(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
- orphan = PendingDevice(
+ orphan = InventoryDevice(
ieee_address="zwave-0xh-2",
friendly_name="Wall Plug",
suggested_type="zwave_router",
@@ -423,7 +423,7 @@ async def test_persist_revives_orphaned_approved_device(db_session) -> None:
result = await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
revived = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
)
).scalar_one()
assert revived.status == "pending"
@@ -437,9 +437,9 @@ async def test_persist_keeps_hidden_hidden(db_session) -> None:
from sqlalchemy import select
from app.api.routes.zwave import _persist_pending_import
- from app.db.models import PendingDevice
+ from app.db.models import InventoryDevice
- hidden = PendingDevice(
+ hidden = InventoryDevice(
ieee_address="zwave-0xh-2",
friendly_name="Wall Plug",
suggested_type="zwave_router",
@@ -453,7 +453,7 @@ async def test_persist_keeps_hidden_hidden(db_session) -> None:
await _persist_pending_import(db_session, _PENDING_NODES, _PENDING_EDGES)
still_hidden = (
await db_session.execute(
- select(PendingDevice).where(PendingDevice.ieee_address == "zwave-0xh-2")
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "zwave-0xh-2")
)
).scalar_one()
assert still_hidden.status == "hidden"
diff --git a/docs/rack-canvas.md b/docs/rack-canvas.md
index 8fc8786..07ffdf6 100644
--- a/docs/rack-canvas.md
+++ b/docs/rack-canvas.md
@@ -91,16 +91,27 @@ Then set:
click only selects it. **Unmount** takes the device out of the rack — it stays in
the Device Inventory.
-### Logical view 🔒
-
-Under the port list, a mount that stands for a real device prints what the
-logical canvas already knows about the same box: canvas name, type, hostname,
-IP, MAC, OS, the status check it runs, the canvas it is drawn on, when it was
-last seen, and the services discovery fingerprinted on it.
-
-It is read-only — edit those facts on the logical canvas, not in the rack. A
-device that is on no logical canvas still shows whatever discovery reported, and
-an accessory shows nothing at all.
+### Linked device 🔒
+
+Under the port list, a mount that stands for a real device prints what is known
+about that box: name, type, hostname, IP, MAC, OS, the status check it runs, the
+canvas it is drawn on, when it was last seen, and the services discovery
+fingerprinted on it.
+
+It is read-only — edit those facts in the Device Inventory or on the logical
+canvas, not in the rack — and an accessory shows nothing at all. A device that is
+on no diagram still prints everything discovery found about it; only the
+canvas-side lines go missing, and the panel says *Not on a logical canvas.*
+
+**Link to another device…** points the plate at a different Device Inventory
+entry — the whole inventory, not just the devices you approved onto a diagram.
+Use it when you created the gear from the rack (the entry starts empty, with just
+a name) or when the plate ended up on the wrong twin of two look-alike hosts. The
+plate takes the entry's IP, MAC, services, status and — unless you renamed it —
+its name, **Check device** becomes available if that device is on a diagram, and
+the link is saved with the rest of the canvas. A device already mounted elsewhere
+in the design is not offered: one entry, one plate. The empty placeholder the
+rack created for the plate is removed from the inventory once nothing uses it.
### Placement rules
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 61bfc99..85fcaa7 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -32,7 +32,7 @@ import { TextModal, type TextFormData } from '@/components/modals/TextModal'
import { ThemeModal } from '@/components/modals/ThemeModal'
import { CustomStyleModal } from '@/components/modals/CustomStyleModal'
import { SearchModal } from '@/components/modals/SearchModal'
-import { PendingDevicesModal } from '@/components/modals/PendingDevicesModal'
+import { DeviceInventoryModal } from '@/components/modals/DeviceInventoryModal'
import { ScanHistoryModal } from '@/components/modals/ScanHistoryModal'
import { ShortcutsModal } from '@/components/modals/ShortcutsModal'
import { ConfirmAddToGroupModal } from '@/components/modals/ConfirmAddToGroupModal'
@@ -49,7 +49,7 @@ import { decideCanvasLoad, isNewUserCanvas } from '@/utils/canvasLoadDecision'
import { WalkthroughActionsProvider, type WalkthroughActionApi } from '@/walkthrough/actions'
import { WalkthroughInvite } from '@/walkthrough/WalkthroughInvite'
import { WalkthroughOverlay } from '@/walkthrough/WalkthroughOverlay'
-import { DEMO_SCAN_RUNS, DEMO_PENDING_DEVICES } from '@/walkthrough/demoTourData'
+import { DEMO_SCAN_RUNS, DEMO_INVENTORY_DEVICES } from '@/walkthrough/demoTourData'
import { useStatusPolling } from '@/hooks/useStatusPolling'
import { bootstrapAuth } from '@/auth/bootstrap'
import { RackCanvas } from '@/rack/components/RackCanvas'
@@ -116,14 +116,14 @@ export default function App() {
const [styleEditorType, setStyleEditorType] = useState<NodeType | null>(null)
const [searchOpen, setSearchOpen] = useState(false)
const [scanHistoryOpen, setScanHistoryOpen] = useState(false)
- const [pendingModalOpen, setPendingModalOpen] = useState(false)
- const [pendingModalStatus, setPendingModalStatus] = useState<'pending' | 'hidden'>('pending')
- const [pendingHighlightId, setPendingHighlightId] = useState<string | undefined>(undefined)
- const openPendingModal = useCallback((deviceId?: string, status: 'pending' | 'hidden' = 'pending') => {
- setPendingHighlightId(undefined)
- setPendingModalStatus(status)
- setPendingModalOpen(true)
- if (deviceId) setTimeout(() => setPendingHighlightId(deviceId), 0)
+ const [inventoryModalOpen, setInventoryModalOpen] = useState(false)
+ const [inventoryModalStatus, setInventoryModalStatus] = useState<'pending' | 'hidden'>('pending')
+ const [inventoryHighlightId, setInventoryHighlightId] = useState<string | undefined>(undefined)
+ const openInventoryModal = useCallback((deviceId?: string, status: 'pending' | 'hidden' = 'pending') => {
+ setInventoryHighlightId(undefined)
+ setInventoryModalStatus(status)
+ setInventoryModalOpen(true)
+ if (deviceId) setTimeout(() => setInventoryHighlightId(deviceId), 0)
}, [])
const [shortcutsOpen, setShortcutsOpen] = useState(false)
const [addNodeOpen, setAddNodeOpen] = useState(false)
@@ -352,7 +352,7 @@ export default function App() {
setScanConfigOpen(false)
setScanHistoryOpen(false)
setTourScanHistoryDemo(false)
- setPendingModalOpen(false)
+ setInventoryModalOpen(false)
setTourInventoryDemo(false)
setEditNodeId(null)
setThemeModalOpen(false)
@@ -371,7 +371,7 @@ export default function App() {
},
openInventoryDemo: () => {
setTourInventoryDemo(true)
- openPendingModal(undefined, 'pending')
+ openInventoryModal(undefined, 'pending')
},
editFirstNode: () => {
const first = useCanvasStore.getState().nodes.find((n) => n.data.type !== 'groupRect' && n.data.type !== 'text')
@@ -392,7 +392,7 @@ export default function App() {
},
openStyle: () => setThemeModalOpen(true),
openZigbeeImport: () => setZigbeeImportOpen(true),
- }), [openPendingModal])
+ }), [openInventoryModal])
// Load designs + canvas on auth (or immediately in standalone mode, which has
// no auth gate).
@@ -1005,7 +1005,7 @@ export default function App() {
onSave={handleSave}
onOpenSettings={() => setSettingsOpen(true)}
onOpenHistory={() => setScanHistoryOpen(true)}
- onOpenPending={openPendingModal}
+ onOpenInventory={openInventoryModal}
/>
<div className="flex flex-col flex-1 min-w-0">
{loadError && (
@@ -1048,7 +1048,7 @@ export default function App() {
onNodeDragStart={snapshotHistory}
onRequestAddToGroup={setPendingGroupAdd}
onRequestAddToContainer={setPendingContainerAdd}
- onOpenPending={(deviceId) => openPendingModal(deviceId)}
+ onOpenInventory={(deviceId) => openInventoryModal(deviceId)}
/>
)}
</div>
@@ -1137,7 +1137,7 @@ export default function App() {
open={zigbeeImportOpen}
onClose={() => setZigbeeImportOpen(false)}
onAddToCanvas={handleZigbeeAddToCanvas}
- onPendingImported={() => {
+ onInventoryImported={() => {
toast.success('Zigbee import started — check Scan History for results')
}}
/>
@@ -1148,7 +1148,7 @@ export default function App() {
open={zwaveImportOpen}
onClose={() => setZwaveImportOpen(false)}
onAddToCanvas={handleZwaveAddToCanvas}
- onPendingImported={() => {
+ onInventoryImported={() => {
toast.success('Z-Wave import started — check Scan History for results')
}}
/>
@@ -1159,7 +1159,7 @@ export default function App() {
open={proxmoxImportOpen}
onClose={() => setProxmoxImportOpen(false)}
onAddToCanvas={handleProxmoxAddToCanvas}
- onPendingImported={() => {
+ onInventoryImported={() => {
toast.success('Proxmox import started — check Scan History for results')
}}
/>
@@ -1258,7 +1258,7 @@ export default function App() {
<SearchModal
open={searchOpen}
onClose={() => setSearchOpen(false)}
- onOpenPending={(deviceId) => openPendingModal(deviceId)}
+ onOpenInventory={(deviceId) => openInventoryModal(deviceId)}
/>
<ShortcutsModal open={shortcutsOpen} onClose={() => setShortcutsOpen(false)} />
@@ -1289,12 +1289,12 @@ export default function App() {
but canvas prefs (snap, hide-IP) still apply. */}
<SettingsModal open={settingsOpen} onClose={() => setSettingsOpen(false)} />
- <PendingDevicesModal
- open={pendingModalOpen}
- onClose={() => setPendingModalOpen(false)}
- highlightId={pendingHighlightId}
- initialStatus={pendingModalStatus}
- demoDevices={tourInventoryDemo ? DEMO_PENDING_DEVICES : undefined}
+ <DeviceInventoryModal
+ open={inventoryModalOpen}
+ onClose={() => setInventoryModalOpen(false)}
+ highlightId={inventoryHighlightId}
+ initialStatus={inventoryModalStatus}
+ demoDevices={tourInventoryDemo ? DEMO_INVENTORY_DEVICES : undefined}
/>
<ExportModal
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index feb271f..f241700 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -61,7 +61,29 @@ export const mediaApi = {
delete: (filename: string) => api.delete(`/media/${filename}`),
}
+/**
+ * A canvas node as `GET /nodes` reports it — the fields a reader needs to tell
+ * two hosts apart. The canvas itself keeps its own richer React Flow shape; this
+ * is only for pickers and lookups.
+ */
+export interface ApiCanvasNode {
+ id: string
+ design_id: string | null
+ label: string
+ type: string
+ ip: string | null
+ mac: string | null
+ hostname: string | null
+ os: string | null
+ status: string
+ check_method: string | null
+ last_seen: string | null
+}
+
export const nodesApi = {
+ /** Every node, across every design. `label` filters case-insensitively. */
+ list: (label?: string) =>
+ api.get<ApiCanvasNode[]>('/nodes', { params: label ? { label } : {} }),
create: (data: object) => api.post('/nodes', data),
update: (id: string, data: object) => api.patch(`/nodes/${id}`, data),
delete: (id: string) => api.delete(`/nodes/${id}`),
@@ -106,6 +128,14 @@ export interface DuplicateNodeConflict {
value: string
}
+/**
+ * The Device Inventory rides the scan routes.
+ *
+ * `/scan/pending/*` is what the table was called when it was a queue of finds
+ * awaiting approval; the rows are the Device Inventory now, but the paths are a
+ * published contract the MCP server also calls, so they stay. The method names
+ * follow the paths rather than the concept, so a route is easy to find.
+ */
export const scanApi = {
trigger: (deepScan?: Partial<DeepScanConfig>) => api.post('/scan/trigger', deepScan ?? {}),
pending: () => api.get('/scan/pending'),
@@ -123,6 +153,8 @@ export const scanApi = {
hidden: () => api.get('/scan/hidden'),
runs: () => api.get('/scan/runs'),
clearPending: () => api.delete('/scan/pending'),
+ /** Remove one inventory entry. 409 when a rack still mounts it. */
+ deletePending: (id: string) => api.delete<{ deleted: boolean }>(`/scan/pending/${id}`),
approve: (id: string, nodeData: object) =>
api.post<{
approved: boolean
diff --git a/frontend/src/components/canvas/CanvasContainer.tsx b/frontend/src/components/canvas/CanvasContainer.tsx
index 3f8b91e..5fb2b36 100644
--- a/frontend/src/components/canvas/CanvasContainer.tsx
+++ b/frontend/src/components/canvas/CanvasContainer.tsx
@@ -34,10 +34,10 @@ interface CanvasContainerProps {
onNodeDragStart?: () => void
onRequestAddToGroup?: (payload: { nodeId: string; groupId: string }) => void
onRequestAddToContainer?: (payload: { nodeId: string; containerId: string }) => void
- onOpenPending?: (deviceId: string) => void
+ onOpenInventory?: (deviceId: string) => void
}
-export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onOpenPending }: CanvasContainerProps) {
+export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, onNodeDoubleClick, onNodeDragStart, onRequestAddToGroup, onRequestAddToContainer, onOpenInventory }: CanvasContainerProps) {
const [lassoMode, setLassoMode] = useState(true)
const {
nodes, edges,
@@ -202,7 +202,7 @@ export function CanvasContainer({ onConnect: onConnectProp, onEdgeDoubleClick, o
color={theme.colors.canvasDotColor}
/>
<FloorMapLayer />
- <SearchBar onOpenPending={onOpenPending} />
+ <SearchBar onOpenInventory={onOpenInventory} />
<AlignmentGuides guides={guides} />
<Controls>
<ControlButton
diff --git a/frontend/src/components/canvas/SearchBar.tsx b/frontend/src/components/canvas/SearchBar.tsx
index 5eab347..4e70d5a 100644
--- a/frontend/src/components/canvas/SearchBar.tsx
+++ b/frontend/src/components/canvas/SearchBar.tsx
@@ -4,23 +4,23 @@ import { Search, X } from 'lucide-react'
import { useCanvasStore } from '@/stores/canvasStore'
import { scanApi } from '@/api/client'
import { NODE_TYPE_LABELS } from '@/types'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
interface SearchBarProps {
- onOpenPending?: (deviceId: string) => void
+ onOpenInventory?: (deviceId: string) => void
}
-export function SearchBar({ onOpenPending }: SearchBarProps) {
+export function SearchBar({ onOpenInventory }: SearchBarProps) {
const [open, setOpen] = useState(false)
const [query, setQuery] = useState('')
- const [pendingDevices, setPendingDevices] = useState<PendingDevice[]>([])
+ const [inventoryDevices, setInventoryEntrys] = useState<InventoryEntry[]>([])
const inputRef = useRef<HTMLInputElement>(null)
const { nodes, setSelectedNode } = useCanvasStore()
const { setCenter } = useReactFlow()
useEffect(() => {
if (!open) return
- scanApi.pending().then((res) => setPendingDevices(res.data)).catch(() => {})
+ scanApi.pending().then((res) => setInventoryEntrys(res.data)).catch(() => {})
}, [open])
useEffect(() => {
@@ -86,7 +86,7 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
: []
const pendingResults = q
- ? pendingDevices.filter((d) =>
+ ? inventoryDevices.filter((d) =>
d.ip?.toLowerCase().includes(q) ||
d.hostname?.toLowerCase().includes(q) ||
d.friendly_name?.toLowerCase().includes(q) ||
@@ -215,7 +215,7 @@ export function SearchBar({ onOpenPending }: SearchBarProps) {
return (
<button
key={d.id}
- onClick={() => { onOpenPending?.(d.id); setOpen(false); setQuery('') }}
+ onClick={() => { onOpenInventory?.(d.id); setOpen(false); setQuery('') }}
style={{
width: '100%',
display: 'flex',
diff --git a/frontend/src/components/modals/PendingDevicesModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsx
similarity index 97%
rename from frontend/src/components/modals/PendingDevicesModal.tsx
rename to frontend/src/components/modals/DeviceInventoryModal.tsx
index ccf9984..e3314ba 100644
--- a/frontend/src/components/modals/PendingDevicesModal.tsx
+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx
@@ -10,7 +10,7 @@ import { useDesignStore } from '@/stores/designStore'
import { useThemeStore } from '@/stores/themeStore'
import { resolveNodeColors } from '@/utils/nodeColors'
import { toast } from 'sonner'
-import { PendingDeviceModal, type PendingDevice } from '@/components/modals/PendingDeviceModal'
+import { InventoryDeviceModal, type InventoryEntry } from '@/components/modals/InventoryDeviceModal'
import type { NodeType, ServiceInfo } from '@/types'
import { applyAutoEdges, type AutoEdge } from '@/utils/autoEdges'
import { buildZigbeeProperties, isZigbeeType } from '@/utils/zigbeeProperties'
@@ -18,22 +18,22 @@ import { buildZwaveProperties, isZwaveType } from '@/utils/zwaveProperties'
import { buildMacProperty } from '@/utils/macProperty'
import { formatRelative, formatTimestamp } from '@/utils/timeFormat'
import { getCenteredPosition } from '@/utils/viewportCenter'
-import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/pendingSources'
+import { sourceBuckets, orderedSources, isRackDevice, SOURCE_META, type SourceBucket } from '@/utils/deviceSources'
import { isRackable } from '@/utils/rackable'
-interface PendingDevicesModalProps {
+interface DeviceInventoryModalProps {
open: boolean
onClose: () => void
highlightId?: string
initialStatus?: 'pending' | 'hidden'
/** Getting Started tour: render these canned devices and skip the backend fetch. */
- demoDevices?: PendingDevice[]
+ demoDevices?: InventoryEntry[]
/**
* Picker mode. Clicking a card hands the device back instead of opening its
* detail modal, so another feature (the rack canvas) can reuse this list —
* search, filters, badges and all — rather than reimplementing a `<select>`.
*/
- onPick?: (device: PendingDevice) => void
+ onPick?: (device: InventoryEntry) => void
/** Start with the Rackable filter on (what the rack picker wants). */
initialRackableOnly?: boolean
}
@@ -91,7 +91,7 @@ type StatusFilter = 'pending' | 'hidden'
const COMMON_PORTS = new Set([22, 80, 443])
-function specialServiceName(d: PendingDevice): string | undefined {
+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,
)
@@ -100,7 +100,7 @@ function specialServiceName(d: PendingDevice): string | undefined {
return (nonWeb ?? candidates[0])?.service_name ?? undefined
}
-function deviceLabel(d: PendingDevice): string {
+function deviceLabel(d: InventoryEntry): string {
return d.friendly_name ?? d.hostname ?? specialServiceName(d) ?? d.ip ?? d.ieee_address ?? 'device'
}
@@ -124,10 +124,10 @@ function injectAutoEdges(edges: AutoEdge[] | undefined) {
}))
}
-export function PendingDevicesModal({ open, onClose, highlightId, initialStatus = 'pending', demoDevices, onPick, initialRackableOnly = false }: PendingDevicesModalProps) {
- const [devices, setDevices] = useState<PendingDevice[]>([])
+export function DeviceInventoryModal({ open, onClose, highlightId, initialStatus = 'pending', demoDevices, onPick, initialRackableOnly = false }: DeviceInventoryModalProps) {
+ const [devices, setDevices] = useState<InventoryEntry[]>([])
const [loading, setLoading] = useState(false)
- const [selected, setSelected] = useState<PendingDevice | null>(null)
+ const [selected, setSelected] = useState<InventoryEntry | null>(null)
const [selectMode, setSelectMode] = useState(false)
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set())
const [search, setSearch] = useState('')
@@ -147,7 +147,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
const highlightRef = useRef<HTMLButtonElement>(null)
// Set when a single approve is refused because the same host is already on
// this design — the user decides: link to the existing node or duplicate.
- const [dupPrompt, setDupPrompt] = useState<{ device: PendingDevice; conflict: DuplicateNodeConflict } | null>(null)
+ const [dupPrompt, setDupPrompt] = useState<{ device: InventoryEntry; conflict: DuplicateNodeConflict } | null>(null)
const load = useCallback(async () => {
// Tour/demo mode: show injected devices, never touch the backend.
@@ -219,7 +219,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
})
}
- const handleCardClick = (d: PendingDevice) => {
+ const handleCardClick = (d: InventoryEntry) => {
// Picker mode wins over everything else: the caller opened this list to get
// one device back, not to approve or hide anything.
if (onPick) { onPick(d); return }
@@ -228,7 +228,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
setSelected(d)
}
- const handleRestore = async (device: PendingDevice) => {
+ const handleRestore = async (device: InventoryEntry) => {
try {
await scanApi.restore(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
@@ -294,7 +294,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
// force=true is sent only after the user confirms they want a duplicate node
// on this design (the backend otherwise 409s to let us ask).
- const approveDevice = async (device: PendingDevice, force = false) => {
+ const approveDevice = async (device: InventoryEntry, force = false) => {
// Rack gear documents a mount, not a host: it stays out of logical canvases.
// The backend refuses it too — this is the friendly half of the guard.
if (isRackDevice(device)) {
@@ -354,7 +354,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
}
- const handleApprove = (device: PendingDevice) => approveDevice(device, false)
+ const handleApprove = (device: InventoryEntry) => approveDevice(device, false)
const goToExistingNode = (nodeId: string) => {
setSelectedNode(nodeId)
@@ -363,7 +363,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
onClose()
}
- const handleHide = async (device: PendingDevice) => {
+ const handleHide = async (device: InventoryEntry) => {
try {
await scanApi.hide(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
@@ -374,7 +374,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
}
- const handleIgnore = async (device: PendingDevice) => {
+ const handleIgnore = async (device: InventoryEntry) => {
try {
await scanApi.ignore(device.id)
setDevices((prev) => prev.filter((d) => d.id !== device.id))
@@ -792,7 +792,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
</DialogContent>
</Dialog>
- <PendingDeviceModal
+ <InventoryDeviceModal
device={selected}
onClose={() => setSelected(null)}
onApprove={handleApprove}
@@ -804,7 +804,7 @@ export function PendingDevicesModal({ open, onClose, highlightId, initialStatus
}
interface DeviceCardProps {
- device: PendingDevice
+ device: InventoryEntry
selected: boolean
selectMode: boolean
highlighted: boolean
diff --git a/frontend/src/components/modals/PendingDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsx
similarity index 95%
rename from frontend/src/components/modals/PendingDeviceModal.tsx
rename to frontend/src/components/modals/InventoryDeviceModal.tsx
index 1ea10b3..bedb034 100644
--- a/frontend/src/components/modals/PendingDeviceModal.tsx
+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx
@@ -1,7 +1,7 @@
import { Globe, Router, Server, Layers, Box, Container, HardDrive, Cpu, Wifi, Circle, Network } from 'lucide-react'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
-import { isRackDevice } from '@/utils/pendingSources'
+import { isRackDevice } from '@/utils/deviceSources'
import type { NodeProperty } from '@/types'
interface Service {
@@ -12,7 +12,7 @@ interface Service {
category?: string | null
}
-export interface PendingDevice {
+export interface InventoryEntry {
id: string
ip: string | null
mac: string | null
@@ -45,12 +45,12 @@ export interface PendingDevice {
node_last_seen?: string | null
}
-interface PendingDeviceModalProps {
- device: PendingDevice | null
+interface InventoryDeviceModalProps {
+ device: InventoryEntry | null
onClose: () => void
- onApprove: (device: PendingDevice) => void
- onHide: (device: PendingDevice) => void
- onIgnore: (device: PendingDevice) => void
+ onApprove: (device: InventoryEntry) => void
+ onHide: (device: InventoryEntry) => void
+ onIgnore: (device: InventoryEntry) => void
}
const TYPE_ICONS: Record<string, React.ElementType> = {
@@ -95,7 +95,7 @@ function InfoRow({ label, value }: { label: string; value: string }) {
)
}
-export function PendingDeviceModal({ device, onClose, onApprove, onHide, onIgnore }: PendingDeviceModalProps) {
+export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore }: InventoryDeviceModalProps) {
if (!device) return null
const TypeIcon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle
diff --git a/frontend/src/components/modals/SearchModal.tsx b/frontend/src/components/modals/SearchModal.tsx
index 630a22d..60f1b77 100644
--- a/frontend/src/components/modals/SearchModal.tsx
+++ b/frontend/src/components/modals/SearchModal.tsx
@@ -3,24 +3,24 @@ import { useReactFlow } from '@xyflow/react'
import { Search } from 'lucide-react'
import { useCanvasStore } from '@/stores/canvasStore'
import { scanApi } from '@/api/client'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
interface SearchModalProps {
open: boolean
onClose: () => void
- onOpenPending: (deviceId: string) => void
+ onOpenInventory: (deviceId: string) => void
}
-export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps) {
+export function SearchModal({ open, onClose, onOpenInventory }: SearchModalProps) {
const [query, setQuery] = useState('')
- const [pendingDevices, setPendingDevices] = useState<PendingDevice[]>([])
+ const [inventoryDevices, setInventoryEntrys] = useState<InventoryEntry[]>([])
const nodes = useCanvasStore((s) => s.nodes)
const setSelectedNode = useCanvasStore((s) => s.setSelectedNode)
const { fitView } = useReactFlow()
useEffect(() => {
if (!open) return
- scanApi.pending().then((res) => setPendingDevices(res.data)).catch(() => {})
+ scanApi.pending().then((res) => setInventoryEntrys(res.data)).catch(() => {})
}, [open])
const searchable = nodes.filter((n) => n.data.type !== 'groupRect')
@@ -32,7 +32,7 @@ export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps)
n.data.hostname?.toLowerCase().includes(q)
).slice(0, 6)
- const pendingResults = q.length === 0 ? [] : pendingDevices.filter((d) =>
+ const pendingResults = q.length === 0 ? [] : inventoryDevices.filter((d) =>
d.ip?.toLowerCase().includes(q) ||
d.hostname?.toLowerCase().includes(q) ||
d.friendly_name?.toLowerCase().includes(q) ||
@@ -52,11 +52,11 @@ export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps)
setQuery('')
}, [fitView, setSelectedNode, onClose])
- const handleSelectPending = useCallback((deviceId: string) => {
- onOpenPending(deviceId)
+ const handleSelectInventoryDevice = useCallback((deviceId: string) => {
+ onOpenInventory(deviceId)
onClose()
setQuery('')
- }, [onOpenPending, onClose])
+ }, [onOpenInventory, onClose])
if (!open) return null
@@ -77,7 +77,7 @@ export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps)
onKeyDown={(e) => {
if (e.key === 'Escape') { onClose(); setQuery('') }
if (e.key === 'Enter' && nodeResults.length > 0) handleSelectNode(nodeResults[0].id)
- if (e.key === 'Enter' && nodeResults.length === 0 && pendingResults.length > 0) handleSelectPending(pendingResults[0].id)
+ if (e.key === 'Enter' && nodeResults.length === 0 && pendingResults.length > 0) handleSelectInventoryDevice(pendingResults[0].id)
}}
/>
<kbd className="text-[10px] text-muted-foreground border border-border rounded px-1">ESC</kbd>
@@ -109,7 +109,7 @@ export function SearchModal({ open, onClose, onOpenPending }: SearchModalProps)
<li
key={device.id}
className="flex items-center gap-3 px-4 py-2 hover:bg-[#21262d] cursor-pointer"
- onClick={() => handleSelectPending(device.id)}
+ onClick={() => handleSelectInventoryDevice(device.id)}
>
<span className="text-xs font-mono text-[#e3b341] w-16 shrink-0">pending</span>
<span className="text-sm text-foreground font-medium flex-1 truncate font-mono">{device.hostname ?? device.ip}</span>
diff --git a/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
similarity index 90%
rename from frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx
rename to frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
index 93c597c..8b4df5c 100644
--- a/frontend/src/components/modals/__tests__/PendingDevicesModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'
-import { PendingDevicesModal } from '../PendingDevicesModal'
+import { DeviceInventoryModal } from '../DeviceInventoryModal'
import { useCanvasStore } from '@/stores/canvasStore'
vi.mock('@/stores/canvasStore')
@@ -33,8 +33,8 @@ vi.mock('@/api/client', () => ({
vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
-vi.mock('@/components/modals/PendingDeviceModal', () => ({
- PendingDeviceModal: ({ device, onApprove }: { device: unknown; onApprove: (d: unknown) => void }) =>
+vi.mock('@/components/modals/InventoryDeviceModal', () => ({
+ InventoryDeviceModal: ({ device, onApprove }: { device: unknown; onApprove: (d: unknown) => void }) =>
device ? (
<div data-testid="approval-modal">
<button data-testid="do-approve" onClick={() => onApprove(device)}>approve</button>
@@ -161,29 +161,29 @@ const baseProps = {
onClose: vi.fn(),
}
-describe('PendingDevicesModal', () => {
+describe('DeviceInventoryModal', () => {
it('loads and renders pending devices on open', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('living-room-bulb')).toBeInTheDocument()
})
it('closes via the X button (routes through DialogClose, not a raw onClick)', async () => {
const onClose = vi.fn()
- render(<PendingDevicesModal open onClose={onClose} />)
+ render(<DeviceInventoryModal open onClose={onClose} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Close' }))
expect(onClose).toHaveBeenCalledTimes(1)
})
it('shows source chip ZIGBEE for zigbee device', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('ZIGBEE')).toBeInTheDocument()
})
it('filters by search query', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: 'living' } })
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
@@ -191,7 +191,7 @@ describe('PendingDevicesModal', () => {
})
it('filters by source (zigbee only)', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Zigbee' }))
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
@@ -200,14 +200,14 @@ describe('PendingDevicesModal', () => {
it('shows source chip Z-WAVE for zwave device', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_IP, DEVICE_ZWAVE] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-c')).toBeInTheDocument())
expect(screen.getByText('Z-WAVE')).toBeInTheDocument()
})
it('colours the role badge with the node-type accent, not flat grey', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_ZWAVE] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
const card = await waitFor(() => screen.getByTestId('pending-card-dev-c'))
// zwave_router accent from the default theme = #e3b341 (amber), applied to
// both the text colour and a translucent background.
@@ -219,7 +219,7 @@ describe('PendingDevicesModal', () => {
it('filters by source (zwave only)', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_IP, DEVICE_ZWAVE] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Z-Wave' }))
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
@@ -228,7 +228,7 @@ describe('PendingDevicesModal', () => {
it('shows source chip PROXMOX for a proxmox device (not zigbee despite ieee)', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_PROXMOX] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-d')).toBeInTheDocument())
expect(screen.getByText('PROXMOX')).toBeInTheDocument()
expect(screen.queryByText('ZIGBEE')).not.toBeInTheDocument()
@@ -236,7 +236,7 @@ describe('PendingDevicesModal', () => {
it('filters by source (proxmox only)', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_IP, DEVICE_PROXMOX] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Proxmox' }))
expect(screen.queryByTestId('pending-card-dev-a')).not.toBeInTheDocument()
@@ -244,7 +244,7 @@ describe('PendingDevicesModal', () => {
})
it('filters by suggested type', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.change(screen.getByLabelText('Type filter'), { target: { value: 'server' } })
expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
@@ -255,7 +255,7 @@ describe('PendingDevicesModal', () => {
mockHidden.mockResolvedValue({
data: [{ ...DEVICE_IP, id: 'h1', hostname: 'hidden-host', status: 'hidden' }],
})
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Hidden' }))
await waitFor(() => expect(screen.getByTestId('pending-card-h1')).toBeInTheDocument())
@@ -263,7 +263,7 @@ describe('PendingDevicesModal', () => {
})
it('opens approval modal when card is clicked outside select mode', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
expect(screen.getByTestId('approval-modal')).toBeInTheDocument()
@@ -286,7 +286,7 @@ describe('PendingDevicesModal', () => {
it('single approve prompts instead of failing when the host is already on the design', async () => {
mockApprove.mockRejectedValueOnce(DUP_409)
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByTestId('do-approve'))
@@ -300,7 +300,7 @@ describe('PendingDevicesModal', () => {
it('"Add duplicate anyway" retries the approve with force=true', async () => {
mockApprove.mockRejectedValueOnce(DUP_409)
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByTestId('do-approve'))
@@ -313,7 +313,7 @@ describe('PendingDevicesModal', () => {
it('"Go to existing node" selects the existing node and closes the modal', async () => {
mockApprove.mockRejectedValueOnce(DUP_409)
const onClose = vi.fn()
- render(<PendingDevicesModal {...baseProps} onClose={onClose} />)
+ render(<DeviceInventoryModal {...baseProps} onClose={onClose} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
fireEvent.click(screen.getByTestId('do-approve'))
@@ -324,7 +324,7 @@ describe('PendingDevicesModal', () => {
})
it('toggles selection in select mode instead of opening approval', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -333,7 +333,7 @@ describe('PendingDevicesModal', () => {
})
it('select all visible selects only filtered devices', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.change(screen.getByPlaceholderText(/Search/), { target: { value: 'host-a' } })
@@ -342,7 +342,7 @@ describe('PendingDevicesModal', () => {
})
it('bulk approve calls API with selected ids', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -360,7 +360,7 @@ describe('PendingDevicesModal', () => {
skipped_devices: [{ device_id: 'dev-a', label: 'host-a', match: 'ip', value: '192.168.1.10', existing_node_id: 'n-existing' }],
},
})
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -382,7 +382,7 @@ describe('PendingDevicesModal', () => {
{ ...DEVICE_IP, canvas_count: 1 },
{ ...DEVICE_ZIGBEE, canvas_count: 1 },
] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -396,7 +396,7 @@ describe('PendingDevicesModal', () => {
})
it('bulk approve carries the scanned MAC onto the canvas node (#168)', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -424,7 +424,7 @@ describe('PendingDevicesModal', () => {
})
it('bulk hide calls API with selected ids', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -433,20 +433,20 @@ describe('PendingDevicesModal', () => {
})
it('does not load when closed', () => {
- render(<PendingDevicesModal {...baseProps} open={false} />)
+ render(<DeviceInventoryModal {...baseProps} open={false} />)
expect(mockPending).not.toHaveBeenCalled()
})
it('respects initialStatus=hidden', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, hostname: 'hidden-host', status: 'hidden' }] })
- render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
+ render(<DeviceInventoryModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(mockHidden).toHaveBeenCalled())
expect(mockPending).not.toHaveBeenCalled()
})
it('clicking a hidden card restores it instead of opening approval', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
- render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
+ render(<DeviceInventoryModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
await waitFor(() => expect(mockRestore).toHaveBeenCalledWith('dev-a'))
@@ -455,7 +455,7 @@ describe('PendingDevicesModal', () => {
it('bulk restore in hidden mode calls API with selected ids', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
- render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
+ render(<DeviceInventoryModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -464,7 +464,7 @@ describe('PendingDevicesModal', () => {
})
it('Enter confirms approve in pending select mode', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -475,7 +475,7 @@ describe('PendingDevicesModal', () => {
it('Enter restores (not approves) in hidden select mode', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
- render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
+ render(<DeviceInventoryModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -487,21 +487,21 @@ describe('PendingDevicesModal', () => {
// --- Device Inventory: rename, canvas badge, on-canvas filter ---
it('titles the pending view "Device Inventory"', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('Device Inventory')).toBeInTheDocument()
})
it('shows "Hidden Devices" title in hidden mode', async () => {
mockHidden.mockResolvedValue({ data: [{ ...DEVICE_IP, status: 'hidden' }] })
- render(<PendingDevicesModal {...baseProps} initialStatus="hidden" />)
+ render(<DeviceInventoryModal {...baseProps} initialStatus="hidden" />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByText('Hidden Devices')).toBeInTheDocument()
})
it('renders a corner canvas-count when canvas_count > 0', async () => {
mockPending.mockResolvedValue({ data: [{ ...DEVICE_IP, canvas_count: 2 }] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
const corner = screen.getByLabelText('On 2 canvases')
expect(corner).toHaveTextContent('2')
@@ -509,21 +509,21 @@ describe('PendingDevicesModal', () => {
it('uses singular "canvas" for a single canvas', async () => {
mockPending.mockResolvedValue({ data: [{ ...DEVICE_IP, canvas_count: 1 }] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.getByLabelText('On 1 canvas')).toHaveTextContent('1')
})
it('does not render the canvas-count corner when canvas_count is 0', async () => {
mockPending.mockResolvedValue({ data: [{ ...DEVICE_IP, canvas_count: 0 }] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.queryByLabelText(/On \d+ canvas/)).not.toBeInTheDocument()
})
it('filters to devices with detected services when "With services" is on', async () => {
// dev-a has an http service; dev-b (zigbee) has none.
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-b')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: /With services/ }))
expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
@@ -534,7 +534,7 @@ describe('PendingDevicesModal', () => {
mockPending.mockResolvedValue({
data: [DEVICE_IP, { ...DEVICE_ZIGBEE, canvas_count: 1 }],
})
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
// Default: both visible (on-canvas shown).
await waitFor(() => expect(screen.getByTestId('pending-card-dev-b')).toBeInTheDocument())
expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
@@ -556,7 +556,7 @@ describe('PendingDevicesModal', () => {
node_last_seen: '2026-06-25T09:15:00Z',
}],
})
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
const card = await screen.findByTestId('pending-card-dev-a')
const inCard = within(card)
expect(inCard.getByText('Created')).toBeInTheDocument()
@@ -569,7 +569,7 @@ describe('PendingDevicesModal', () => {
it('falls back to Discovered for devices not on any canvas', async () => {
mockPending.mockResolvedValue({ data: [DEVICE_IP] })
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
const card = await screen.findByTestId('pending-card-dev-a')
const inCard = within(card)
expect(inCard.getByText('Discovered')).toBeInTheDocument()
@@ -585,7 +585,7 @@ describe('PendingDevicesModal', () => {
})
it('filters them into their own section', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Rack devices' }))
expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument()
@@ -594,7 +594,7 @@ describe('PendingDevicesModal', () => {
it('refuses to approve one onto a logical canvas', async () => {
const { toast } = await import('sonner')
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-rack'))
fireEvent.click(screen.getByTestId('do-approve'))
@@ -605,7 +605,7 @@ describe('PendingDevicesModal', () => {
it('drops them from a bulk approve and says how many', async () => {
const { toast } = await import('sonner')
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -617,13 +617,13 @@ describe('PendingDevicesModal', () => {
})
it('keeps rack gear in the rackable list — it is hardware', async () => {
- render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ render(<DeviceInventoryModal {...baseProps} initialRackableOnly />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument())
expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument()
})
it('approves nothing when the whole selection is rack gear', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-rack')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Select mode' }))
fireEvent.click(screen.getByTestId('pending-card-dev-rack'))
@@ -641,7 +641,7 @@ describe('PendingDevicesModal', () => {
})
it('drops virtual and mesh kinds when the filter is on', async () => {
- render(<PendingDevicesModal {...baseProps} />)
+ render(<DeviceInventoryModal {...baseProps} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-vm')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Rackable' }))
@@ -650,7 +650,7 @@ describe('PendingDevicesModal', () => {
})
it('starts filtered when the caller asks for it', async () => {
- render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ render(<DeviceInventoryModal {...baseProps} initialRackableOnly />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.queryByTestId('pending-card-dev-vm')).not.toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Rackable' })).toHaveAttribute(
@@ -660,20 +660,20 @@ describe('PendingDevicesModal', () => {
})
it('re-arms the filter when reopened after the user turned it off', async () => {
- const { rerender } = render(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ const { rerender } = render(<DeviceInventoryModal {...baseProps} initialRackableOnly />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByRole('button', { name: 'Rackable' }))
expect(screen.getByTestId('pending-card-dev-vm')).toBeInTheDocument()
- rerender(<PendingDevicesModal {...baseProps} open={false} initialRackableOnly />)
- rerender(<PendingDevicesModal {...baseProps} initialRackableOnly />)
+ rerender(<DeviceInventoryModal {...baseProps} open={false} initialRackableOnly />)
+ rerender(<DeviceInventoryModal {...baseProps} initialRackableOnly />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.queryByTestId('pending-card-dev-vm')).not.toBeInTheDocument()
})
it('hands the card back instead of opening the approval modal', async () => {
const onPick = vi.fn()
- render(<PendingDevicesModal {...baseProps} onPick={onPick} />)
+ render(<DeviceInventoryModal {...baseProps} onPick={onPick} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
fireEvent.click(screen.getByTestId('pending-card-dev-a'))
@@ -682,7 +682,7 @@ describe('PendingDevicesModal', () => {
})
it('hides the bulk and clear controls a picker has no business offering', async () => {
- render(<PendingDevicesModal {...baseProps} onPick={vi.fn()} />)
+ render(<DeviceInventoryModal {...baseProps} onPick={vi.fn()} />)
await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())
expect(screen.queryByRole('button', { name: 'Select mode' })).not.toBeInTheDocument()
diff --git a/frontend/src/components/modals/__tests__/PendingDeviceModal.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModal.test.tsx
similarity index 71%
rename from frontend/src/components/modals/__tests__/PendingDeviceModal.test.tsx
rename to frontend/src/components/modals/__tests__/InventoryDeviceModal.test.tsx
index ec61f73..dec2b8a 100644
--- a/frontend/src/components/modals/__tests__/PendingDeviceModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModal.test.tsx
@@ -1,8 +1,8 @@
import { describe, it, expect, vi } from 'vitest'
import { render, screen, fireEvent } from '@testing-library/react'
-import { PendingDeviceModal, type PendingDevice } from '../PendingDeviceModal'
+import { InventoryDeviceModal, type InventoryEntry } from '../InventoryDeviceModal'
-function makeDevice(overrides: Partial<PendingDevice> = {}): PendingDevice {
+function makeDevice(overrides: Partial<InventoryEntry> = {}): InventoryEntry {
return {
id: 'dev-1',
ip: '192.168.1.100',
@@ -17,19 +17,19 @@ function makeDevice(overrides: Partial<PendingDevice> = {}): PendingDevice {
}
}
-describe('PendingDeviceModal', () => {
+describe('InventoryDeviceModal', () => {
// ── Visibility ────────────────────────────────────────────────────────────
it('renders nothing when device is null', () => {
const { container } = render(
- <PendingDeviceModal device={null} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={null} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(container.querySelector('[role="dialog"]')).toBeNull()
})
it('renders dialog when device is provided', () => {
render(
- <PendingDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByRole('dialog')).toBeDefined()
})
@@ -38,7 +38,7 @@ describe('PendingDeviceModal', () => {
it('shows hostname as title when available', () => {
render(
- <PendingDeviceModal device={makeDevice({ hostname: 'myserver.local' })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice({ hostname: 'myserver.local' })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
// hostname appears in both title and info row — check at least one match
expect(screen.getAllByText('myserver.local').length).toBeGreaterThan(0)
@@ -46,7 +46,7 @@ describe('PendingDeviceModal', () => {
it('falls back to IP as title when hostname is null', () => {
render(
- <PendingDeviceModal device={makeDevice({ hostname: null })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice({ hostname: null })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
// IP appears in both title and info row when hostname is absent
expect(screen.getAllByText('192.168.1.100').length).toBeGreaterThan(0)
@@ -54,28 +54,28 @@ describe('PendingDeviceModal', () => {
it('shows IP address', () => {
render(
- <PendingDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('192.168.1.100')).toBeDefined()
})
it('shows MAC address when present', () => {
render(
- <PendingDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('aa:bb:cc:dd:ee:ff')).toBeDefined()
})
it('shows OS when present', () => {
render(
- <PendingDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('Linux')).toBeDefined()
})
it('does not show hostname row when hostname is null', () => {
render(
- <PendingDeviceModal device={makeDevice({ hostname: null })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice({ hostname: null })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
// "Hostname" label should not appear in the info rows
expect(screen.queryByText('Hostname')).toBeNull()
@@ -83,7 +83,7 @@ describe('PendingDeviceModal', () => {
it('shows suggested type when present', () => {
render(
- <PendingDeviceModal device={makeDevice({ suggested_type: 'proxmox' })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice({ suggested_type: 'proxmox' })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('proxmox')).toBeDefined()
})
@@ -92,7 +92,7 @@ describe('PendingDeviceModal', () => {
it('shows "No services detected" when services list is empty', () => {
render(
- <PendingDeviceModal device={makeDevice({ services: [] })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice({ services: [] })} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('No services detected')).toBeDefined()
})
@@ -105,7 +105,7 @@ describe('PendingDeviceModal', () => {
],
})
render(
- <PendingDeviceModal device={device} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={device} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('Services found (2)')).toBeDefined()
expect(screen.getByText('HTTP')).toBeDefined()
@@ -119,7 +119,7 @@ describe('PendingDeviceModal', () => {
services: [{ port: 8006, protocol: 'tcp', service_name: 'Proxmox Web', category: 'hypervisor' }],
})
render(
- <PendingDeviceModal device={device} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={device} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByText('hypervisor')).toBeDefined()
})
@@ -131,7 +131,7 @@ describe('PendingDeviceModal', () => {
const onApprove = vi.fn()
const onClose = vi.fn()
render(
- <PendingDeviceModal device={device} onClose={onClose} onApprove={onApprove} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={device} onClose={onClose} onApprove={onApprove} onHide={vi.fn()} onIgnore={vi.fn()} />
)
fireEvent.click(screen.getByRole('button', { name: 'Approve' }))
expect(onApprove).toHaveBeenCalledWith(device)
@@ -143,7 +143,7 @@ describe('PendingDeviceModal', () => {
const onHide = vi.fn()
const onClose = vi.fn()
render(
- <PendingDeviceModal device={device} onClose={onClose} onApprove={vi.fn()} onHide={onHide} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={device} onClose={onClose} onApprove={vi.fn()} onHide={onHide} onIgnore={vi.fn()} />
)
fireEvent.click(screen.getByRole('button', { name: 'Hide' }))
expect(onHide).toHaveBeenCalledWith(device)
@@ -155,7 +155,7 @@ describe('PendingDeviceModal', () => {
const onIgnore = vi.fn()
const onClose = vi.fn()
render(
- <PendingDeviceModal device={device} onClose={onClose} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={onIgnore} />
+ <InventoryDeviceModal device={device} onClose={onClose} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={onIgnore} />
)
fireEvent.click(screen.getByRole('button', { name: 'Delete' }))
expect(onIgnore).toHaveBeenCalledWith(device)
@@ -163,7 +163,7 @@ describe('PendingDeviceModal', () => {
})
})
-describe('PendingDeviceModal — rack gear', () => {
+describe('InventoryDeviceModal — rack gear', () => {
const rackDevice = makeDevice({
id: 'dev-rack',
hostname: 'patch-house',
@@ -174,7 +174,7 @@ describe('PendingDeviceModal — rack gear', () => {
it('offers no Approve button — rack gear never lands on a logical canvas', () => {
render(
- <PendingDeviceModal device={rackDevice} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={rackDevice} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull()
// Hide and Delete still apply: the entry is inventory like any other.
@@ -184,7 +184,7 @@ describe('PendingDeviceModal — rack gear', () => {
it('keeps Approve for a scanned device', () => {
render(
- <PendingDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
+ <InventoryDeviceModal device={makeDevice()} onClose={vi.fn()} onApprove={vi.fn()} onHide={vi.fn()} onIgnore={vi.fn()} />
)
expect(screen.getByRole('button', { name: 'Approve' })).toBeInTheDocument()
})
diff --git a/frontend/src/components/modals/__tests__/SearchModal.test.tsx b/frontend/src/components/modals/__tests__/SearchModal.test.tsx
index 5b19298..3ded3a3 100644
--- a/frontend/src/components/modals/__tests__/SearchModal.test.tsx
+++ b/frontend/src/components/modals/__tests__/SearchModal.test.tsx
@@ -14,7 +14,7 @@ vi.mock('@/api/client', () => ({
scanApi: { pending: vi.fn().mockResolvedValue({ data: [] }) },
}))
-const mockOnOpenPending = vi.fn()
+const mockOnOpenInventory = vi.fn()
function makeNode(id: string, overrides: Partial<NodeData> = {}): Node<NodeData> {
return {
@@ -38,23 +38,23 @@ describe('SearchModal', () => {
})
it('renders nothing when closed', () => {
- render(<SearchModal open={false} onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open={false} onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
expect(screen.queryByPlaceholderText(/search nodes/i)).toBeNull()
})
it('renders search input when open', () => {
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
expect(screen.getByPlaceholderText(/search nodes/i)).toBeDefined()
})
it('shows "Type to search" hint when query is empty', () => {
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
expect(screen.getByText(/type to search/i)).toBeDefined()
})
it('shows no results message when query has no matches', () => {
useCanvasStore.setState({ nodes: [makeNode('router', { label: 'Router' })] })
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zzz' } })
expect(screen.getByText(/no results match/i)).toBeDefined()
})
@@ -63,7 +63,7 @@ describe('SearchModal', () => {
useCanvasStore.setState({
nodes: [makeNode('n1', { label: 'My Router' }), makeNode('n2', { label: 'NAS Server' })],
})
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'router' } })
expect(screen.getByText('My Router')).toBeDefined()
expect(screen.queryByText('NAS Server')).toBeNull()
@@ -76,7 +76,7 @@ describe('SearchModal', () => {
makeNode('n2', { label: 'Box B', ip: '10.0.0.1' }),
],
})
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: '192.168' } })
expect(screen.getByText('Box A')).toBeDefined()
expect(screen.queryByText('Box B')).toBeNull()
@@ -89,7 +89,7 @@ describe('SearchModal', () => {
makeNode('n2', { label: 'B', hostname: 'nas.local' }),
],
})
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'pve' } })
expect(screen.getByText('A')).toBeDefined()
expect(screen.queryByText('B')).toBeNull()
@@ -102,7 +102,7 @@ describe('SearchModal', () => {
makeNode('g1', { label: 'Zone A', type: 'groupRect' }),
],
})
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'zone' } })
expect(screen.getByText(/no results match/i)).toBeDefined()
})
@@ -111,7 +111,7 @@ describe('SearchModal', () => {
useCanvasStore.setState({
nodes: Array.from({ length: 12 }, (_, i) => makeNode(`n${i}`, { label: `Server ${i}` })),
})
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'server' } })
const items = screen.getAllByText(/Server \d/)
expect(items).toHaveLength(6)
@@ -120,7 +120,7 @@ describe('SearchModal', () => {
it('selects node and closes on result click', () => {
const onClose = vi.fn()
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Proxmox' })] })
- render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={onClose} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'prox' } })
fireEvent.click(screen.getByText('Proxmox'))
expect(useCanvasStore.getState().selectedNodeId).toBe('n1')
@@ -131,7 +131,7 @@ describe('SearchModal', () => {
it('selects first result and closes on Enter key', () => {
const onClose = vi.fn()
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'Switch' })] })
- render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={onClose} onOpenInventory={mockOnOpenInventory} />)
const input = screen.getByPlaceholderText(/search nodes/i)
fireEvent.change(input, { target: { value: 'switch' } })
fireEvent.keyDown(input, { key: 'Enter' })
@@ -141,14 +141,14 @@ describe('SearchModal', () => {
it('closes on Escape key', () => {
const onClose = vi.fn()
- render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={onClose} onOpenInventory={mockOnOpenInventory} />)
fireEvent.keyDown(screen.getByPlaceholderText(/search nodes/i), { key: 'Escape' })
expect(onClose).toHaveBeenCalledOnce()
})
it('closes when clicking backdrop', () => {
const onClose = vi.fn()
- render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={onClose} onOpenInventory={mockOnOpenInventory} />)
// The backdrop is the fixed inset div — clicking it fires onClose
const backdrop = document.querySelector('.fixed.inset-0') as HTMLElement
fireEvent.click(backdrop)
@@ -157,14 +157,14 @@ describe('SearchModal', () => {
it('does not close when clicking inside the search box', () => {
const onClose = vi.fn()
- render(<SearchModal open onClose={onClose} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={onClose} onOpenInventory={mockOnOpenInventory} />)
fireEvent.click(screen.getByPlaceholderText(/search nodes/i))
expect(onClose).not.toHaveBeenCalled()
})
it('search is case-insensitive', () => {
useCanvasStore.setState({ nodes: [makeNode('n1', { label: 'My NAS' })] })
- render(<SearchModal open onClose={vi.fn()} onOpenPending={mockOnOpenPending} />)
+ render(<SearchModal open onClose={vi.fn()} onOpenInventory={mockOnOpenInventory} />)
fireEvent.change(screen.getByPlaceholderText(/search nodes/i), { target: { value: 'MY NAS' } })
expect(screen.getByText('My NAS')).toBeDefined()
})
diff --git a/frontend/src/components/panels/Sidebar.tsx b/frontend/src/components/panels/Sidebar.tsx
index d4cc60e..1542323 100644
--- a/frontend/src/components/panels/Sidebar.tsx
+++ b/frontend/src/components/panels/Sidebar.tsx
@@ -34,10 +34,10 @@ interface SidebarProps {
onSave: () => void
onOpenSettings: () => void
onOpenHistory: () => void
- onOpenPending: (deviceId?: string, status?: 'pending' | 'hidden') => void
+ onOpenInventory: (deviceId?: string, status?: 'pending' | 'hidden') => void
}
-export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onZwaveImport, onProxmoxImport, onSave, onOpenSettings, onOpenHistory, onOpenPending }: SidebarProps) {
+export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbeeImport, onZwaveImport, onProxmoxImport, onSave, onOpenSettings, onOpenHistory, onOpenInventory }: SidebarProps) {
const [collapsed, setCollapsed] = useState(false)
const logout = useAuthStore((s) => s.logout)
const { designs, activeDesignId, activeDesignType, setActiveDesign, addDesign, updateDesign, removeDesign } = useDesignStore()
@@ -251,7 +251,7 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
icon={t.icon}
label={t.label}
collapsed={collapsed}
- onClick={() => onOpenPending(undefined, t.kind)}
+ onClick={() => onOpenInventory(undefined, t.kind)}
/>
))}
{!STANDALONE && (
diff --git a/frontend/src/components/panels/__tests__/Sidebar.test.tsx b/frontend/src/components/panels/__tests__/Sidebar.test.tsx
index fb8d312..4e3ab5a 100644
--- a/frontend/src/components/panels/__tests__/Sidebar.test.tsx
+++ b/frontend/src/components/panels/__tests__/Sidebar.test.tsx
@@ -78,7 +78,7 @@ const defaultProps = {
onSave: vi.fn(),
onOpenSettings: vi.fn(),
onOpenHistory: vi.fn(),
- onOpenPending: vi.fn(),
+ onOpenInventory: vi.fn(),
}
// ── Tests ─────────────────────────────────────────────────────────────────────
@@ -244,16 +244,16 @@ describe('Sidebar', () => {
// ── Pending / Hidden open modal ────────────────────────────────────────────
- it('calls onOpenPending with pending status when Device Inventory is clicked', () => {
+ it('calls onOpenInventory with pending status when Device Inventory is clicked', () => {
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Device Inventory'))
- expect(defaultProps.onOpenPending).toHaveBeenCalledWith(undefined, 'pending')
+ expect(defaultProps.onOpenInventory).toHaveBeenCalledWith(undefined, 'pending')
})
- it('calls onOpenPending with hidden status when Hidden Devices is clicked', () => {
+ it('calls onOpenInventory with hidden status when Hidden Devices is clicked', () => {
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Hidden Devices'))
- expect(defaultProps.onOpenPending).toHaveBeenCalledWith(undefined, 'hidden')
+ expect(defaultProps.onOpenInventory).toHaveBeenCalledWith(undefined, 'hidden')
})
it('calls onOpenHistory when Scan History nav item is clicked', () => {
diff --git a/frontend/src/components/panels/__tests__/VersionBadge.test.tsx b/frontend/src/components/panels/__tests__/VersionBadge.test.tsx
index 104fc41..043f30a 100644
--- a/frontend/src/components/panels/__tests__/VersionBadge.test.tsx
+++ b/frontend/src/components/panels/__tests__/VersionBadge.test.tsx
@@ -29,7 +29,7 @@ vi.mock('@/components/ui/tooltip', () => ({
TooltipTrigger: ({ children }: { children: React.ReactNode }) => <>{children}</>,
TooltipContent: () => null,
}))
-vi.mock('@/components/modals/PendingDeviceModal', () => ({ PendingDeviceModal: () => null }))
+vi.mock('@/components/modals/InventoryDeviceModal', () => ({ InventoryDeviceModal: () => null }))
vi.mock('@/components/modals/StatusTimelineModal', () => ({ StatusTimelineModal: () => null }))
vi.mock('@/hooks/useLatestRelease', () => ({
diff --git a/frontend/src/components/proxmox/ProxmoxImportModal.tsx b/frontend/src/components/proxmox/ProxmoxImportModal.tsx
index 02812e2..be89d4c 100644
--- a/frontend/src/components/proxmox/ProxmoxImportModal.tsx
+++ b/frontend/src/components/proxmox/ProxmoxImportModal.tsx
@@ -12,7 +12,7 @@ interface ProxmoxImportModalProps {
open: boolean
onClose: () => void
onAddToCanvas: (nodes: ProxmoxNode[], edges: ProxmoxEdge[]) => void
- onPendingImported?: () => void
+ onInventoryImported?: () => void
}
type ImportMode = 'pending' | 'canvas'
@@ -53,7 +53,7 @@ const DEVICE_TYPE_COLOR: Record<ProxmoxNodeType, string> = {
lxc: '#39d353',
}
-export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onPendingImported }: ProxmoxImportModalProps) {
+export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryImported }: ProxmoxImportModalProps) {
const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')
const [connectionMsg, setConnectionMsg] = useState('')
@@ -101,7 +101,7 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onPendingImpo
if (importMode === 'pending') {
await proxmoxApi.importToPending(buildPayload())
toast.success('Proxmox import started — track progress in Scan History')
- onPendingImported?.()
+ onInventoryImported?.()
handleClose()
} else {
const res = await proxmoxApi.importNetwork(buildPayload())
diff --git a/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx b/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
index 4384c2b..7efa2a8 100644
--- a/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
+++ b/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
@@ -18,7 +18,7 @@ const defaultProps = {
open: true,
onClose: vi.fn(),
onAddToCanvas: vi.fn(),
- onPendingImported: vi.fn(),
+ onInventoryImported: vi.fn(),
}
const sampleNodes = [
@@ -44,7 +44,7 @@ describe('ProxmoxImportModal', () => {
vi.mocked(toast.info).mockReset()
defaultProps.onClose.mockReset()
defaultProps.onAddToCanvas.mockReset()
- defaultProps.onPendingImported.mockReset()
+ defaultProps.onInventoryImported.mockReset()
})
it('renders nothing when closed', () => {
@@ -85,7 +85,7 @@ describe('ProxmoxImportModal', () => {
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or pve.local'), { target: { value: 'pve' } })
fireEvent.click(screen.getByRole('button', { name: /import to pending/i }))
await waitFor(() => expect(proxmoxApi.importToPending).toHaveBeenCalled())
- expect(defaultProps.onPendingImported).toHaveBeenCalled()
+ expect(defaultProps.onInventoryImported).toHaveBeenCalled()
expect(proxmoxApi.importNetwork).not.toHaveBeenCalled()
})
diff --git a/frontend/src/components/zigbee/ZigbeeImportModal.tsx b/frontend/src/components/zigbee/ZigbeeImportModal.tsx
index 9c452ee..6172581 100644
--- a/frontend/src/components/zigbee/ZigbeeImportModal.tsx
+++ b/frontend/src/components/zigbee/ZigbeeImportModal.tsx
@@ -12,7 +12,7 @@ interface ZigbeeImportModalProps {
open: boolean
onClose: () => void
onAddToCanvas: (nodes: ZigbeeNode[], edges: ZigbeeEdge[]) => void
- onPendingImported?: (
+ onInventoryImported?: (
coordinator?: { id: string; label: string; ieee_address: string } | null,
) => void
}
@@ -59,7 +59,7 @@ const DEVICE_TYPE_COLOR = {
zigbee_enddevice: '#e3b341',
} as const
-export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onPendingImported }: ZigbeeImportModalProps) {
+export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImported }: ZigbeeImportModalProps) {
const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')
const [connectionMsg, setConnectionMsg] = useState('')
@@ -140,7 +140,7 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onPendingImpor
if (importMode === 'pending') {
await zigbeeApi.importToPending(buildPayload())
toast.success('Zigbee import started — track progress in Scan History')
- onPendingImported?.(null)
+ onInventoryImported?.(null)
handleClose()
} else {
const res = await zigbeeApi.importNetwork(buildPayload())
diff --git a/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx b/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
index f74b11c..3e8f960 100644
--- a/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
+++ b/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
@@ -191,16 +191,16 @@ describe('ZigbeeImportModal', () => {
error: null,
},
} as never)
- const onPendingImported = vi.fn()
+ const onInventoryImported = vi.fn()
- render(<ZigbeeImportModal {...defaultProps} onPendingImported={onPendingImported} />)
+ render(<ZigbeeImportModal {...defaultProps} onInventoryImported={onInventoryImported} />)
const hostInput = screen.getByPlaceholderText('192.168.1.x or mqtt.local')
fireEvent.change(hostInput, { target: { value: '192.168.1.100' } })
fireEvent.click(screen.getByRole('button', { name: /import to pending/i }))
await waitFor(() => {
expect(zigbeeApi.importToPending).toHaveBeenCalled()
- expect(onPendingImported).toHaveBeenCalled()
+ expect(onInventoryImported).toHaveBeenCalled()
expect(defaultProps.onClose).toHaveBeenCalled()
})
expect(zigbeeApi.importNetwork).not.toHaveBeenCalled()
diff --git a/frontend/src/components/zwave/ZwaveImportModal.tsx b/frontend/src/components/zwave/ZwaveImportModal.tsx
index ad809ca..d8543ca 100644
--- a/frontend/src/components/zwave/ZwaveImportModal.tsx
+++ b/frontend/src/components/zwave/ZwaveImportModal.tsx
@@ -12,7 +12,7 @@ interface ZwaveImportModalProps {
open: boolean
onClose: () => void
onAddToCanvas: (nodes: ZwaveNode[], edges: ZwaveEdge[]) => void
- onPendingImported?: (
+ onInventoryImported?: (
coordinator?: { id: string; label: string; ieee_address: string } | null,
) => void
}
@@ -63,7 +63,7 @@ const DEVICE_TYPE_COLOR = {
zwave_enddevice: '#e3b341',
} as const
-export function ZwaveImportModal({ open, onClose, onAddToCanvas, onPendingImported }: ZwaveImportModalProps) {
+export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImported }: ZwaveImportModalProps) {
const [form, setForm] = useState<ConnectionForm>(DEFAULT_FORM)
const [connectionStatus, setConnectionStatus] = useState<'idle' | 'testing' | 'ok' | 'fail'>('idle')
const [connectionMsg, setConnectionMsg] = useState('')
@@ -145,7 +145,7 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onPendingImport
if (importMode === 'pending') {
await zwaveApi.importToPending(buildPayload())
toast.success('Z-Wave import started — track progress in Scan History')
- onPendingImported?.(null)
+ onInventoryImported?.(null)
handleClose()
} else {
const res = await zwaveApi.importNetwork(buildPayload())
diff --git a/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx b/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
index 3d5fcf8..7b4241b 100644
--- a/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
+++ b/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
@@ -152,9 +152,9 @@ describe('ZwaveImportModal', () => {
error: null,
},
} as never)
- const onPendingImported = vi.fn()
+ const onInventoryImported = vi.fn()
- render(<ZwaveImportModal {...defaultProps} onPendingImported={onPendingImported} />)
+ render(<ZwaveImportModal {...defaultProps} onInventoryImported={onInventoryImported} />)
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or mqtt.local'), {
target: { value: '192.168.1.100' },
})
@@ -162,7 +162,7 @@ describe('ZwaveImportModal', () => {
await waitFor(() => {
expect(zwaveApi.importToPending).toHaveBeenCalled()
- expect(onPendingImported).toHaveBeenCalled()
+ expect(onInventoryImported).toHaveBeenCalled()
expect(defaultProps.onClose).toHaveBeenCalled()
})
expect(zwaveApi.importNetwork).not.toHaveBeenCalled()
diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.md
index f46d7e0..86231a4 100644
--- a/frontend/src/rack/README.md
+++ b/frontend/src/rack/README.md
@@ -14,11 +14,12 @@ Create one from **New Canvas → Kind → Rack**.
| Vertical | `uStart` (1-based, **always counted from the bottom rail**) + `uHeight`. `numbering` only changes the printed labels. |
| Horizontal | 12-column grid (`RACK_COLUMNS`). Full = 12, half = 6, third = 4, quarter = 3 — so 2 or 3 machines share one U. |
| Collision | `canPlace` / `findSlot` in `layout.ts`. A drop snaps to the nearest free slot; an impossible drop shows a red preview. |
-| Inventory | A mount references a **Device Inventory** entry (`pending_devices`) via `deviceId`. Those rows survive approval *and* node deletion, so unracking never removes the device. Accessories (blank, shelf, cable manager) have `deviceId: null`. `label` comes from `_device_label` in `racks.py`, which mirrors `deviceLabel` in `PendingDevicesModal.tsx` (friendly name → host → app the ports say it runs → IP → IEEE → id) so a device is named the same in both lists. |
+| Inventory | A mount references a **Device Inventory** entry (`device_inventory`) via `deviceId`. Those rows survive approval *and* node deletion, so unracking never removes the device. Accessories (blank, shelf, cable manager) have `deviceId: null`. `label` comes from `_device_label` in `racks.py`, which mirrors `deviceLabel` in `DeviceInventoryModal.tsx` (friendly name → host → app the ports say it runs → IP → IEEE → id) so a device is named the same in both lists. |
| Rack-created gear | A device created from this canvas is a normal inventory row with `discovery_source: "rack"`, so it inherits the inventory's search, filters, hide and delete. It shows under the **Rack devices** source filter, and both `POST /scan/pending/{id}/approve` and bulk-approve refuse it — a mount is not a host to document on a logical canvas. Its `suggested_type` comes from the plate it wears (`deviceTypeForFaceplate`), since no scan is there to guess one: without it the row had no icon, no role badge and no place in the type filter. Passive gear uses the rack-only kinds `patch_panel` and `pdu` — the logical canvas has no node type for it, and `pdu` must not be `socket`, which is excluded from the rack inventory. |
-| Picking one | The **Device Inventory entry** field opens the real Device Inventory modal (`PendingDevicesModal` in picker mode: a card click returns the device, bulk/clear controls are hidden) rather than a flat `<select>`, so the user gets its search, source/type filters and per-card detail. It opens with the **Rackable** filter armed — hardware only, `UNRACKABLE_TYPES` in `utils/rackable.ts` mirroring `_UNRACKABLE_TYPES` in `racks.py`, with `test_rackable_sync.py` failing on drift. The rack side still has the last word: a device missing from its own list, or already mounted in this design, is refused with a toast. Standalone keeps the `<select>` — no backend, no inventory modal. |
+| Picking one | The **Device Inventory entry** field opens the real Device Inventory modal (`DeviceInventoryModal` in picker mode: a card click returns the device, bulk/clear controls are hidden) rather than a flat `<select>`, so the user gets its search, source/type filters and per-card detail. It opens with the **Rackable** filter armed — hardware only, `UNRACKABLE_TYPES` in `utils/rackable.ts` mirroring `_UNRACKABLE_TYPES` in `racks.py`, with `test_rackable_sync.py` failing on drift. The rack side still has the last word: a device missing from its own list, or already mounted in this design, is refused with a toast. Standalone keeps the `<select>` — no backend, no inventory modal. |
| Canvas node link | `nodeId` is a second, optional link to a logical-canvas node, resolved server-side by IEEE then IP. It supplies live status and lets the network-link import match endpoints. Never required. |
-| Logical view panel | `LinkedDevicePanel`, under the port list in `RackDeviceModal`: the facts the logical canvas holds about the same box — name, type, hostname, IP, MAC, OS, status check, the canvas it is drawn on, last seen, and the fingerprinted services. Read-only; the logical view owns them. `/racks/inventory` ships them as `node_*` alongside the inventory row's own `mac` / `hostname` / `os` / `services`, and the panel prefers the node value (curated) over the inventory one (what discovery last saw), dropping any row neither side can fill. A mount with no inventory entry — an accessory — gets no panel. |
+| Relinking one by hand | A plate created from the rack carries a placeholder inventory row with a name and nothing else, and the IEEE/IP guess behind `nodeId` finds nothing for gear with no MAC and no address. `DevicePickerModal` — opened from the Linked device panel, listing the rack's own `/racks/inventory` copy — points the mount at another **Device Inventory** row instead: `relinkDevice` writes `deviceId`, adopts that row's `nodeId`, status and (unless the user renamed the plate) label, and recomputes the racked flags, so the panel, the Status select and the plate LED follow before the canvas is even saved. One entry, one mount: a row another plate stands for is not offered, and the store refuses it anyway. The placeholder left behind is deleted through `DELETE /scan/pending/{id}` when the rack created it (`discovery_source: "rack"`) and nothing else mounts it — that route refuses a mounted device with a 409, since `rack_devices.device_id` is `ON DELETE SET NULL` and would otherwise blank the mount. A row from discovery or from the user is never touched. |
+| Linked device panel | `LinkedDevicePanel`, under the port list in `RackDeviceModal`: what is known about the box a mount stands for — name, type, hostname, IP, MAC, OS, status check, the canvas it is drawn on, last seen, and the fingerprinted services. Read-only; the inventory and the logical canvas own them. `/racks/inventory` ships the canvas side as `node_*` alongside the inventory row's own `mac` / `hostname` / `os` / `services`, and the panel prefers the node value (curated) over the inventory one (what discovery last saw), dropping any row neither side can fill. A device on no canvas still prints everything discovery found — it is the record of a real box whether or not anyone drew it — and adds *Not on a logical canvas.*, which is why `auto` resolves to `unknown` there. *Link to another device…* is always on offer for a real mount, so a placeholder or the wrong twin of two look-alikes is not a dead end. A mount with no inventory entry — an accessory — gets no panel. |
| Status | A mount stores a `MountStatus`: `online` / `offline` / `unknown` pinned by hand, or `auto` — "check device", i.e. follow the status check already configured on the matching canvas node (ping, http, ssh…). The rack runs no checker of its own; `auto` resolves through the inventory entry's `node_status` (`resolveDeviceStatus` in `deviceStatus.ts`) and falls back to `unknown` when nothing is behind it. The Status select offers `auto` only when the mount — or the entry being picked — resolves to a node, and drops back to `unknown` when that link is lost. `useAutoStatusRefresh` polls the inventory every 60 s while at least one mount is on `auto`, and only then; the refresh writes inventory only, so autosave stays quiet. |
| Faceplates | Declarative templates in `faceplates.ts`, drawn as SVG in unit coordinates so a plate scales with U height and rack width. Applying a template seeds ports; the user edits them afterwards. `suggestFaceplate()` picks one from the device's discovery type. Chosen from `FaceplatePicker` — a visual catalog, not a `<select>`: every template is drawn with the canvas renderer at its real relative width and U height, grouped, searchable, and filterable by `kind` (accessories are offered only to accessories). |
| Ports | RJ45 and SFP/SFP+ only, drawn as real jack artwork at a fixed pixel size so plates of different U heights line up. Manual list per device. Power outlets are artwork, never a cable endpoint. |
@@ -36,13 +37,13 @@ debounces on the store's `editSeq`.
| Where | What |
|---|---|
-| `racks`, `rack_devices`, `rack_cables` | One row set per design. `rack_devices.device_id → pending_devices` and `node_id → nodes` are both `ON DELETE SET NULL`, and `label` is denormalized, so a rack keeps rendering after an inventory purge. |
+| `racks`, `rack_devices`, `rack_cables` | One row set per design. `rack_devices.device_id → device_inventory` and `node_id → nodes` are both `ON DELETE SET NULL`, and `label` is denormalized, so a rack keeps rendering after an inventory purge. |
| `canvas_state.viewport` | Pan/zoom, shared with the logical canvas row for that design. |
| `GET /api/v1/racks?design_id=` | Full state. |
| `POST /api/v1/racks/save` | Full state: upsert what is sent, prune the rest. Rejects a device pointing at a rack outside the payload, or a cable pointing at a device outside it. Also cross-checks geometry: a mount against the height of the rack it names, and `col_start + col_span` against the grid — each field is legal alone and the pair is not. |
| `GET /api/v1/racks/inventory?design_id=` | Rackable inventory entries, each flagged `racked` and resolved to a canvas node when one matches. |
| `POST /api/v1/scan/pending` | Manual inventory entry (`discovery_source: "manual"`), for hardware no scan can find. |
-| Standalone | `homelable_rack:<designId>` in localStorage, inventory included (no `pending_devices` table to read). |
+| Standalone | `homelable_rack:<designId>` in localStorage, inventory included (no `device_inventory` table to read). |
`@/utils/rackSerializer` maps the snake_case wire shapes to the camelCase domain
types in `@/types/rack`, narrowing every enum on the way in.
@@ -53,7 +54,7 @@ types in `@/types/rack`, narrowing every enum on the way in.
- Drag from the sidebar tray onto a rack → snaps to a free U.
- Drag a mounted device inside the rack → same snapping, own slot ignored.
- The **Faceplate** field previews the current plate; clicking it opens `FaceplatePicker`. Switching the source between device and accessory swaps the plate to a sane default of the other kind.
-- Double-click a plate → the same modal in edit mode: label, faceplate, U/height/column/width, status, colour, port list, the **Logical view** panel, Unmount. Single click only selects.
+- Double-click a plate → the same modal in edit mode: label, faceplate, U/height/column/width, status, colour, port list, the **Linked device** panel, Unmount. Single click only selects.
- Double-click empty rack chrome → `RackSettingsModal` (name, location, U height, 19"/10", numbering direction, frame/rail/interior colours, U numbers, enclosed, delete).
- Growing a device — by hand or by picking a taller plate — relocates it to the nearest slot that takes the new size. Only a rack with no such slot rejects the edit, and says so.
- Shrinking a **rack** follows the same rule: `updateRack` clamps `uHeight` to `[MIN_RACK_U, MAX_RACK_U]` (1–48; the backend tolerates 100) and relocates every mount the new height would push above the top rail, one at a time so two never land on the same slot. It returns false and changes nothing when one has nowhere to go. The number input's `min`/`max` are hints the browser does not enforce on typed input — a raw 999 used to make every save fail the backend's `1..100` check with no cause shown, and a shrink left plates drawn outside the chassis that nothing could drag back.
diff --git a/frontend/src/rack/__tests__/DevicePickerModal.test.tsx b/frontend/src/rack/__tests__/DevicePickerModal.test.tsx
new file mode 100644
index 0000000..4833d0f
--- /dev/null
+++ b/frontend/src/rack/__tests__/DevicePickerModal.test.tsx
@@ -0,0 +1,138 @@
+/** Pointing a mount at another Device Inventory entry. */
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { DevicePickerModal } from '../components/DevicePickerModal'
+import { useRackStore } from '../store'
+import type { InventoryDevice } from '@/types'
+
+const refreshInventory = vi.hoisted(() => vi.fn())
+
+function makeEntry(overrides: Partial<InventoryDevice> = {}): InventoryDevice {
+ return {
+ id: 'inv1',
+ label: 'nas-truenas',
+ type: 'nas',
+ discoverySource: 'arp',
+ ip: '192.168.1.40',
+ mac: 'aa:bb:cc:dd:ee:ff',
+ hostname: 'nas.lan',
+ os: null,
+ services: [],
+ status: 'online',
+ nodeId: null,
+ node: null,
+ racked: false,
+ suggestedFaceplateId: 'nas-2u',
+ ...overrides,
+ }
+}
+
+function seed(inventory: InventoryDevice[]) {
+ useRackStore.setState({ inventory, refreshInventory })
+}
+
+beforeEach(() => {
+ refreshInventory.mockClear()
+ seed([])
+})
+
+describe('DevicePickerModal', () => {
+ it('offers the Device Inventory, canvas node or not', async () => {
+ // The whole point: a device no one ever approved onto a logical canvas is
+ // still the record of a real box, and is what racks are built out of.
+ seed([
+ makeEntry(),
+ makeEntry({ id: 'inv2', label: 'pve-01', ip: '192.168.1.10', nodeId: 'node2' }),
+ ])
+ render(<DevicePickerModal open onPick={vi.fn()} onClose={vi.fn()} />)
+
+ expect(screen.getByText('nas-truenas')).toBeInTheDocument()
+ expect(screen.getByText('pve-01')).toBeInTheDocument()
+ expect(refreshInventory).toHaveBeenCalled()
+ })
+
+ it('hands the picked entry back', async () => {
+ const onPick = vi.fn()
+ seed([makeEntry()])
+ render(<DevicePickerModal open onPick={onPick} onClose={vi.fn()} />)
+
+ await userEvent.click(screen.getByText('nas-truenas'))
+ expect(onPick).toHaveBeenCalledWith(expect.objectContaining({ id: 'inv1' }))
+ })
+
+ it('prints the source and the canvas, which tell look-alikes apart', () => {
+ seed([
+ makeEntry({
+ discoverySource: 'rack',
+ node: {
+ id: 'node1',
+ label: 'nas-truenas',
+ type: 'nas',
+ ip: '192.168.1.40',
+ mac: null,
+ hostname: null,
+ os: null,
+ checkMethod: 'ping',
+ designId: 'd1',
+ designName: 'Network Topology',
+ lastSeen: null,
+ },
+ }),
+ ])
+ render(<DevicePickerModal open onPick={vi.fn()} onClose={vi.fn()} />)
+
+ expect(screen.getByText(/Rack device/)).toBeInTheDocument()
+ expect(screen.getByText(/Network Topology/)).toBeInTheDocument()
+ })
+
+ it('hides a device another plate already stands for, keeping the current one', () => {
+ // One entry, one mount — but the mount being edited must still see its own.
+ seed([
+ makeEntry({ id: 'inv1', label: 'mine', racked: true }),
+ makeEntry({ id: 'inv2', label: 'taken', racked: true }),
+ makeEntry({ id: 'inv3', label: 'free' }),
+ ])
+ render(<DevicePickerModal open value="inv1" onPick={vi.fn()} onClose={vi.fn()} />)
+
+ expect(screen.getByText('mine')).toBeInTheDocument()
+ expect(screen.getByText('free')).toBeInTheDocument()
+ expect(screen.queryByText('taken')).not.toBeInTheDocument()
+ })
+
+ it('searches name, IP, hostname and source', async () => {
+ seed([makeEntry(), makeEntry({ id: 'inv2', label: 'pve-01', ip: '192.168.1.10', hostname: 'pve.lan' })])
+ render(<DevicePickerModal open onPick={vi.fn()} onClose={vi.fn()} />)
+ const search = screen.getByLabelText('Search devices')
+
+ await userEvent.type(search, '192.168.1.10')
+ expect(screen.queryByText('nas-truenas')).not.toBeInTheDocument()
+ expect(screen.getByText('pve-01')).toBeInTheDocument()
+
+ await userEvent.clear(search)
+ await userEvent.type(search, 'pve.lan')
+ expect(screen.getByText('pve-01')).toBeInTheDocument()
+
+ await userEvent.clear(search)
+ await userEvent.type(search, 'network scan')
+ expect(screen.getByText('nas-truenas')).toBeInTheDocument()
+ })
+
+ it('points at the Device Inventory when it is empty', () => {
+ render(<DevicePickerModal open onPick={vi.fn()} onClose={vi.fn()} />)
+ expect(screen.getByText(/The Device Inventory is empty/)).toBeInTheDocument()
+ })
+
+ it('says a search matched nothing, which is not the same thing', async () => {
+ seed([makeEntry()])
+ render(<DevicePickerModal open onPick={vi.fn()} onClose={vi.fn()} />)
+
+ await userEvent.type(screen.getByLabelText('Search devices'), 'nothing')
+ expect(screen.getByText('No device matches that search.')).toBeInTheDocument()
+ })
+
+ it('does not refetch while closed', () => {
+ render(<DevicePickerModal open={false} onPick={vi.fn()} onClose={vi.fn()} />)
+ expect(refreshInventory).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/rack/__tests__/LinkedDevicePanel.test.tsx b/frontend/src/rack/__tests__/LinkedDevicePanel.test.tsx
index 11d170b..5e36e58 100644
--- a/frontend/src/rack/__tests__/LinkedDevicePanel.test.tsx
+++ b/frontend/src/rack/__tests__/LinkedDevicePanel.test.tsx
@@ -1,6 +1,7 @@
/** The logical-canvas facts printed beside a mount's ports. */
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, vi } from 'vitest'
import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import { LinkedDevicePanel } from '../components/LinkedDevicePanel'
import type { InventoryDevice } from '@/types'
@@ -66,12 +67,33 @@ describe('LinkedDevicePanel', () => {
expect(screen.queryByText('192.168.1.99')).not.toBeInTheDocument()
})
- it('falls back to the inventory row when the device is on no canvas', () => {
+ it('still prints what discovery found when the device is on no canvas', () => {
+ // The inventory row is the record of a real box whether or not anyone ever
+ // drew it on a canvas — only the canvas-side rows go missing.
render(<LinkedDevicePanel entry={makeEntry({ nodeId: null, node: null })} status="unknown" />)
- expect(screen.getByText(/Not on a logical canvas/)).toBeInTheDocument()
expect(screen.getByText('192.168.1.9')).toBeInTheDocument()
expect(screen.getByText('TrueNAS')).toBeInTheDocument()
+ expect(screen.getByText('smb:445')).toBeInTheDocument()
+ // No node means no check to follow and no canvas to name.
+ expect(screen.getByText('Not on a logical canvas.')).toBeInTheDocument()
+ expect(screen.queryByText('Canvas')).not.toBeInTheDocument()
+ })
+
+ it('offers no link when relinking is not on offer', () => {
+ // A mount that does not exist yet has nothing to hang a link on.
+ render(<LinkedDevicePanel entry={makeEntry({ nodeId: null, node: null })} status="unknown" />)
+ expect(screen.queryByRole('button')).not.toBeInTheDocument()
+ })
+
+ it('lets a mount be pointed at another device', async () => {
+ // The device behind a plate can be picked wrong — a placeholder, or the
+ // wrong twin of two look-alikes — so the panel must not be a dead end.
+ const onLink = vi.fn()
+ render(<LinkedDevicePanel entry={makeEntry()} status="online" onLink={onLink} />)
+
+ await userEvent.click(screen.getByRole('button', { name: /Link to another device/ }))
+ expect(onLink).toHaveBeenCalled()
})
it('shows the status it was handed, not the inventory row own', () => {
@@ -84,10 +106,25 @@ describe('LinkedDevicePanel', () => {
it('skips the rows nothing knows about', () => {
const bare: InventoryDevice = {
id: 'inv2',
- label: 'patch panel',
+ // A row discovery could not even name — nothing to fall back on.
+ label: '',
type: null,
status: 'unknown',
- nodeId: null,
+ nodeId: 'node2',
+ // A node exists, and holds nothing worth printing.
+ node: {
+ id: 'node2',
+ label: null,
+ type: null,
+ ip: null,
+ mac: null,
+ hostname: null,
+ os: null,
+ checkMethod: null,
+ designId: null,
+ designName: null,
+ lastSeen: null,
+ },
racked: false,
suggestedFaceplateId: 'patch-24',
}
diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
index 24ca523..c95adef 100644
--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
@@ -9,6 +9,7 @@ import { useRackStore } from '../store'
const createPending = vi.fn()
const pendingList = vi.fn()
+const deletePending = vi.fn()
vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())
vi.mock('@/api/client', () => ({
@@ -19,6 +20,8 @@ vi.mock('@/api/client', () => ({
// reads `pending_devices` itself rather than the rack's mirrored list.
pending: (...args: unknown[]) => pendingList(...args),
hidden: vi.fn().mockResolvedValue({ data: [] }),
+ // Cleanup after a relink: the placeholder the rack created is dropped.
+ deletePending: (...args: unknown[]) => deletePending(...args),
},
}))
@@ -28,6 +31,7 @@ beforeEach(() => {
vi.clearAllMocks()
store().loadDemo()
pendingList.mockResolvedValue({ data: [] })
+ deletePending.mockResolvedValue({ data: { deleted: true } })
})
/** Shape the Device Inventory modal expects for one of the rack's entries. */
@@ -579,7 +583,7 @@ describe('RackDeviceModal — editing', () => {
render(<RackDeviceModal />)
const entry = store().inventory.find((i) => i.id === 'inv-pve1')!
- const panel = screen.getByLabelText('Logical view')
+ const panel = screen.getByLabelText('Linked device')
expect(panel).toHaveTextContent(entry.node!.hostname!)
expect(panel).toHaveTextContent(entry.ip!)
expect(panel).toHaveTextContent(entry.mac!)
@@ -591,6 +595,91 @@ describe('RackDeviceModal — editing', () => {
render(<RackDeviceModal />)
expect(store().devices.find((d) => d.id === 'dev-shelf')!.deviceId).toBeNull()
- expect(screen.queryByLabelText('Logical view')).not.toBeInTheDocument()
+ expect(screen.queryByLabelText('Linked device')).not.toBeInTheDocument()
+ })
+
+ /** A discovered row, offered in the inventory the picker reads. */
+ function offerScannedRow() {
+ useRackStore.setState((s) => ({
+ inventory: [
+ ...s.inventory,
+ {
+ id: 'inv-scanned',
+ label: 'pdu-real',
+ type: 'pdu',
+ discoverySource: 'arp',
+ ip: '192.168.1.60',
+ mac: null,
+ hostname: 'pdu.lan',
+ os: null,
+ services: [],
+ status: 'online' as const,
+ nodeId: 'node-pdu',
+ node: {
+ id: 'node-pdu',
+ label: 'pdu-main',
+ type: 'pdu',
+ ip: '192.168.1.60',
+ mac: null,
+ hostname: 'pdu.lan',
+ os: null,
+ checkMethod: 'ping',
+ designId: 'demo-network',
+ designName: 'Network',
+ lastSeen: null,
+ },
+ racked: false,
+ suggestedFaceplateId: 'pdu-1u',
+ },
+ ],
+ }))
+ }
+
+ it('repoints a mount at the inventory device the user picks', async () => {
+ // `dev-pdu` was created from the rack: its entry is a placeholder with a
+ // name and nothing else, and no IEEE or IP for the backend to guess from.
+ store().openDeviceEditor('dev-pdu')
+ render(<RackDeviceModal />)
+ expect(screen.getByLabelText('Linked device')).not.toHaveTextContent('pdu.lan')
+
+ act(() => offerScannedRow())
+ fireEvent.click(screen.getByRole('button', { name: /Link to another device/ }))
+ // By role: the plate preview draws the same label in its SVG artwork.
+ const row = await screen.findByRole('button', { name: /pdu-real/ })
+ await act(async () => {
+ fireEvent.click(row)
+ })
+
+ const mount = store().devices.find((d) => d.id === 'dev-pdu')!
+ expect(mount.deviceId).toBe('inv-scanned')
+ expect(mount.nodeId).toBe('node-pdu')
+ expect(screen.getByLabelText('Linked device')).toHaveTextContent('pdu.lan')
+ // The form follows the plate's new name rather than saving the old one back.
+ expect(screen.getByLabelText('Label')).toHaveValue('pdu-real')
+ })
+
+ it('offers "Check device" once a device with a node has been linked', async () => {
+ store().openDeviceEditor('dev-pdu')
+ render(<RackDeviceModal />)
+
+ expect(screen.queryByRole('option', { name: /Check device/ })).not.toBeInTheDocument()
+
+ act(() => offerScannedRow())
+ await act(async () => {
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+ })
+
+ await waitFor(() =>
+ expect(screen.getByRole('option', { name: /Check device/ })).toBeInTheDocument(),
+ )
+ })
+
+ it('does not offer linking while the mount is still being created', async () => {
+ store().openDeviceEditor()
+ render(<RackDeviceModal />)
+ await pickFromInventory('inv-pdu')
+
+ // Nothing to hang a link on yet: the mount does not exist.
+ expect(screen.queryByRole('button', { name: /Link to/ })).not.toBeInTheDocument()
})
})
diff --git a/frontend/src/rack/__tests__/store.test.ts b/frontend/src/rack/__tests__/store.test.ts
index d04d4b3..49a8a25 100644
--- a/frontend/src/rack/__tests__/store.test.ts
+++ b/frontend/src/rack/__tests__/store.test.ts
@@ -1,12 +1,22 @@
-import { describe, it, expect, beforeEach } from 'vitest'
+import { describe, it, expect, beforeEach, vi } from 'vitest'
import { useRackStore } from '../store'
import { getFaceplate } from '../faceplates'
-import { RACK_COLUMNS } from '@/types'
+import { RACK_COLUMNS, type InventoryDevice } from '@/types'
import { MAX_RACK_U, MIN_RACK_U } from '../rackDefaults'
import { demoNetworkLinks } from '../demoData'
const store = () => useRackStore.getState()
+/**
+ * Dropping an inventory entry is the one store action that talks to the
+ * backend; the rest of the demo state is local, so only that call is stubbed.
+ */
+const deletePending = vi.hoisted(() => vi.fn())
+vi.mock('@/api/client', () => ({
+ racksApi: { load: vi.fn(), inventory: vi.fn(), save: vi.fn() },
+ scanApi: { deletePending, createPending: vi.fn() },
+}))
+
beforeEach(() => {
useRackStore.getState().loadDemo()
})
@@ -186,6 +196,147 @@ describe('mounting', () => {
})
})
+describe('relinking a mount to another inventory entry', () => {
+ /** A row discovery filled in: an IP, a MAC and a canvas node behind it. */
+ const scanned: InventoryDevice = {
+ id: 'inv-scanned',
+ label: 'pdu-real',
+ type: 'pdu',
+ discoverySource: 'arp',
+ ip: '192.168.1.60',
+ mac: 'aa:bb:cc:dd:ee:ff',
+ hostname: 'pdu.lan',
+ os: null,
+ services: [],
+ status: 'online',
+ nodeId: 'node-scanned',
+ node: {
+ id: 'node-scanned',
+ label: 'pdu-real',
+ type: 'pdu',
+ ip: '192.168.1.60',
+ mac: 'aa:bb:cc:dd:ee:ff',
+ hostname: 'pdu.lan',
+ os: null,
+ checkMethod: 'ping',
+ designId: 'demo-network',
+ designName: 'Network',
+ lastSeen: null,
+ },
+ racked: false,
+ suggestedFaceplateId: 'pdu-1u',
+ }
+
+ /** Offer `scanned` in the inventory the store holds. */
+ function offer(extra: Partial<InventoryDevice> = {}) {
+ useRackStore.setState((s) => ({ inventory: [...s.inventory, { ...scanned, ...extra }] }))
+ }
+
+ /** Turn `dev-pdu`'s entry into a placeholder the rack created. */
+ function placeholder() {
+ useRackStore.setState((s) => ({
+ inventory: s.inventory.map((i) =>
+ i.id === 'inv-pdu' ? { ...i, discoverySource: 'rack' } : i,
+ ),
+ }))
+ }
+
+ beforeEach(() => {
+ deletePending.mockClear()
+ deletePending.mockResolvedValue({ data: { deleted: true } })
+ })
+
+ it('points the mount at the entry, with its node, status and label', async () => {
+ // `dev-pdu` is dumb hardware: the backend has no IEEE and no IP to guess a
+ // canvas node from, so the link can only ever come from the user.
+ expect(store().devices.find((d) => d.id === 'dev-pdu')!.nodeId).toBeNull()
+ offer()
+
+ expect(await store().relinkDevice('dev-pdu', 'inv-scanned')).toBe(true)
+
+ const mount = store().devices.find((d) => d.id === 'dev-pdu')!
+ expect(mount.deviceId).toBe('inv-scanned')
+ expect(mount.nodeId).toBe('node-scanned')
+ expect(mount.label).toBe('pdu-real')
+ expect(mount.status).toBe('online')
+ // The entry is now taken, so it stops being offered as a fresh mount.
+ expect(store().inventory.find((i) => i.id === 'inv-scanned')!.racked).toBe(true)
+ expect(store().inventory.find((i) => i.id === 'inv-pdu')!.racked).toBe(false)
+ })
+
+ it('keeps a plate the user renamed', async () => {
+ store().updateDevice('dev-pdu', { label: 'PDU (left)' })
+ offer()
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+ expect(store().devices.find((d) => d.id === 'dev-pdu')!.label).toBe('PDU (left)')
+ })
+
+ it('keeps `auto`, which is a choice about how to resolve the status', async () => {
+ store().updateDevice('dev-pdu', { status: 'auto' })
+ offer()
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+ expect(store().devices.find((d) => d.id === 'dev-pdu')!.status).toBe('auto')
+ })
+
+ it('marks the canvas dirty, so the link is saved with the rest', async () => {
+ offer()
+ store().markSaved()
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+ expect(store().hasUnsavedChanges).toBe(true)
+ })
+
+ it('refuses an accessory, which stands for no device', async () => {
+ offer()
+ const id = store().mountAccessory('shelf-1u', 'rack-main', { uStart: 20 })!
+ expect(await store().relinkDevice(id, 'inv-scanned')).toBe(false)
+ expect(store().devices.find((d) => d.id === id)!.deviceId).toBeNull()
+ })
+
+ it('refuses an entry another plate already stands for', async () => {
+ const taken = store().devices.find((d) => d.id === 'dev-nas')!.deviceId!
+ expect(await store().relinkDevice('dev-pdu', taken)).toBe(false)
+ expect(store().devices.find((d) => d.id === 'dev-pdu')!.deviceId).toBe('inv-pdu')
+ })
+
+ it('refuses an entry the inventory does not hold', async () => {
+ expect(await store().relinkDevice('dev-pdu', 'inv-ghost')).toBe(false)
+ })
+
+ it('deletes the placeholder the rack created and left behind', async () => {
+ placeholder()
+ offer()
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+
+ expect(deletePending).toHaveBeenCalledWith('inv-pdu')
+ expect(store().inventory.some((i) => i.id === 'inv-pdu')).toBe(false)
+ })
+
+ it('keeps a discovered entry the mount leaves behind', async () => {
+ offer()
+ await store().relinkDevice('dev-pdu', 'inv-scanned')
+
+ expect(deletePending).not.toHaveBeenCalled()
+ // Still there, and free to be mounted again.
+ expect(store().inventory.find((i) => i.id === 'inv-pdu')!.racked).toBe(false)
+ })
+
+ it('keeps the placeholder when the backend refuses to delete it', async () => {
+ deletePending.mockRejectedValue(new Error('409'))
+ placeholder()
+ offer()
+
+ // The relink itself still stands — only the cleanup failed.
+ expect(await store().relinkDevice('dev-pdu', 'inv-scanned')).toBe(true)
+ expect(store().inventory.some((i) => i.id === 'inv-pdu')).toBe(true)
+ })
+
+ it('refuses to discard an entry a plate still stands for', async () => {
+ placeholder()
+ expect(await store().discardInventoryDevice('inv-pdu')).toBe(false)
+ expect(deletePending).not.toHaveBeenCalled()
+ })
+})
+
describe('moving and resizing', () => {
it('refuses a move onto an occupied slot', () => {
const target = store().devices.find((d) => d.id === 'dev-sw24')!
diff --git a/frontend/src/rack/components/DevicePickerModal.tsx b/frontend/src/rack/components/DevicePickerModal.tsx
new file mode 100644
index 0000000..761e075
--- /dev/null
+++ b/frontend/src/rack/components/DevicePickerModal.tsx
@@ -0,0 +1,147 @@
+/**
+ * Pick the Device Inventory entry a mount stands for.
+ *
+ * A plate created from the rack carries a placeholder entry with nothing in it
+ * but a name, and discovery only *guesses* the canvas node behind an entry
+ * (IEEE, then IP) — so a device it cannot correlate stays bare however complete
+ * its twin is. This is the way in: point the plate at the inventory row that
+ * already holds the IP, the MAC, the services and, when there is one, the
+ * canvas node.
+ *
+ * The list is the Device Inventory itself, not the logical canvases: an entry
+ * no one ever approved onto a canvas is still the record of a real box, and is
+ * exactly what a rack is built out of.
+ */
+import { useEffect, useMemo, useState } from 'react'
+import { Search } from 'lucide-react'
+import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
+import { useRackStore } from '../store'
+import { useRackPalette } from '../rackTheme'
+import type { InventoryDevice } from '@/types'
+
+/** Discovery labels, as the Device Inventory prints them. */
+const SOURCE_LABELS: Record<string, string> = {
+ arp: 'Network scan',
+ proxmox: 'Proxmox',
+ zigbee: 'Zigbee',
+ zwave: 'Z-Wave',
+ manual: 'Added by hand',
+ rack: 'Rack device',
+}
+
+function sourceLabel(source: string | null | undefined): string | null {
+ if (!source) return null
+ return SOURCE_LABELS[source] ?? source
+}
+
+function matches(item: InventoryDevice, query: string): boolean {
+ if (!query) return true
+ const q = query.toLowerCase()
+ return [
+ item.label,
+ item.type,
+ item.ip,
+ item.hostname,
+ item.mac,
+ item.node?.designName,
+ sourceLabel(item.discoverySource),
+ ].some((v) => v?.toLowerCase().includes(q))
+}
+
+interface Props {
+ open: boolean
+ /** Entry the mount already points at, highlighted in the list. */
+ value?: string | null
+ onPick: (entry: InventoryDevice) => void
+ onClose: () => void
+}
+
+export function DevicePickerModal({ open, value, onPick, onClose }: Props) {
+ const palette = useRackPalette()
+ const inventory = useRackStore((s) => s.inventory)
+ const refreshInventory = useRackStore((s) => s.refreshInventory)
+ const [query, setQuery] = useState('')
+
+ // The Device Inventory lives outside the rack — a scan, an approval or a
+ // rename can land while this modal's parent stays open.
+ useEffect(() => {
+ if (open) void refreshInventory()
+ }, [open, refreshInventory])
+
+ // One entry, one mount: a device already on a plate in this design is not on
+ // offer, or two plates would follow the same box.
+ const visible = useMemo(
+ () => inventory.filter((i) => (!i.racked || i.id === value) && matches(i, query)),
+ [inventory, value, query],
+ )
+
+ return (
+ <Dialog open={open} onOpenChange={(o) => !o && onClose()}>
+ <DialogContent className="border-[#30363d] bg-[#161b22] text-foreground max-w-[calc(100%-2rem)] sm:max-w-xl max-h-[80vh] overflow-y-auto">
+ <DialogHeader>
+ <DialogTitle className="text-sm font-semibold">Link to an inventory device</DialogTitle>
+ </DialogHeader>
+
+ <div className="relative">
+ <Search
+ size={13}
+ className="pointer-events-none absolute left-2 top-1/2 -translate-y-1/2 text-muted-foreground"
+ />
+ <input
+ autoFocus
+ aria-label="Search devices"
+ value={query}
+ onChange={(e) => setQuery(e.target.value)}
+ placeholder="Search by name, IP, hostname or source…"
+ className="w-full rounded border border-[#30363d] bg-[#21262d] py-1 pl-7 pr-2 text-sm text-foreground outline-none focus:border-[#00d4ff]"
+ />
+ </div>
+
+ {visible.length === 0 && (
+ <p className="text-[11px] text-muted-foreground">
+ {inventory.length === 0
+ ? 'The Device Inventory is empty. Run a scan or add a device by hand.'
+ : 'No device matches that search.'}
+ </p>
+ )}
+
+ <ul className="flex max-h-[50vh] flex-col gap-1 overflow-y-auto">
+ {visible.map((item) => {
+ const source = sourceLabel(item.discoverySource)
+ // Where the logical twin is drawn, when discovery found one — the
+ // reason two look-alike entries are not the same device.
+ const canvas = item.node?.designName ?? null
+ return (
+ <li key={item.id}>
+ <button
+ type="button"
+ onClick={() => onPick(item)}
+ className={`flex w-full cursor-pointer items-center gap-2 rounded border px-2 py-1.5 text-left hover:border-[#00d4ff] ${
+ item.id === value ? 'border-[#00d4ff]' : 'border-[#30363d]'
+ }`}
+ >
+ <span
+ aria-hidden
+ className="inline-block h-2 w-2 shrink-0 rounded-full"
+ style={{ backgroundColor: palette.status[item.status] }}
+ />
+ <span className="flex min-w-0 flex-1 flex-col">
+ <span className="truncate text-sm">{item.label}</span>
+ <span className="truncate text-[11px] text-muted-foreground">
+ {[item.type, source, canvas].filter(Boolean).join(' · ')}
+ </span>
+ </span>
+ {(item.ip || item.mac) && (
+ <span className="shrink-0 font-mono text-[11px] text-muted-foreground">
+ {item.ip || item.mac}
+ </span>
+ )}
+ </button>
+ </li>
+ )
+ })}
+ </ul>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/frontend/src/rack/components/LinkedDevicePanel.tsx b/frontend/src/rack/components/LinkedDevicePanel.tsx
index e2b516a..0ab37f6 100644
--- a/frontend/src/rack/components/LinkedDevicePanel.tsx
+++ b/frontend/src/rack/components/LinkedDevicePanel.tsx
@@ -1,14 +1,15 @@
/**
- * What the logical canvas knows about a mounted device.
+ * What is known about the device a mount stands for.
*
* A mount points at a Device Inventory entry, which the backend correlates with
- * a canvas node (IEEE, then IP). Everything here is read-only: the logical view
- * owns these facts, the rack only prints them so the user does not have to open
- * the other canvas to read an IP off it.
+ * a canvas node (IEEE, then IP) when it can. Everything here is read-only: the
+ * inventory and the logical canvas own these facts, the rack only prints them
+ * so the user does not have to open the other canvas to read an IP off it.
*
* Node values win over the inventory row's — the node is the record the user
* curates, the inventory row is what discovery last saw — and each row is
- * dropped when neither side has anything to show.
+ * dropped when neither side has anything to show. A device on no canvas still
+ * prints everything discovery found; only the canvas-side rows go missing.
*/
import { useRackPalette } from '../rackTheme'
import type { DeviceStatus, InventoryDevice } from '@/types'
@@ -43,11 +44,18 @@ function serviceLabel(service: { port: number | null; name: string | null }): st
export function LinkedDevicePanel({
entry,
status,
+ onLink,
}: {
/** The inventory row behind the mount. Absent for accessories. */
entry: InventoryDevice | null | undefined
/** Status already resolved for the plate, so both agree on `auto`. */
status: DeviceStatus
+ /**
+ * Opens the inventory picker. Omitted when relinking is not on offer — a
+ * mount that does not exist yet has nothing to hang a link on, and an
+ * accessory stands for no device.
+ */
+ onLink?: () => void
}) {
const palette = useRackPalette()
if (!entry) return null
@@ -58,7 +66,7 @@ export function LinkedDevicePanel({
if (value) rows.push({ label, value, mono })
}
- push('Canvas name', firstOf(node?.label))
+ push('Name', firstOf(node?.label, entry.label))
push('Type', firstOf(node?.type, entry.type))
push('Hostname', firstOf(node?.hostname, entry.hostname))
push('IP', firstOf(node?.ip, entry.ip), true)
@@ -70,28 +78,26 @@ export function LinkedDevicePanel({
const services = entry.services ?? []
+ const header = (
+ <header className="mb-2 flex items-center justify-between gap-2">
+ <span className="text-xs font-medium">Linked device</span>
+ <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
+ <span
+ aria-hidden
+ className="inline-block h-2 w-2 rounded-full"
+ style={{ backgroundColor: palette.status[status] }}
+ />
+ {status}
+ </span>
+ </header>
+ )
+
return (
<section
- aria-label="Logical view"
+ aria-label="Linked device"
className="rounded border border-[#30363d] bg-[#0d1117] p-2.5"
>
- <header className="mb-2 flex items-center justify-between gap-2">
- <span className="text-xs font-medium">Logical view</span>
- <span className="flex items-center gap-1.5 text-[11px] text-muted-foreground">
- <span
- aria-hidden
- className="inline-block h-2 w-2 rounded-full"
- style={{ backgroundColor: palette.status[status] }}
- />
- {status}
- </span>
- </header>
-
- {!node && (
- <p className="mb-2 text-[11px] text-muted-foreground">
- Not on a logical canvas — the facts below are what discovery reported.
- </p>
- )}
+ {header}
{rows.length === 0 && (
<p className="text-[11px] text-muted-foreground">
@@ -125,6 +131,26 @@ export function LinkedDevicePanel({
</ul>
</div>
)}
+
+ {/* Discovery only guesses the canvas node behind an entry, so saying so is
+ part of the reading: no canvas node means `auto` status resolves to
+ `unknown` and no link can be imported. */}
+ {!node && (
+ <p className="mt-2 text-[11px] text-muted-foreground">Not on a logical canvas.</p>
+ )}
+
+ {/* The device behind a plate is a choice — a placeholder created from the
+ rack, or the wrong twin of two look-alikes — so it must be changeable
+ from where it is read. */}
+ {onLink && (
+ <button
+ type="button"
+ onClick={onLink}
+ className="mt-2 cursor-pointer text-[11px] text-[#00d4ff] hover:underline"
+ >
+ Link to another device…
+ </button>
+ )}
</section>
)
}
diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsx
index f905b1d..cd1237c 100644
--- a/frontend/src/rack/components/RackDeviceModal.tsx
+++ b/frontend/src/rack/components/RackDeviceModal.tsx
@@ -16,12 +16,13 @@ import { toast } from 'sonner'
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
import { Label } from '@/components/ui/label'
-import { PendingDevicesModal } from '@/components/modals/PendingDevicesModal'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import { DeviceInventoryModal } from '@/components/modals/DeviceInventoryModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
import { useRackStore } from '../store'
import { FaceplatePicker } from './FaceplatePicker'
import { Faceplate } from './Faceplate'
import { LinkedDevicePanel } from './LinkedDevicePanel'
+import { DevicePickerModal } from './DevicePickerModal'
import { deviceTypeForFaceplate, getFaceplate } from '../faceplates'
import { findSlot } from '../layout'
import { canFollowNode, resolveDeviceStatus } from '../deviceStatus'
@@ -85,6 +86,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
const createInventoryDevice = useRackStore((s) => s.createInventoryDevice)
const applyFaceplate = useRackStore((s) => s.applyFaceplate)
const updateDevice = useRackStore((s) => s.updateDevice)
+ const relinkDevice = useRackStore((s) => s.relinkDevice)
const unmountDevice = useRackStore((s) => s.unmountDevice)
const setPorts = useRackStore((s) => s.setPorts)
@@ -111,6 +113,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
const [plateChanged, setPlateChanged] = useState(false)
const [pickerOpen, setPickerOpen] = useState(false)
const [inventoryPickerOpen, setInventoryPickerOpen] = useState(false)
+ const [devicePickerOpen, setDevicePickerOpen] = useState(false)
const [busy, setBusy] = useState(false)
// The inventory lives in the Device Inventory, which the user can edit from
@@ -172,7 +175,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
* (added since this form opened, or a kind no rack can hold). Refetch once
* before refusing, and never mount a device twice in the same design.
*/
- async function handlePickFromInventory(picked: PendingDevice) {
+ async function handlePickFromInventory(picked: InventoryEntry) {
let entry = inventory.find((i) => i.id === picked.id)
if (!entry) {
await refreshInventory()
@@ -190,6 +193,33 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
setInventoryPickerOpen(false)
}
+ /**
+ * Repointing needs a mount to repoint: a device being created has none yet,
+ * and an accessory stands for no hardware at all.
+ */
+ const canRelink = isEdit && !!device?.deviceId
+
+ /**
+ * Another inventory entry, picked by hand.
+ *
+ * Applied straight away rather than on Save: the panel, the Status select and
+ * the plate LED all read the link from the store, and the picker is an
+ * explicit action of its own. It is persisted with the rest of the canvas on
+ * the next save, like every other rack edit.
+ */
+ async function handleRelink(entry: InventoryDevice) {
+ setDevicePickerOpen(false)
+ if (!device) return
+ if (await relinkDevice(device.id, entry.id)) {
+ // The plate may have taken the entry's name; keep the open form in step.
+ const next = useRackStore.getState().devices.find((d) => d.id === device.id)
+ if (next) setLabel(next.label)
+ toast.success(`Linked to ${entry.label}`)
+ } else {
+ toast.error(`${entry.label} is already mounted in this design`)
+ }
+ }
+
/**
* The Device Inventory row behind this mount: the entry being picked while
* adding, the one the mount was created from while editing.
@@ -405,7 +435,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
{/* Rendered inside this DialogContent on purpose: an open Base UI
dialog marks outside content inert, so a sibling overlay would
be unclickable. */}
- <PendingDevicesModal
+ <DeviceInventoryModal
open={inventoryPickerOpen}
onClose={() => setInventoryPickerOpen(false)}
onPick={(d) => void handlePickFromInventory(d)}
@@ -653,7 +683,22 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
{/* The column below the port list used to be dead space. A mount
that stands for an inventory entry fills it with what the
logical canvas knows about the same box. */}
- <LinkedDevicePanel entry={mountEntry} status={previewStatus} />
+ <LinkedDevicePanel
+ entry={mountEntry}
+ status={previewStatus}
+ onLink={canRelink ? () => setDevicePickerOpen(true) : undefined}
+ />
+ {canRelink && devicePickerOpen && (
+ /* Inside this DialogContent for the same reason as the inventory
+ picker: an open Base UI dialog makes outside content inert.
+ Mounted per opening, so the inventory is fetched fresh. */
+ <DevicePickerModal
+ open={devicePickerOpen}
+ value={device?.deviceId}
+ onPick={handleRelink}
+ onClose={() => setDevicePickerOpen(false)}
+ />
+ )}
</div>
</div>
diff --git a/frontend/src/rack/store.ts b/frontend/src/rack/store.ts
index e926733..77017e5 100644
--- a/frontend/src/rack/store.ts
+++ b/frontend/src/rack/store.ts
@@ -171,6 +171,29 @@ interface RackState {
* the rack had no room at all and nothing changed.
*/
updateDevice: (id: string, patch: Partial<Omit<RackDevice, 'id' | 'ports'>>) => boolean
+ /**
+ * Point a mount at another Device Inventory entry, picked by hand.
+ *
+ * A mount created from the rack carries a placeholder entry of its own, and
+ * discovery only *guesses* the canvas node behind an entry (IEEE, then IP) —
+ * so the way to give a plate real facts is to point it at the inventory row
+ * discovery already filled in. The mount adopts that row's node, status and
+ * (unless the user renamed the plate) label.
+ *
+ * The placeholder left behind is deleted when the rack created it and no
+ * other mount uses it; a row from discovery or from the user is never touched.
+ * `false` means the target is not a device mount, the entry is unknown, or it
+ * is already mounted elsewhere in this design.
+ */
+ relinkDevice: (deviceId: string, entryId: string) => Promise<boolean>
+ /**
+ * Drop an inventory entry the rack created and no longer mounts.
+ *
+ * Deletes the Device Inventory row for real, so it stops showing under the
+ * **Rack devices** filter. Refuses any row the rack did not create, and any
+ * row a mount still stands for. Not an edit of the canvas — nothing to save.
+ */
+ discardInventoryDevice: (entryId: string) => Promise<boolean>
/** Unmounts from the rack. The inventory entry survives. */
unmountDevice: (id: string) => void
/** Swaps the plate, resizing to its U height — relocating if need be. */
@@ -362,6 +385,9 @@ export const useRackStore = create<RackState>((set, get) => {
id: generateUUID(),
label,
type,
+ // What the POST below files it under, mirrored locally so a relink can
+ // tell this placeholder from a row discovery or the user owns.
+ discoverySource: 'rack',
ip,
status: 'unknown',
nodeId: null,
@@ -578,6 +604,69 @@ export const useRackStore = create<RackState>((set, get) => {
return true
},
+ relinkDevice: async (deviceId, entryId) => {
+ const { devices, inventory } = get()
+ const device = devices.find((d) => d.id === deviceId)
+ // Accessories are rack furniture with no inventory row behind them, so
+ // there is nothing to repoint.
+ if (!device?.deviceId) return false
+ const entry = inventory.find((i) => i.id === entryId)
+ if (!entry) return false
+ if (entry.id === device.deviceId) return true
+ // One inventory entry, one mount: two plates claiming the same device
+ // would both follow its status and both answer to its links.
+ if (devices.some((d) => d.id !== deviceId && d.deviceId === entry.id)) return false
+
+ const previous = inventory.find((i) => i.id === device.deviceId)
+ edit((s) => {
+ const next = s.devices.map((d) =>
+ d.id === deviceId
+ ? {
+ ...d,
+ deviceId: entry.id,
+ nodeId: entry.nodeId,
+ // A plate the user renamed keeps its name; one still wearing the
+ // old entry's name follows the new entry, or the rename would
+ // have to be undone by hand every time.
+ label: !previous || d.label === previous.label ? entry.label : d.label,
+ // `auto` is a choice about *how* to resolve the status, not a
+ // status — it survives the swap; a pinned colour follows the
+ // entry, as it did when the mount was created.
+ status: d.status === 'auto' ? d.status : entry.status,
+ }
+ : d,
+ )
+ return { devices: next, inventory: withRackedFlags(s.inventory, next) }
+ })
+
+ // The placeholder the rack created for this plate now stands for nothing.
+ // `discardInventoryDevice` re-reads the state this edit just wrote, so it
+ // sees the mount already repointed and only the rows it owns.
+ if (previous) await get().discardInventoryDevice(previous.id)
+ return true
+ },
+
+ discardInventoryDevice: async (entryId) => {
+ const { devices, inventory } = get()
+ const entry = inventory.find((i) => i.id === entryId)
+ // Never delete a row another plate still stands for, and never one the
+ // rack did not create — discovery and the user own theirs.
+ if (!entry || entry.discoverySource !== 'rack') return false
+ if (devices.some((d) => d.deviceId === entryId)) return false
+
+ if (!STANDALONE) {
+ try {
+ await scanApi.deletePending(entryId)
+ } catch {
+ // The row survives in the Device Inventory, where the user can remove
+ // it; the relink that triggered this already stands.
+ return false
+ }
+ }
+ set((s) => ({ inventory: s.inventory.filter((i) => i.id !== entryId) }))
+ return true
+ },
+
unmountDevice: (id) =>
edit((s) => {
const devices = s.devices.filter((d) => d.id !== id)
diff --git a/frontend/src/types/rack.ts b/frontend/src/types/rack.ts
index cf5c7f8..b1db91e 100644
--- a/frontend/src/types/rack.ts
+++ b/frontend/src/types/rack.ts
@@ -241,6 +241,15 @@ export interface InventoryDevice {
label: string
/** `suggested_type` from discovery; free-form, may be unknown to the UI. */
type: string | null
+ /**
+ * How the entry got into the inventory: `arp`, `proxmox`, `zigbee`, `manual`,
+ * or `rack` for gear the rack canvas created itself.
+ *
+ * The rack only reads it to know which rows it owns: relinking a mount to
+ * another entry discards the placeholder it created, and never a row
+ * discovery or the user put there.
+ */
+ discoverySource?: string | null
ip?: string | null
/** MAC, or the IEEE address for a mesh device. */
mac?: string | null
diff --git a/frontend/src/utils/__tests__/pendingSources.test.ts b/frontend/src/utils/__tests__/deviceSources.test.ts
similarity index 93%
rename from frontend/src/utils/__tests__/pendingSources.test.ts
rename to frontend/src/utils/__tests__/deviceSources.test.ts
index a0f862e..6b3b70c 100644
--- a/frontend/src/utils/__tests__/pendingSources.test.ts
+++ b/frontend/src/utils/__tests__/deviceSources.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect } from 'vitest'
-import { sourceBuckets, orderedSources, isRackDevice } from '../pendingSources'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import { sourceBuckets, orderedSources, isRackDevice } from '../deviceSources'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
-function device(overrides: Partial<PendingDevice> = {}): PendingDevice {
+function device(overrides: Partial<InventoryEntry> = {}): InventoryEntry {
return {
id: 'd1',
ip: null,
diff --git a/frontend/src/utils/__tests__/rackable.test.ts b/frontend/src/utils/__tests__/rackable.test.ts
index 3e81b30..f3b28ee 100644
--- a/frontend/src/utils/__tests__/rackable.test.ts
+++ b/frontend/src/utils/__tests__/rackable.test.ts
@@ -1,8 +1,8 @@
import { describe, it, expect } from 'vitest'
import { isRackable, UNRACKABLE_TYPES } from '../rackable'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
-function device(suggested_type: string | null): PendingDevice {
+function device(suggested_type: string | null): InventoryEntry {
return {
id: 'd1',
ip: null,
diff --git a/frontend/src/utils/pendingSources.ts b/frontend/src/utils/deviceSources.ts
similarity index 89%
rename from frontend/src/utils/pendingSources.ts
rename to frontend/src/utils/deviceSources.ts
index 51323f1..8c99b6a 100644
--- a/frontend/src/utils/pendingSources.ts
+++ b/frontend/src/utils/deviceSources.ts
@@ -5,7 +5,7 @@
* raw list to the UI's filter/badge buckets so a merged device shows under each
* matching filter and renders one badge per source.
*/
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
export type SourceBucket = 'ip' | 'zigbee' | 'zwave' | 'proxmox' | 'rack'
@@ -22,7 +22,7 @@ const SOURCE_ORDER: SourceBucket[] = ['ip', 'proxmox', 'zigbee', 'zwave', 'rack'
/** Every source bucket that has observed this device. A device found by both an
* IP scan and a Proxmox import returns {ip, proxmox}. */
-export function sourceBuckets(d: PendingDevice): Set<SourceBucket> {
+export function sourceBuckets(d: InventoryEntry): Set<SourceBucket> {
const raw = d.discovery_sources && d.discovery_sources.length > 0
? d.discovery_sources
: d.discovery_source ? [d.discovery_source] : []
@@ -49,12 +49,12 @@ export function sourceBuckets(d: PendingDevice): Set<SourceBucket> {
* patch panel, a shelf), so it is never placed on a logical canvas — the
* approve paths refuse it on both sides of the wire.
*/
-export function isRackDevice(d: PendingDevice): boolean {
+export function isRackDevice(d: InventoryEntry): boolean {
return sourceBuckets(d).has('rack')
}
/** Ordered bucket list for badge rendering. */
-export function orderedSources(d: PendingDevice): SourceBucket[] {
+export function orderedSources(d: InventoryEntry): SourceBucket[] {
const buckets = sourceBuckets(d)
return SOURCE_ORDER.filter((b) => buckets.has(b))
}
diff --git a/frontend/src/utils/rackSerializer.ts b/frontend/src/utils/rackSerializer.ts
index 9c3a415..486956f 100644
--- a/frontend/src/utils/rackSerializer.ts
+++ b/frontend/src/utils/rackSerializer.ts
@@ -279,6 +279,7 @@ export function toInventoryDevice(api: ApiInventoryItem): InventoryDevice {
id: api.id,
label: api.label,
type: api.suggested_type,
+ discoverySource: api.discovery_source,
ip: api.ip,
mac: api.mac ?? null,
hostname: api.hostname ?? null,
diff --git a/frontend/src/utils/rackable.ts b/frontend/src/utils/rackable.ts
index 0f88bf8..1bb77d5 100644
--- a/frontend/src/utils/rackable.ts
+++ b/frontend/src/utils/rackable.ts
@@ -13,7 +13,7 @@
* the backend suite when the two drift. Keeping them equal is what makes the
* inventory modal's Rackable filter show exactly the rows the rack tray offers.
*/
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
export const UNRACKABLE_TYPES = new Set([
'vm',
@@ -35,6 +35,6 @@ export const UNRACKABLE_TYPES = new Set([
'zwave_enddevice',
])
-export function isRackable(device: PendingDevice): boolean {
+export function isRackable(device: InventoryEntry): boolean {
return !device.suggested_type || !UNRACKABLE_TYPES.has(device.suggested_type)
}
diff --git a/frontend/src/walkthrough/demoTourData.ts b/frontend/src/walkthrough/demoTourData.ts
index 671f0f6..be36487 100644
--- a/frontend/src/walkthrough/demoTourData.ts
+++ b/frontend/src/walkthrough/demoTourData.ts
@@ -1,5 +1,5 @@
import type { ScanRun } from '@/components/modals/ScanHistoryModal'
-import type { PendingDevice } from '@/components/modals/PendingDeviceModal'
+import type { InventoryEntry } from '@/components/modals/InventoryDeviceModal'
/**
* Canned data injected into the real modals during the tour, so the demo steps
@@ -29,7 +29,7 @@ export const DEMO_SCAN_RUNS: ScanRun[] = [
},
]
-export const DEMO_PENDING_DEVICES: PendingDevice[] = [
+export const DEMO_INVENTORY_DEVICES: InventoryEntry[] = [
{
id: 'tour-dev-1',
ip: '192.168.1.20',