Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(inventory): resolve the remaining PR review findings
Pouzor1c9d5791b702
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.pyindex 1c23cc6..fddfdd2 100644--- a/backend/app/api/routes/scan.py+++ b/backend/app/api/routes/scan.py@@ -339,6 +339,12 @@ async def create_pending(existing.properties = merge_properties(existing.properties, body.properties)existing.services = merge_services(existing.services, body.services)existing.discovery_sources = add_source(existing.discovery_sources, body.discovery_source)+ # A hidden row is still that device, so it is the one to fill in — but+ # adding a device by hand is asking for it, and returning it still hidden+ # would leave the user with a 201 and nothing in the inventory. The+ # explicit add outranks the earlier hide, exactly like restore.+ if existing.status == "hidden":+ existing.status = "pending"await db.commit()await db.refresh(existing)return (await _with_canvas_counts(db, [existing]))[0]diff --git a/backend/app/core/scheduler.py b/backend/app/core/scheduler.pyindex 07134c7..e2d317a 100644--- a/backend/app/core/scheduler.py+++ b/backend/app/core/scheduler.py@@ -78,6 +78,13 @@ async def _run_status_checks() -> None:Device-scoped, not node-scoped: a host drawn on three canvases used to bepinged three times and could report three different states. Hidden devicesare skipped — hiding one is how a user says "stop showing me this".++ A device with no node at all is still checked, deliberately. The inventory+ row owns the device and shows its live status in the list and the detail+ modal, so a rack mount or an inventory-only entry reports state without+ being drawn anywhere — and deleting a node no longer silently stops+ monitoring the host. `hide` (or clearing the check method) is what ends the+ checks; the broadcast simply carries an empty `node_ids`."""async with AsyncSessionLocal() as db:devices = (diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.pyindex 1854bee..a8aa1eb 100644--- a/backend/tests/scan/test_scan_routes.py+++ b/backend/tests/scan/test_scan_routes.py@@ -297,6 +297,46 @@ async def test_create_pending_keeps_a_missing_mac_null(client: AsyncClient, headassert res.json()["mac"] is None+async def test_create_pending_unhides_the_row_it_merges_into(client: AsyncClient, headers, db_session):+ """Adding a device by hand outranks an earlier hide of the same host.++ One device is one row, hidden ones included — but merging into a hidden row+ and leaving it hidden answers 201 while nothing appears in the inventory, so+ the add reads as a no-op.+ """+ db_session.add(InventoryDevice(id="d-1", ip="192.168.1.50", status="hidden"))+ await db_session.commit()++ res = await client.post(+ "/api/v1/scan/pending",+ json={"ip": "192.168.1.50", "hostname": "printer", "discovery_source": "manual"},+ headers=headers,+ )+ assert res.status_code == 201, res.text+ assert res.json()["id"] == "d-1"+ assert res.json()["status"] == "pending"++ listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()+ assert [d["id"] for d in listed] == ["d-1"]+++async def test_create_pending_leaves_an_approved_row_approved(client: AsyncClient, headers, db_session):+ """Only `hidden` is lifted — a merge must not walk a device back down the+ lifecycle and re-queue something already on a canvas."""+ db_session.add(InventoryDevice(id="d-1", ip="192.168.1.51", status="approved"))+ await db_session.commit()++ res = await client.post(+ "/api/v1/scan/pending",+ json={"ip": "192.168.1.51", "hostname": "nas", "discovery_source": "manual"},+ headers=headers,+ )+ assert res.status_code == 201, res.text+ assert res.json()["status"] == "approved"++@pytest.mark.asyncioasync def test_delete_pending_removes_one_entry(client: AsyncClient, headers, pending_device):# The rack canvas drops the placeholder it created for a plate once thatdiff --git a/backend/tests/test_scheduler.py b/backend/tests/test_scheduler.pyindex b8caf2e..b5e3785 100644--- a/backend/tests/test_scheduler.py+++ b/backend/tests/test_scheduler.py@@ -113,6 +113,49 @@ async def test_run_status_checks_updates_device_status(mem_db):assert kwargs["status"] == "online"+async def test_run_status_checks_covers_a_device_no_canvas_draws(mem_db):+ """Deliberate: the inventory row, not a node, is what gets monitored.++ A rack mount or an inventory-only entry reports live status without being+ drawn on any canvas, and deleting a node does not silently stop monitoring+ the host. `hide` (or clearing the check method) is what ends the checks.+ """+ async with mem_db() as session:+ device = _make_device(check_method="ping", ip="10.0.0.1")+ session.add(device)+ await session.commit()+ device_id = device.id++ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \+ patch("app.core.scheduler.check_node", new_callable=AsyncMock,+ return_value={"status": "online", "response_time_ms": 5}), \+ patch("app.api.routes.status.broadcast_status", new_callable=AsyncMock) as mock_broadcast:+ await _run_status_checks()++ async with mem_db() as session:+ updated = await session.get(InventoryDevice, device_id)+ assert updated is not None+ assert updated.status_live == "online"++ _, kwargs = mock_broadcast.call_args+ assert kwargs["device_id"] == device_id+ assert kwargs["node_ids"] == []+++async def test_run_status_checks_skips_a_hidden_device(mem_db):+ """Hiding a device is how a user stops the checks, node or no node."""+ async with mem_db() as session:+ session.add(_make_device(check_method="ping", ip="10.0.0.1", status="hidden"))+ await session.commit()++ with patch("app.core.scheduler.AsyncSessionLocal", mem_db), \+ patch("app.core.scheduler.check_node", new_callable=AsyncMock) as mock_check:+ await _run_status_checks()+ mock_check.assert_not_called()++@pytest.mark.asyncioasync def test_run_status_checks_sets_last_seen_only_when_online(mem_db):"""last_seen is updated only when status is 'online'."""diff --git a/frontend/src/utils/__tests__/standaloneStorageDevices.test.ts b/frontend/src/utils/__tests__/standaloneStorageDevices.test.tsindex 7472656..abcbad9 100644--- a/frontend/src/utils/__tests__/standaloneStorageDevices.test.ts+++ b/frontend/src/utils/__tests__/standaloneStorageDevices.test.ts@@ -80,6 +80,42 @@ describe('standalone device rows', () => {expect(reloaded.nodes.every((n) => n.data.ip === reloaded.nodes[0].data.ip)).toBe(true)})+ it('stores reachability as status_live, never as the lifecycle status', () => {+ saveCanvas('d1', { nodes: [node('n1', { ip: '10.0.0.5', status: 'online' })], edges: [] })++ const [device] = stored('d1').devices!+ // `status` is pending / approved / hidden — a device on a canvas is approved.+ expect(device.status).toBe('approved')+ expect(device.status_live).toBe('online')+ })++ it('puts reachability back on the node it belongs to', () => {+ saveCanvas('d1', { nodes: [node('n1', { ip: '10.0.0.5', status: 'offline' })], edges: [] })+ expect(loadCanvas('d1')?.nodes[0].data.status).toBe('offline')+ })++ it('repairs a row saved with reachability in the lifecycle field', () => {+ // Written by the version that copied `status` straight across.+ localStorage.setItem(+ 'homelable_canvas:d1',+ JSON.stringify({+ nodes: [{ ...node('n1'), data: { ...node('n1').data, device_id: 'dev-1' } }],+ edges: [],+ devices: [+ { id: 'dev-1', ip: '10.0.0.5', status: 'online', discovered_at: '2026-01-01T00:00:00Z' },+ ],+ }),+ )++ const loaded = loadCanvas('d1')!+ expect(loaded.nodes[0].data.status).toBe('online')+ saveCanvas('d1', loaded)++ const [device] = stored('d1').devices!+ expect(device.status).toBe('approved')+ expect(device.status_live).toBe('online')+ })+it('gives canvas furniture no row', () => {saveCanvas('d1', {nodes: [node('z1', { type: 'groupRect', label: 'Zone' }), node('t1', { type: 'text' })],diff --git a/frontend/src/utils/standaloneStorage.ts b/frontend/src/utils/standaloneStorage.tsindex f3ad936..154753d 100644--- a/frontend/src/utils/standaloneStorage.ts+++ b/frontend/src/utils/standaloneStorage.ts@@ -65,13 +65,34 @@ export interface StandaloneCanvas {/** Node types that draw nothing physical, so they never get an inventory row. */const FURNITURE_TYPES = new Set(['group', 'groupRect', 'text'])-/** Device fields the inventory row owns — everything a node no longer keeps. */+/**+ * Device fields the inventory row owns — everything a node no longer keeps.+ *+ * `status` is deliberately absent. On a node it is live reachability+ * (online/offline/unknown); on an inventory row it is the pending / approved /+ * hidden lifecycle. The backend keeps them apart as `status` vs `status_live`+ * and so does this — copying one into the other would leave a stored device+ * reading `status: "online"`, which no inventory filter can make sense of.+ */const DEVICE_FIELDS = [- 'hostname', 'ip', 'mac', 'os', 'status', 'check_method', 'check_target',+ 'hostname', 'ip', 'mac', 'os', 'check_method', 'check_target','services', 'notes', 'cpu_count', 'cpu_model', 'ram_gb', 'disk_gb','show_hardware', 'properties', 'last_seen', 'last_scan', 'response_time_ms',] as const+const LIFECYCLE_STATUSES = new Set(['pending', 'approved', 'hidden'])++/**+ * Repair a row saved before the two statuses were told apart, where the node's+ * reachability landed in the lifecycle field. Anything that is not a lifecycle+ * value was reachability, so it moves to `status_live` and the row counts as+ * approved — it is on a canvas, which is what approved means.+ */+function normalizeLifecycle(row: InventoryEntry): InventoryEntry {+ if (LIFECYCLE_STATUSES.has(row.status)) return row+ return { ...row, status: 'approved', status_live: row.status_live ?? row.status }+}+/*** Split a canvas into nodes-plus-rows on the way to storage.*@@ -91,11 +112,15 @@ function splitDevices(data: StandaloneCanvas): StandaloneCanvas {DEVICE_FIELDS.filter((f) => n.data[f] !== undefined).map((f) => [f, n.data[f]]),)const row = {- ...(previous ?? { id: deviceId, discovered_at: new Date().toISOString(), status: 'approved' }),+ ...(previous+ ? normalizeLifecycle(previous)+ : { id: deviceId, discovered_at: new Date().toISOString(), status: 'approved' }),...facts,id: deviceId,label: n.data.label,type: n.data.type,+ // Reachability, kept where the backend keeps it — never in `status`.+ status_live: (n.data.status as string | undefined) ?? previous?.status_live ?? 'unknown',} as InventoryEntryif (previous) devices[devices.indexOf(previous)] = rowelse devices.push(row)@@ -118,9 +143,18 @@ function hydrateDevices(data: StandaloneCanvas): StandaloneCanvas {const facts = Object.fromEntries(DEVICE_FIELDS.filter((f) => row[f] != null).map((f) => [f, row[f]]),)+ const normalized = normalizeLifecycle(row)return {...n,- data: { ...n.data, ...facts, label: row.label ?? n.data.label, type: row.type ?? n.data.type },+ data: {+ ...n.data,+ ...facts,+ label: row.label ?? n.data.label,+ type: row.type ?? n.data.type,+ // The node draws reachability; a row saved before the split carries it+ // in `status`, which normalizeLifecycle has moved to `status_live`.+ status: normalized.status_live ?? n.data.status,+ },} as Node<NodeData>}),}