Skip to content

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

feat(imports): link a canvas-direct import to its Device Inventory row

Pouzor2413ac3950d5
diff --git a/backend/app/api/routes/proxmox.py b/backend/app/api/routes/proxmox.py
index 267d2b6..fb8ab44 100644
--- a/backend/app/api/routes/proxmox.py
+++ b/backend/app/api/routes/proxmox.py
@@ -34,6 +34,7 @@ from app.schemas.proxmox import (
)
from app.schemas.scan import ScanRunResponse
from app.services.discovery_sources import add_source
+from app.services.inventory_sync import attach_device_ids
from app.services.mac_utils import normalize_mac
from app.services.node_dedupe import dedupe_nodes_by_device
from app.services.proxmox_service import (
@@ -88,6 +89,7 @@ async def test_connection_endpoint(
@router.post("/import", response_model=ProxmoxImportResponse)
async def import_proxmox(
payload: ProxmoxConnectionRequest,
+ db: AsyncSession = Depends(get_db),
_: str = Depends(get_current_user),
) -> ProxmoxImportResponse:
"""Fetch the inventory and return nodes + edges ready for canvas drop."""
@@ -108,6 +110,12 @@ async def import_proxmox(
logger.exception("Unexpected error during Proxmox import")
raise HTTPException(status_code=500, detail="Unexpected error during Proxmox import") from exc
+ # A canvas import is an import: the guests land in the Device Inventory too,
+ # and each node carries the id of the row it draws so the canvas save links
+ # to it instead of minting a second row for the same guest.
+ await _persist_pending_import(db, nodes_raw, edges_raw)
+ nodes_raw = await attach_device_ids(db, nodes_raw)
+
nodes = [ProxmoxNodeOut(**n) for n in nodes_raw]
edges = [ProxmoxEdgeOut(**e) for e in edges_raw]
return ProxmoxImportResponse(nodes=nodes, edges=edges, device_count=len(nodes))
diff --git a/backend/app/api/routes/zigbee.py b/backend/app/api/routes/zigbee.py
index b2dd02b..23bed90 100644
--- a/backend/app/api/routes/zigbee.py
+++ b/backend/app/api/routes/zigbee.py
@@ -30,6 +30,7 @@ from app.schemas.zigbee import (
ZigbeeTestConnectionResponse,
)
from app.services.import_jobs import create_job, fail_job, finish_job, get_job
+from app.services.inventory_sync import attach_device_ids
from app.services.node_dedupe import dedupe_nodes_by_device
from app.services.zigbee_service import (
build_zigbee_properties,
@@ -130,6 +131,18 @@ async def _background_canvas_import(job_id: str, payload: ZigbeeImportRequest) -
fail_job(job_id, detail, status)
return
+ # A canvas import is an import: the devices land in the Device Inventory
+ # too, and each node carries the id of the row it draws so the canvas save
+ # links to it instead of minting a second, IEEE-less row.
+ try:
+ async with AsyncSessionLocal() as db:
+ await _persist_pending_import(db, nodes_raw, edges_raw)
+ nodes_raw = await attach_device_ids(db, nodes_raw)
+ except Exception as exc:
+ status, detail = _import_error(exc)
+ fail_job(job_id, detail, status)
+ return
+
nodes = [ZigbeeNodeOut(**n) for n in nodes_raw]
edges = [ZigbeeEdgeOut(**e) for e in edges_raw]
finish_job(
diff --git a/backend/app/api/routes/zwave.py b/backend/app/api/routes/zwave.py
index 2ae7b7b..cbc2b7c 100644
--- a/backend/app/api/routes/zwave.py
+++ b/backend/app/api/routes/zwave.py
@@ -27,6 +27,7 @@ from app.schemas.zwave import (
ZwaveTestConnectionRequest,
ZwaveTestConnectionResponse,
)
+from app.services.inventory_sync import attach_device_ids
from app.services.node_dedupe import dedupe_nodes_by_device
from app.services.zwave_service import (
build_zwave_properties,
@@ -51,6 +52,7 @@ router = APIRouter()
@router.post("/import", response_model=ZwaveImportResponse)
async def import_zwave_network(
payload: ZwaveImportRequest,
+ db: AsyncSession = Depends(get_db),
_: str = Depends(get_current_user),
) -> ZwaveImportResponse:
"""Fetch the Z-Wave node list and return nodes + edges ready for canvas drop.
@@ -82,6 +84,12 @@ async def import_zwave_network(
logger.exception("Unexpected error during Z-Wave import")
raise HTTPException(status_code=500, detail="Unexpected error during Z-Wave import") from exc
+ # A canvas import is an import: the devices land in the Device Inventory too,
+ # and each node carries the id of the row it draws so the canvas save links
+ # to it instead of minting a second, IEEE-less row.
+ await _persist_pending_import(db, nodes_raw, edges_raw)
+ nodes_raw = await attach_device_ids(db, nodes_raw)
+
nodes = [ZwaveNodeOut(**n) for n in nodes_raw]
edges = [ZwaveEdgeOut(**e) for e in edges_raw]
return ZwaveImportResponse(nodes=nodes, edges=edges, device_count=len(nodes))
diff --git a/backend/app/schemas/proxmox.py b/backend/app/schemas/proxmox.py
index cdeb13a..49f1e34 100644
--- a/backend/app/schemas/proxmox.py
+++ b/backend/app/schemas/proxmox.py
@@ -41,6 +41,10 @@ class ProxmoxNodeOut(BaseModel):
vendor: str | None = None
model: str | None = None
parent_ieee: str | None = None
+ # The Device Inventory row this node draws, stamped by the import. The
+ # canvas carries it back on save so the node links to that row rather
+ # than minting a second one for the same device.
+ device_id: str | None = None
class ProxmoxEdgeOut(BaseModel):
diff --git a/backend/app/schemas/zigbee.py b/backend/app/schemas/zigbee.py
index 2edc84e..e6851ee 100644
--- a/backend/app/schemas/zigbee.py
+++ b/backend/app/schemas/zigbee.py
@@ -60,6 +60,10 @@ class ZigbeeNodeOut(BaseModel):
vendor: str | None = None
lqi: int | None = None
parent_id: str | None = None
+ # The Device Inventory row this node draws, stamped by the import. The
+ # canvas carries it back on save so the node links to that row rather
+ # than minting a second one for the same device.
+ device_id: str | None = None
class ZigbeeEdgeOut(BaseModel):
diff --git a/backend/app/schemas/zwave.py b/backend/app/schemas/zwave.py
index 34d1b0b..22b13e3 100644
--- a/backend/app/schemas/zwave.py
+++ b/backend/app/schemas/zwave.py
@@ -50,6 +50,10 @@ class ZwaveNodeOut(BaseModel):
vendor: str | None = None
lqi: int | None = None
parent_id: str | None = None
+ # The Device Inventory row this node draws, stamped by the import. The
+ # canvas carries it back on save so the node links to that row rather
+ # than minting a second one for the same device.
+ device_id: str | None = None
class ZwaveEdgeOut(BaseModel):
diff --git a/backend/app/services/inventory_sync.py b/backend/app/services/inventory_sync.py
index 143d6b9..53f0165 100644
--- a/backend/app/services/inventory_sync.py
+++ b/backend/app/services/inventory_sync.py
@@ -612,6 +612,12 @@ async def link_facts(
)
device.discovery_sources = add_source(device.discovery_sources, CANVAS_SOURCE)
+ # A row a node draws is past the pending queue — the mirror of the
+ # "approved but no longer drawn -> pending" revival the imports do. A hidden
+ # row stays hidden: the user hid it on purpose.
+ if device.status == "pending":
+ device.status = "approved"
+
node.device_id = device.id
# Order and visibility are this node's, not the device's, so they are taken
# from the full payload — never from the `changed_fields`/`only_changed`
@@ -981,3 +987,27 @@ async def backfill_node_devices(db: AsyncSession) -> dict[str, int]:
await db.flush()
return {"linked": linked, "created": created, "merged": merged, "skipped": skipped}
+
+
+async def attach_device_ids(
+ db: AsyncSession, nodes_raw: list[dict[str, Any]]
+) -> list[dict[str, Any]]:
+ """Stamp each imported node with the inventory row that already owns it.
+
+ A canvas-direct import upserts the inventory first, so the node dropped on
+ the canvas can point straight at that row instead of minting a second one
+ on the next save. Matching goes through :func:`find_device_for`, so a
+ Proxmox guest merged into a scanned row by ip/mac resolves too.
+
+ Returns new dicts — the caller's payload is left untouched.
+ """
+ stamped: list[dict[str, Any]] = []
+ for node in nodes_raw:
+ device = await find_device_for(
+ db,
+ ip=node.get("ip"),
+ mac=node.get("mac"),
+ ieee=node.get("ieee_address"),
+ )
+ stamped.append({**node, "device_id": device.id} if device else dict(node))
+ return stamped
diff --git a/backend/tests/test_inventory_sync.py b/backend/tests/test_inventory_sync.py
index e444051..9ed7260 100644
--- a/backend/tests/test_inventory_sync.py
+++ b/backend/tests/test_inventory_sync.py
@@ -279,6 +279,38 @@ class TestIeeeCollisions:
assert device is not None and device.ieee_address == "0xAAA"
+
+
+class TestStatusOnLink:
+ """A row a node draws is past the pending queue."""
+
+ @pytest.mark.asyncio
+ async def test_pending_row_is_approved_once_a_node_draws_it(self, db_session):
+ design = await _design(db_session)
+ db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", status="pending"))
+ node = _node(design)
+ db_session.add(node)
+ await db_session.commit()
+
+ device = await link_facts(db_session, node, {"ip": "10.0.0.5"})
+ await db_session.commit()
+
+ assert device is not None and device.status == "approved"
+
+ @pytest.mark.asyncio
+ async def test_hidden_row_stays_hidden(self, db_session):
+ """The user hid it on purpose — drawing it does not undo that."""
+ design = await _design(db_session)
+ db_session.add(InventoryDevice(id="d-1", ip="10.0.0.5", status="hidden"))
+ node = _node(design)
+ db_session.add(node)
+ await db_session.commit()
+
+ device = await link_facts(db_session, node, {"ip": "10.0.0.5"})
+ await db_session.commit()
+
+ assert device is not None and device.status == "hidden"
+
# --- the backfill -----------------------------------------------------------
diff --git a/backend/tests/test_proxmox_router.py b/backend/tests/test_proxmox_router.py
index 3ecae70..5fb5368 100644
--- a/backend/tests/test_proxmox_router.py
+++ b/backend/tests/test_proxmox_router.py
@@ -509,3 +509,62 @@ async def test_persist_never_deletes(db_session) -> None:
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
+
+
+async def test_canvas_import_also_lands_in_device_inventory(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ """A canvas import is an import: the guests reach the Device Inventory too."""
+ nodes = [_host_node(), _guest_node(101, "10.0.0.5")]
+ with patch("app.api.routes.proxmox.fetch_proxmox_inventory") as mock_fetch:
+ mock_fetch.return_value = (nodes, [])
+ res = await client.post(
+ "/api/v1/proxmox/import",
+ json={
+ "host": "pve1",
+ "token_id": "root@pam!t",
+ "token_secret": "s",
+ },
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+
+ rows = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.discovery_source == "proxmox")
+ )
+ ).scalars().all()
+ by_ieee = {r.ieee_address: r for r in rows}
+ assert set(by_ieee) == {"pve-node-pve1", "pve-pve1-101"}
+ for node in res.json()["nodes"]:
+ assert node["device_id"] == by_ieee[node["ieee_address"]].id
+
+
+async def test_canvas_import_points_at_the_row_matched_by_ip(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ """A guest merged into a scanned row by IP draws that row, not a new one."""
+ scanned = InventoryDevice(
+ id=str(uuid.uuid4()), ip="10.0.0.5", suggested_type="generic",
+ status="pending", discovery_source="arp", discovery_sources=["arp"],
+ )
+ db_session.add(scanned)
+ await db_session.commit()
+
+ with patch("app.api.routes.proxmox.fetch_proxmox_inventory") as mock_fetch:
+ mock_fetch.return_value = ([_guest_node(101, "10.0.0.5")], [])
+ res = await client.post(
+ "/api/v1/proxmox/import",
+ json={"host": "pve1", "token_id": "root@pam!t", "token_secret": "s"},
+ headers=headers,
+ )
+ assert res.status_code == 200, res.text
+ assert res.json()["nodes"][0]["device_id"] == scanned.id
+ rows = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.ip == "10.0.0.5")
+ )
+ ).scalars().all()
+ assert len(rows) == 1
diff --git a/backend/tests/test_zigbee_router.py b/backend/tests/test_zigbee_router.py
index 79408cb..7c88897 100644
--- a/backend/tests/test_zigbee_router.py
+++ b/backend/tests/test_zigbee_router.py
@@ -915,3 +915,91 @@ async def test_sync_now_rejected_without_host(
async def test_sync_now_requires_auth(client: AsyncClient) -> None:
res = await client.post("/api/v1/zigbee/sync-now")
assert res.status_code == 401
+
+
+async def test_canvas_import_also_lands_in_device_inventory(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ """A canvas import is an import: the devices reach the Device Inventory too."""
+ from sqlalchemy import select
+
+ from app.db.models import InventoryDevice
+
+ with patch("app.api.routes.zigbee.fetch_networkmap") as mock_fetch:
+ mock_fetch.return_value = (_SAMPLE_NODES, _SAMPLE_EDGES)
+ job_id = await _start_canvas_import(
+ client, headers, {"mqtt_host": "localhost", "mqtt_port": 1883}
+ )
+
+ res = await client.get(f"/api/v1/zigbee/import/{job_id}", headers=headers)
+ nodes = res.json()["result"]["nodes"]
+
+ rows = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.discovery_source == "zigbee")
+ )
+ ).scalars().all()
+ by_ieee = {r.ieee_address: r for r in rows}
+ assert set(by_ieee) == {"0x00000000", "0x00000001"}
+
+ # Each node names the row it draws, so the canvas save links to it rather
+ # than minting a second, IEEE-less row.
+ for node in nodes:
+ assert node["device_id"] == by_ieee[node["ieee_address"]].id
+
+
+async def test_canvas_import_reuses_the_existing_inventory_row(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ from sqlalchemy import select
+
+ from app.db.models import InventoryDevice
+
+ existing = InventoryDevice(
+ ieee_address="0x00000001",
+ friendly_name="router_1",
+ status="pending",
+ discovery_source="zigbee",
+ )
+ db_session.add(existing)
+ await db_session.commit()
+ existing_id = existing.id
+
+ with patch("app.api.routes.zigbee.fetch_networkmap") as mock_fetch:
+ mock_fetch.return_value = (_SAMPLE_NODES, _SAMPLE_EDGES)
+ job_id = await _start_canvas_import(
+ client, headers, {"mqtt_host": "localhost", "mqtt_port": 1883}
+ )
+
+ res = await client.get(f"/api/v1/zigbee/import/{job_id}", headers=headers)
+ router = next(
+ n for n in res.json()["result"]["nodes"] if n["ieee_address"] == "0x00000001"
+ )
+ assert router["device_id"] == existing_id
+ rows = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.ieee_address == "0x00000001")
+ )
+ ).scalars().all()
+ assert len(rows) == 1
+
+
+async def test_canvas_import_failure_is_reported_on_the_job(
+ client: AsyncClient, headers: dict
+) -> None:
+ """A failed inventory write fails the job rather than returning half a map."""
+ with patch("app.api.routes.zigbee.fetch_networkmap") as mock_fetch, patch(
+ "app.api.routes.zigbee._persist_pending_import",
+ new=AsyncMock(side_effect=ValueError("inventory write failed")),
+ ):
+ mock_fetch.return_value = (_SAMPLE_NODES, _SAMPLE_EDGES)
+ job_id = await _start_canvas_import(
+ client, headers, {"mqtt_host": "localhost", "mqtt_port": 1883}
+ )
+
+ res = await client.get(f"/api/v1/zigbee/import/{job_id}", headers=headers)
+ assert res.status_code == 422
+ assert "inventory write failed" in res.json()["detail"]
diff --git a/backend/tests/test_zwave_router.py b/backend/tests/test_zwave_router.py
index e7bf962..961adbe 100644
--- a/backend/tests/test_zwave_router.py
+++ b/backend/tests/test_zwave_router.py
@@ -601,3 +601,79 @@ async def test_sync_now_rejected_without_host(
async def test_sync_now_requires_auth(client: AsyncClient) -> None:
res = await client.post("/api/v1/zwave/sync-now")
assert res.status_code == 401
+
+
+async def test_import_also_lands_in_device_inventory(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ """A canvas import is an import: the devices reach the Device Inventory too."""
+ from sqlalchemy import select
+
+ from app.db.models import InventoryDevice
+
+ with patch("app.api.routes.zwave.fetch_zwave_network") as mock_fetch:
+ mock_fetch.return_value = (_SAMPLE_NODES, _SAMPLE_EDGES)
+ res = await client.post(
+ "/api/v1/zwave/import",
+ json={"mqtt_host": "localhost", "mqtt_port": 1883},
+ headers=headers,
+ )
+ assert res.status_code == 200
+
+ rows = (
+ await db_session.execute(
+ select(InventoryDevice).where(InventoryDevice.discovery_source == "zwave")
+ )
+ ).scalars().all()
+ by_ieee = {r.ieee_address: r for r in rows}
+ assert set(by_ieee) == {"zwave-0xh-1", "zwave-0xh-2"}
+
+ # Every returned node names the row it draws, so the canvas save links to it
+ # rather than minting a second one.
+ for node in res.json()["nodes"]:
+ assert node["device_id"] == by_ieee[node["ieee_address"]].id
+
+
+async def test_import_reuses_the_existing_inventory_row(
+ client: AsyncClient, headers: dict, db_session
+) -> None:
+ """A device already in the inventory is pointed at, not duplicated."""
+ from sqlalchemy import select
+
+ from app.db.models import InventoryDevice
+
+ existing = InventoryDevice(
+ ieee_address="zwave-0xh-1",
+ friendly_name="Controller",
+ status="pending",
+ discovery_source="zwave",
+ )
+ db_session.add(existing)
+ await db_session.commit()
+ existing_id = existing.id
+
+ with patch("app.api.routes.zwave.fetch_zwave_network") as mock_fetch:
+ mock_fetch.return_value = (_SAMPLE_NODES, _SAMPLE_EDGES)
+ res = await client.post(
+ "/api/v1/zwave/import",
+ json={"mqtt_host": "localhost", "mqtt_port": 1883},
+ headers=headers,
+ )
+ assert res.status_code == 200
+
+ count = len(
+ (
+ await db_session.execute(
+ select(InventoryDevice).where(
+ InventoryDevice.ieee_address == "zwave-0xh-1"
+ )
+ )
+ ).scalars().all()
+ )
+ assert count == 1
+ coordinator = next(
+ n for n in res.json()["nodes"] if n["ieee_address"] == "zwave-0xh-1"
+ )
+ assert coordinator["device_id"] == existing_id
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index da126a6..ba846b5 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -813,6 +813,9 @@ export default function App() {
type: zn.type as NodeData['type'],
status: 'unknown' as const,
services: [],
+ // The import already upserted the Device Inventory row; carry its id so
+ // the canvas save links to that row instead of minting a second one.
+ ...(zn.device_id ? { device_id: zn.device_id } : {}),
...(zn.lqi != null ? { properties: [{ key: 'LQI', value: String(zn.lqi), icon: 'signal', visible: true }] } : {}),
...(zn.model ? { os: zn.model } : {}),
...(zn.parent_id ? { parent_id: zn.parent_id } : {}),
@@ -863,6 +866,8 @@ export default function App() {
type: zn.type as NodeData['type'],
status: 'unknown' as const,
services: [],
+ // Same as the Zigbee import: the row exists already, point at it.
+ ...(zn.device_id ? { device_id: zn.device_id } : {}),
...(zn.model ? { os: zn.model } : {}),
...(zn.parent_id ? { parent_id: zn.parent_id } : {}),
},
@@ -915,6 +920,8 @@ export default function App() {
type: pn.type as NodeData['type'],
status: (pn.status === 'online' ? 'online' : 'unknown') as NodeData['status'],
services: [],
+ // Same as the Zigbee import: the row exists already, point at it.
+ ...(pn.device_id ? { device_id: pn.device_id } : {}),
...(pn.ip ? { ip: pn.ip } : {}),
...(pn.hostname ? { hostname: pn.hostname } : {}),
...(isClusterHost ? { left_handles: 1, right_handles: 1 } : {}),
diff --git a/frontend/src/components/proxmox/ProxmoxImportModal.tsx b/frontend/src/components/proxmox/ProxmoxImportModal.tsx
index be89d4c..bf04ccb 100644
--- a/frontend/src/components/proxmox/ProxmoxImportModal.tsx
+++ b/frontend/src/components/proxmox/ProxmoxImportModal.tsx
@@ -159,7 +159,7 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryIm
return (
<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
- <DialogContent className="bg-[#161b22] border-border max-w-xl max-h-[85vh] flex flex-col">
+ <DialogContent className="bg-[#161b22] border-border max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Server size={16} style={{ color: ACCENT }} />
@@ -169,7 +169,7 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryIm
<div className="flex-1 overflow-y-auto space-y-4 py-2 min-h-0">
<div className="space-y-3">
- <div className="grid grid-cols-2 gap-3">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
<div className="col-span-2 space-y-1">
<Label className="text-xs text-muted-foreground">Proxmox Host</Label>
<Input
@@ -209,7 +209,7 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryIm
className="text-sm bg-[#0d1117] border-border"
/>
</div>
- <div className="col-span-2 flex items-center gap-4 pt-1">
+ <div className="col-span-2 flex flex-wrap items-center gap-x-6 gap-y-2 pt-1">
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
@@ -238,32 +238,34 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryIm
</div>
)}
- <div className="flex items-center gap-3 text-xs">
- <span className="text-muted-foreground">Send devices to:</span>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="proxmox-import-mode"
- checked={importMode === 'pending'}
- onChange={() => setImportMode('pending')}
- className="cursor-pointer"
- style={{ accentColor: ACCENT }}
- />
- Pending section
- </label>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="proxmox-import-mode"
- checked={importMode === 'canvas'}
- onChange={() => setImportMode('canvas')}
- className="cursor-pointer"
- style={{ accentColor: ACCENT }}
- />
- Canvas directly
- </label>
+ <div className="space-y-2 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5">
+ <span className="block text-xs text-muted-foreground">Send devices to</span>
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-xs">
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="proxmox-import-mode"
+ checked={importMode === 'pending'}
+ onChange={() => setImportMode('pending')}
+ className="cursor-pointer"
+ style={{ accentColor: ACCENT }}
+ />
+ Device inventory only
+ </label>
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="proxmox-import-mode"
+ checked={importMode === 'canvas'}
+ onChange={() => setImportMode('canvas')}
+ className="cursor-pointer"
+ style={{ accentColor: ACCENT }}
+ />
+ Inventory + canvas
+ </label>
+ </div>
</div>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2 pt-1">
<Button
size="sm"
variant="ghost"
@@ -284,7 +286,7 @@ export function ProxmoxImportModal({ open, onClose, onAddToCanvas, onInventoryIm
disabled={loading || connectionStatus === 'testing'}
>
{loading ? <Loader2 size={13} className="animate-spin" /> : <Server size={13} />}
- {importMode === 'pending' ? 'Import to Pending' : 'Fetch Inventory'}
+ {importMode === 'pending' ? 'Import to Inventory' : 'Fetch Guests'}
</Button>
</div>
<p className="text-[11px] text-muted-foreground italic">
diff --git a/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx b/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
index 7efa2a8..f30fc34 100644
--- a/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
+++ b/frontend/src/components/proxmox/__tests__/ProxmoxImportModal.test.tsx
@@ -83,7 +83,7 @@ describe('ProxmoxImportModal', () => {
} as never)
render(<ProxmoxImportModal {...defaultProps} />)
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or pve.local'), { target: { value: 'pve' } })
- fireEvent.click(screen.getByRole('button', { name: /import to pending/i }))
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
await waitFor(() => expect(proxmoxApi.importToPending).toHaveBeenCalled())
expect(defaultProps.onInventoryImported).toHaveBeenCalled()
expect(proxmoxApi.importNetwork).not.toHaveBeenCalled()
@@ -94,9 +94,9 @@ describe('ProxmoxImportModal', () => {
data: { nodes: sampleNodes, edges: [{ source: 'pve-node-pve1', target: 'pve-pve1-101' }], device_count: 2 },
} as never)
render(<ProxmoxImportModal {...defaultProps} />)
- fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
+ fireEvent.click(screen.getByRole('radio', { name: /inventory \+ canvas/i }))
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or pve.local'), { target: { value: 'pve' } })
- fireEvent.click(screen.getByRole('button', { name: /fetch inventory/i }))
+ fireEvent.click(screen.getByRole('button', { name: /fetch guests/i }))
await waitFor(() => {
expect(screen.getByText('pve1')).toBeDefined()
expect(screen.getByText('web')).toBeDefined()
@@ -109,10 +109,10 @@ describe('ProxmoxImportModal', () => {
data: { nodes: [], edges: [], device_count: 0 },
} as never)
render(<ProxmoxImportModal {...defaultProps} />)
- fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
+ fireEvent.click(screen.getByRole('radio', { name: /inventory \+ canvas/i }))
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or pve.local'), { target: { value: 'pve' } })
fireEvent.change(screen.getByPlaceholderText('user@pam!tokenname'), { target: { value: 'root@pam!hl' } })
- fireEvent.click(screen.getByRole('button', { name: /fetch inventory/i }))
+ fireEvent.click(screen.getByRole('button', { name: /fetch guests/i }))
await waitFor(() => expect(proxmoxApi.importNetwork).toHaveBeenCalled())
const payload = vi.mocked(proxmoxApi.importNetwork).mock.calls[0][0]
expect(payload.token_id).toBe('root@pam!hl')
diff --git a/frontend/src/components/proxmox/types.ts b/frontend/src/components/proxmox/types.ts
index b0a4b8c..e63d865 100644
--- a/frontend/src/components/proxmox/types.ts
+++ b/frontend/src/components/proxmox/types.ts
@@ -16,6 +16,9 @@ export interface ProxmoxNode {
vendor?: string | null
model?: string | null
parent_ieee?: string | null
+ /** Device Inventory row this node draws — stamped by the import so the
+ * canvas save links to it instead of minting a second row. */
+ device_id?: string | null
}
export interface ProxmoxEdge {
diff --git a/frontend/src/components/zigbee/ZigbeeImportModal.tsx b/frontend/src/components/zigbee/ZigbeeImportModal.tsx
index f18f551..d951052 100644
--- a/frontend/src/components/zigbee/ZigbeeImportModal.tsx
+++ b/frontend/src/components/zigbee/ZigbeeImportModal.tsx
@@ -215,7 +215,7 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImp
return (
<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
- <DialogContent className="bg-[#161b22] border-border max-w-xl max-h-[85vh] flex flex-col">
+ <DialogContent className="bg-[#161b22] border-border max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<Network size={16} className="text-[#00d4ff]" />
@@ -226,7 +226,7 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImp
<div className="flex-1 overflow-y-auto space-y-4 py-2 min-h-0">
{/* Connection Form */}
<div className="space-y-3">
- <div className="grid grid-cols-2 gap-3">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
<div className="col-span-2 space-y-1">
<Label className="text-xs text-muted-foreground">Broker Host</Label>
<Input
@@ -275,7 +275,7 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImp
className="text-sm bg-[#0d1117] border-border"
/>
</div>
- <div className="col-span-2 flex items-center gap-4 pt-1">
+ <div className="col-span-2 flex flex-wrap items-center gap-x-6 gap-y-2 pt-1">
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
@@ -320,30 +320,32 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImp
</div>
)}
- <div className="flex items-center gap-3 text-xs">
- <span className="text-muted-foreground">Send devices to:</span>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="zigbee-import-mode"
- checked={importMode === 'pending'}
- onChange={() => setImportMode('pending')}
- className="accent-[#00d4ff] cursor-pointer"
- />
- Pending section
- </label>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="zigbee-import-mode"
- checked={importMode === 'canvas'}
- onChange={() => setImportMode('canvas')}
- className="accent-[#00d4ff] cursor-pointer"
- />
- Canvas directly
- </label>
+ <div className="space-y-2 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5">
+ <span className="block text-xs text-muted-foreground">Send devices to</span>
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-xs">
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="zigbee-import-mode"
+ checked={importMode === 'pending'}
+ onChange={() => setImportMode('pending')}
+ className="accent-[#00d4ff] cursor-pointer"
+ />
+ Device inventory only
+ </label>
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="zigbee-import-mode"
+ checked={importMode === 'canvas'}
+ onChange={() => setImportMode('canvas')}
+ className="accent-[#00d4ff] cursor-pointer"
+ />
+ Inventory + canvas
+ </label>
+ </div>
</div>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2 pt-1">
<Button
size="sm"
variant="ghost"
@@ -364,7 +366,7 @@ export function ZigbeeImportModal({ open, onClose, onAddToCanvas, onInventoryImp
disabled={loading || connectionStatus === 'testing'}
>
{loading ? <Loader2 size={13} className="animate-spin" /> : <Network size={13} />}
- {importMode === 'pending' ? 'Import to Pending' : 'Fetch Devices'}
+ {importMode === 'pending' ? 'Import to Inventory' : 'Fetch Devices'}
</Button>
</div>
<p className="text-[11px] text-muted-foreground italic">
diff --git a/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx b/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
index f5cea9e..28e2a83 100644
--- a/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
+++ b/frontend/src/components/zigbee/__tests__/ZigbeeImportModal.test.tsx
@@ -114,7 +114,7 @@ describe('ZigbeeImportModal', () => {
})
const selectCanvasMode = () => {
- fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
+ fireEvent.click(screen.getByRole('radio', { name: /inventory \+ canvas/i }))
}
/** A canvas import now answers with a job id; the payload arrives from a poll. */
@@ -183,6 +183,28 @@ describe('ZigbeeImportModal', () => {
})
})
+ it('forwards the device_id the import stamped on each node', async () => {
+ // The import upserted the Device Inventory server-side; the id it returns is
+ // what lets the placed node draw that row instead of minting a second one.
+ mockCanvasImport({
+ nodes: sampleNodes.map((n, i) => ({ ...n, device_id: `dev-${i}` })),
+ edges: [],
+ device_count: 2,
+ })
+
+ startCanvasFetch()
+
+ await waitFor(() => screen.getByText('Coordinator'))
+ fireEvent.click(screen.getByRole('button', { name: /add.*canvas/i }))
+
+ await waitFor(() => expect(defaultProps.onAddToCanvas).toHaveBeenCalledOnce())
+ const [nodes] = defaultProps.onAddToCanvas.mock.calls[0]
+ expect(nodes.map((n: { device_id?: string | null }) => n.device_id)).toEqual([
+ 'dev-0',
+ 'dev-1',
+ ])
+ })
+
it('calls onClose when Cancel is clicked', () => {
render(<ZigbeeImportModal {...defaultProps} />)
fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))
@@ -207,7 +229,7 @@ describe('ZigbeeImportModal', () => {
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 }))
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
await waitFor(() => {
expect(zigbeeApi.importToPending).toHaveBeenCalled()
diff --git a/frontend/src/components/zigbee/types.ts b/frontend/src/components/zigbee/types.ts
index c730bc6..d6b53bf 100644
--- a/frontend/src/components/zigbee/types.ts
+++ b/frontend/src/components/zigbee/types.ts
@@ -11,6 +11,9 @@ export interface ZigbeeNode {
vendor?: string | null
lqi?: number | null
parent_id?: string | null
+ /** Device Inventory row this node draws — stamped by the import so the
+ * canvas save links to it instead of minting a second row. */
+ device_id?: string | null
}
export interface ZigbeeEdge {
diff --git a/frontend/src/components/zwave/ZwaveImportModal.tsx b/frontend/src/components/zwave/ZwaveImportModal.tsx
index d8543ca..b900419 100644
--- a/frontend/src/components/zwave/ZwaveImportModal.tsx
+++ b/frontend/src/components/zwave/ZwaveImportModal.tsx
@@ -203,7 +203,7 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImpo
return (
<Dialog open={open} onOpenChange={(v) => !v && handleClose()}>
- <DialogContent className="bg-[#161b22] border-border max-w-xl max-h-[85vh] flex flex-col">
+ <DialogContent className="bg-[#161b22] border-border max-w-2xl max-h-[85vh] flex flex-col">
<DialogHeader>
<DialogTitle className="text-foreground flex items-center gap-2">
<RadioTower size={16} style={{ color: ACCENT }} />
@@ -214,7 +214,7 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImpo
<div className="flex-1 overflow-y-auto space-y-4 py-2 min-h-0">
{/* Connection Form */}
<div className="space-y-3">
- <div className="grid grid-cols-2 gap-3">
+ <div className="grid grid-cols-2 gap-x-4 gap-y-3">
<div className="col-span-2 space-y-1">
<Label className="text-xs text-muted-foreground">Broker Host</Label>
<Input
@@ -272,7 +272,7 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImpo
className="text-sm bg-[#0d1117] border-border"
/>
</div>
- <div className="col-span-2 flex items-center gap-4 pt-1">
+ <div className="col-span-2 flex flex-wrap items-center gap-x-6 gap-y-2 pt-1">
<label className="flex items-center gap-1.5 text-xs text-muted-foreground cursor-pointer">
<input
type="checkbox"
@@ -318,32 +318,34 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImpo
</div>
)}
- <div className="flex items-center gap-3 text-xs">
- <span className="text-muted-foreground">Send devices to:</span>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="zwave-import-mode"
- checked={importMode === 'pending'}
- onChange={() => setImportMode('pending')}
- className="cursor-pointer"
- style={{ accentColor: ACCENT }}
- />
- Pending section
- </label>
- <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
- <input
- type="radio"
- name="zwave-import-mode"
- checked={importMode === 'canvas'}
- onChange={() => setImportMode('canvas')}
- className="cursor-pointer"
- style={{ accentColor: ACCENT }}
- />
- Canvas directly
- </label>
+ <div className="space-y-2 rounded-md border border-border bg-[#0d1117]/60 px-3 py-2.5">
+ <span className="block text-xs text-muted-foreground">Send devices to</span>
+ <div className="flex flex-wrap items-center gap-x-6 gap-y-2 text-xs">
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="zwave-import-mode"
+ checked={importMode === 'pending'}
+ onChange={() => setImportMode('pending')}
+ className="cursor-pointer"
+ style={{ accentColor: ACCENT }}
+ />
+ Device inventory only
+ </label>
+ <label className="flex items-center gap-1.5 cursor-pointer text-foreground">
+ <input
+ type="radio"
+ name="zwave-import-mode"
+ checked={importMode === 'canvas'}
+ onChange={() => setImportMode('canvas')}
+ className="cursor-pointer"
+ style={{ accentColor: ACCENT }}
+ />
+ Inventory + canvas
+ </label>
+ </div>
</div>
- <div className="flex gap-2">
+ <div className="flex flex-wrap gap-2 pt-1">
<Button
size="sm"
variant="ghost"
@@ -364,7 +366,7 @@ export function ZwaveImportModal({ open, onClose, onAddToCanvas, onInventoryImpo
disabled={loading || connectionStatus === 'testing'}
>
{loading ? <Loader2 size={13} className="animate-spin" /> : <RadioTower size={13} />}
- {importMode === 'pending' ? 'Import to Pending' : 'Fetch Devices'}
+ {importMode === 'pending' ? 'Import to Inventory' : 'Fetch Devices'}
</Button>
</div>
<p className="text-[11px] text-muted-foreground italic">
diff --git a/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx b/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
index 7b4241b..86655d7 100644
--- a/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
+++ b/frontend/src/components/zwave/__tests__/ZwaveImportModal.test.tsx
@@ -97,7 +97,7 @@ describe('ZwaveImportModal', () => {
})
const selectCanvasMode = () => {
- fireEvent.click(screen.getByRole('radio', { name: /canvas directly/i }))
+ fireEvent.click(screen.getByRole('radio', { name: /inventory \+ canvas/i }))
}
it('fetches devices and renders them grouped by type', async () => {
@@ -158,7 +158,7 @@ describe('ZwaveImportModal', () => {
fireEvent.change(screen.getByPlaceholderText('192.168.1.x or mqtt.local'), {
target: { value: '192.168.1.100' },
})
- fireEvent.click(screen.getByRole('button', { name: /import to pending/i }))
+ fireEvent.click(screen.getByRole('button', { name: /import to inventory/i }))
await waitFor(() => {
expect(zwaveApi.importToPending).toHaveBeenCalled()
diff --git a/frontend/src/components/zwave/types.ts b/frontend/src/components/zwave/types.ts
index 3ee9a87..34576a1 100644
--- a/frontend/src/components/zwave/types.ts
+++ b/frontend/src/components/zwave/types.ts
@@ -11,6 +11,9 @@ export interface ZwaveNode {
vendor?: string | null
lqi?: number | null
parent_id?: string | null
+ /** Device Inventory row this node draws — stamped by the import so the
+ * canvas save links to it instead of minting a second row. */
+ device_id?: string | null
}
export interface ZwaveEdge {