Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(inventory): keep approved cards linked to their row across a save
Pouzor6e6ccde1e140
diff --git a/backend/app/api/routes/canvas.py b/backend/app/api/routes/canvas.pyindex 8b80233..4dd5735 100644--- a/backend/app/api/routes/canvas.py+++ b/backend/app/api/routes/canvas.py@@ -8,7 +8,7 @@ from sqlalchemy.ext.asyncio import AsyncSessionfrom app.api.deps import get_current_userfrom app.db.database import get_db-from app.db.models import CanvasState, Design, Edge, Node+from app.db.models import CanvasState, Design, Edge, InventoryDevice, Nodefrom app.schemas.canvas import CanvasSaveRequest, CanvasStateResponsefrom app.schemas.edges import EdgeResponsefrom app.schemas.nodes import NodeResponse@@ -94,6 +94,16 @@ async def save_canvas(payload["design_id"] = design_idfacts = facts_from_payload(payload, label=node_data.label, node_type=node_data.type)columns = node_columns(payload)+ if db_node and db_node.device_id and not columns.get("device_id"):+ # A node linked to an IEEE-identified row (an approve or import of a+ # Zigbee/Z-Wave/Proxmox device) keeps it when the client sent none.+ # The save payload carries no IEEE, so link_facts could never match+ # that row again: it would mint a stray IEEE-less one on every save,+ # and the mesh links, resolved by IEEE, would lose the node.+ # Furniture is still detached, by link_facts below.+ row = await db.get(InventoryDevice, db_node.device_id)+ if row is not None and row.ieee_address:+ columns["device_id"] = db_node.device_idif db_node:for field, value in columns.items():setattr(db_node, field, value)diff --git a/backend/tests/test_canvas.py b/backend/tests/test_canvas.pyindex d076833..ef7e12e 100644--- a/backend/tests/test_canvas.py+++ b/backend/tests/test_canvas.py@@ -829,3 +829,58 @@ async def test_save_canvas_drops_a_description_on_a_device_node(client: AsyncClisaved = (await client.get("/api/v1/canvas", headers=headers)).json()["nodes"][0]assert saved["description"] is Noneassert saved["notes"] == "Backs up nightly."+++async def test_save_canvas_keeps_the_row_a_node_was_linked_to(client: AsyncClient, headers: dict, db_session):+ """A save that omits device_id must not detach a node the server linked.++ A Zigbee device has no ip or mac, so once detached it cannot be re-matched:+ every save minted another IEEE-less row, the real row showed on no canvas,+ and the mesh links (resolved by IEEE) found nothing to attach to (#532).+ """+ from sqlalchemy import select++ from app.db.models import InventoryDevice, Node++ db_session.add(InventoryDevice(+ id="d-zb", ieee_address="0x588e81fffef09c07", suggested_type="zigbee_router", status="pending",+ ))+ await db_session.commit()+ node_id = (await client.post(+ "/api/v1/scan/pending/d-zb/approve",+ json={"type": "zigbee_router", "label": "Lidl PC"},+ headers=headers,+ )).json()["node_id"]++ for _ in range(2):+ res = await client.post(+ "/api/v1/canvas/save",+ json={"nodes": [{**node_payload(type="zigbee_router", label="Lidl PC"), "id": node_id}],+ "edges": [], "viewport": {}},+ headers=headers,+ )+ assert res.status_code == 200++ db_session.expire_all()+ node = await db_session.get(Node, node_id)+ assert node is not None and node.device_id == "d-zb"+ rows = (await db_session.execute(select(InventoryDevice))).scalars().all()+ assert [r.id for r in rows] == ["d-zb"]+++async def test_save_canvas_still_detaches_a_node_turned_into_furniture(client: AsyncClient, headers: dict, db_session):+ """The keep-the-link guard must not pin a row onto canvas furniture."""+ from app.db.models import InventoryDevice, Node++ db_session.add(InventoryDevice(id="d-zb", ieee_address="0xAAAA", status="pending"))+ await db_session.commit()+ node_id = (await client.post(+ "/api/v1/scan/pending/d-zb/approve",+ json={"type": "zigbee_router", "label": "Plug"},+ headers=headers,+ )).json()["node_id"]++ zone = {**node_payload(type="groupRect", label="Zone"), "id": node_id, "device_id": None}+ await client.post("/api/v1/canvas/save", json={"nodes": [zone], "edges": [], "viewport": {}}, headers=headers)+ db_session.expire_all()+ assert (await db_session.get(Node, node_id)).device_id is Nonediff --git a/backend/tests/test_zigbee_router.py b/backend/tests/test_zigbee_router.pyindex 119c2f0..af8d5b9 100644--- a/backend/tests/test_zigbee_router.py+++ b/backend/tests/test_zigbee_router.py@@ -1230,3 +1230,65 @@ async def test_resolve_links_targets_the_card_just_placed(db_session) -> None:assert [(e["source"], e["target"]) for e in created] == [(router.id, placed.id)]edges = (await db_session.execute(select(Edge))).scalars().all()assert {(e.source, e.target) for e in edges} == {(router.id, linked.id), (router.id, placed.id)}+++async def test_second_card_is_linked_after_the_canvas_was_saved(+ client: AsyncClient, headers: dict, db_session+) -> None:+ """Regression for #532 as reported: approve, save the canvas, add the device+ again. The save used to detach the cards from their rows, so the second+ approve found no coordinator to link to.+ """+ import uuid++ from app.db.models import Design, InventoryDevice, InventoryDeviceLink++ design = Design(id=str(uuid.uuid4()), name="Zigbee")+ db_session.add_all([+ design,+ InventoryDevice(id="d-coord", ieee_address="0xCOORD", status="pending"),+ InventoryDevice(id="d-lidl", ieee_address="0xLIDL", status="pending"),+ InventoryDeviceLink(+ id=str(uuid.uuid4()), source_ieee="0xCOORD", target_ieee="0xLIDL",+ discovery_source="zigbee",+ ),+ ])+ await db_session.commit()++ async def approve(device_id: str, node_type: str, force: bool = False) -> dict:+ res = await client.post(+ f"/api/v1/scan/pending/{device_id}/approve",+ json={"type": node_type, "label": device_id, "design_id": design.id, "force": force},+ headers=headers,+ )+ assert res.status_code == 200, res.text+ body: dict = res.json()+ return body++ coord = await approve("d-coord", "zigbee_coordinator")+ first = await approve("d-lidl", "zigbee_router")+ # What a client that never learned the device ids sends: no device_id.+ nodes = [+ {"id": coord["node_id"], "type": "zigbee_coordinator", "label": "Coordinator"},+ {"id": first["node_id"], "type": "zigbee_router", "label": "Lidl PC"},+ ]+ edge = first["edges"][0]+ res = await client.post(+ "/api/v1/canvas/save",+ json={+ "design_id": design.id,+ "nodes": nodes,+ "edges": [{"id": edge["id"], "source": edge["source"], "target": edge["target"], "type": "iot"}],+ "viewport": {},+ },+ headers=headers,+ )+ assert res.status_code == 200, res.text++ second = await approve("d-lidl", "zigbee_router", force=True)++ assert second["edges_created"] == 1+ assert (second["edges"][0]["source"], second["edges"][0]["target"]) == (+ coord["node_id"], second["node_id"],+ )diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsxindex 0750c32..b31cfec 100644--- a/frontend/src/components/modals/DeviceInventoryModal.tsx+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx@@ -136,6 +136,10 @@ function inventoryNodeData(d: InventoryEntry) {data: {label: deviceLabel(d),type,+ // The row this card draws. Without it the next canvas save would re-match+ // the node by ip/mac, which a Zigbee or Z-Wave device does not have, and+ // mint a stray row instead.+ device_id: d.id,ip: d.ip ?? undefined,mac: d.mac ?? undefined,hostname: d.hostname ?? undefined,@@ -388,7 +392,11 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatusid: nodeId,type: nodeData.type,position: getCenteredPosition(),- data: { ...nodeData, status: wireless ? ('online' as const) : ('unknown' as const) },+ data: {+ ...nodeData,+ device_id: device.id,+ status: wireless ? ('online' as const) : ('unknown' as const),+ },})injectAutoEdges(res.data.edges)const extra = res.data.edges_created > 0 ? ` (+${res.data.edges_created} link${res.data.edges_created !== 1 ? 's' : ''})` : ''diff --git a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsxindex 88ad974..b5df795 100644--- a/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx+++ b/frontend/src/components/modals/__tests__/DeviceInventoryModal.test.tsx@@ -512,6 +512,32 @@ describe('DeviceInventoryModal', () => {expect(zbNode.data.properties.some((p: { key: string }) => p.key === 'MAC')).toBe(false)})+ // A Zigbee card has no ip/mac, so a canvas save cannot find its row again: the+ // card must carry device_id from the moment it is placed, or the save detaches+ // it and mints a stray row (#532).+ it('single approve places a card that points at its inventory row', async () => {+ render(<DeviceInventoryModal {...baseProps} />)+ await waitFor(() => expect(screen.getByTestId('pending-card-dev-b')).toBeInTheDocument())+ fireEvent.click(screen.getByTestId('pending-card-dev-b'))+ fireEvent.click(screen.getByTestId('do-approve'))+ await waitFor(() => expect(mockAddNode).toHaveBeenCalledTimes(1))+ expect(mockAddNode.mock.calls[0][0].data.device_id).toBe('dev-b')+ })++ it('bulk approve places cards that point at their inventory rows', async () => {+ 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'))+ fireEvent.click(screen.getByTestId('pending-card-dev-b'))+ fireEvent.click(screen.getByRole('button', { name: /Put in current Canvas \(2\)/ }))+ await waitFor(() => expect(mockAddNode).toHaveBeenCalledTimes(2))+ const byNode = Object.fromEntries(+ mockAddNode.mock.calls.map((c) => [c[0].id, c[0].data.device_id]),+ )+ expect(byNode).toEqual({ n1: 'dev-a', n2: 'dev-b' })+ })+it('bulk hide calls API with selected ids', async () => {render(<DeviceInventoryModal {...baseProps} />)await waitFor(() => expect(screen.getByTestId('pending-card-dev-a')).toBeInTheDocument())