Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
fix(scan): stop a scan from repainting hand-picked service icons
Pouzor2e642815f476
diff --git a/backend/app/services/inventory_sync.py b/backend/app/services/inventory_sync.pyindex acc8f41..143d6b9 100644--- a/backend/app/services/inventory_sync.py+++ b/backend/app/services/inventory_sync.py@@ -358,8 +358,26 @@ def _stamped(item: Any, visible: bool) -> Any:return {**item, "visible": visible}-def merge_services(base: list[Any] | None, incoming: list[Any] | None) -> list[Any]:- """Union two service lists on (port, protocol, name); incoming wins."""+# How a service looks is the user's call. A fingerprint only ever guesses it+# from a port number and a banner, so a scan that re-finds a known service must+# not repaint the icon someone picked by hand — that happened on every "Scan+# network", across every canvas drawing the device, at once.+_CURATED_SERVICE_FIELDS = ("icon", "category")+++def merge_services(+ base: list[Any] | None,+ incoming: list[Any] | None,+ *,+ discovered: bool = False,+) -> list[Any]:+ """Union two service lists on (port, protocol, name); incoming wins.++ ``discovered`` marks ``incoming`` as scanner output rather than a user edit:+ it still adds services and refreshes facts, but leaves an established icon+ and category alone. Either way a blank incoming value never clears one that+ is already set — an absent field is silence, not a reset.+ """out: list[Any] = [dict(s) if isinstance(s, dict) else s for s in (base or [])]index = {_service_key(s): i for i, s in enumerate(out)}for svc in incoming or []:@@ -369,7 +387,12 @@ def merge_services(base: list[Any] | None, incoming: list[Any] | None) -> list[Aout.append(dict(svc) if isinstance(svc, dict) else svc)index[key] = len(out) - 1elif isinstance(svc, dict) and isinstance(out[pos], dict):- out[pos] = {**out[pos], **svc}+ merged = {**out[pos], **svc}+ for field_name in _CURATED_SERVICE_FIELDS:+ established = out[pos].get(field_name)+ if established and (discovered or not svc.get(field_name)):+ merged[field_name] = established+ out[pos] = mergedelse:out[pos] = svcreturn outdiff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.pyindex 375b01e..94ad6ef 100644--- a/backend/app/services/scanner.py+++ b/backend/app/services/scanner.py@@ -674,7 +674,9 @@ async def process_host(# finds is added; what it no longer sees stays. A service the# user does not want on a canvas is hidden by that node's view,# which is where "I deleted this" belongs.- keep.services = merge_services(keep.services, services)+ # discovered=: the fingerprint may add services and refresh what it+ # knows, but never repaints an icon or category the user chose.+ keep.services = merge_services(keep.services, services, discovered=True)# Don't downgrade a Proxmox-typed guest (vm/lxc) to the generic# scan guess; the importer knows the true type.if not (keep.ieee_address or "").startswith("pve-"):diff --git a/backend/tests/test_inventory_sync.py b/backend/tests/test_inventory_sync.pyindex 913475a..e444051 100644--- a/backend/tests/test_inventory_sync.py+++ b/backend/tests/test_inventory_sync.py@@ -85,6 +85,49 @@ class TestMergeRules:assert out[1]["port"] == 80+ def test_a_scan_never_repaints_an_icon_the_user_picked(self):+ """Every "Scan network" used to overwrite a hand-picked brand icon."""+ base = [+ {"port": 80, "protocol": "tcp", "service_name": "http",+ "icon": "brand:pihole", "category": "network"},+ ]+ # What fingerprint_ports returns for the same port: its own guess.+ incoming = [+ {"port": 80, "protocol": "tcp", "service_name": "http",+ "icon": "Globe", "category": "web"},+ ]+ out = merge_services(base, incoming, discovered=True)+ assert len(out) == 1+ assert out[0]["icon"] == "brand:pihole"+ assert out[0]["category"] == "network"++ def test_a_scan_still_fills_an_icon_the_service_never_had(self):+ out = merge_services(+ [{"port": 80, "protocol": "tcp", "service_name": "http"}],+ [{"port": 80, "protocol": "tcp", "service_name": "http",+ "icon": "Globe", "category": "web"}],+ discovered=True,+ )+ assert out[0]["icon"] == "Globe"+ assert out[0]["category"] == "web"++ def test_a_user_edit_still_changes_the_icon(self):+ """The guard is for scanner output only — an edit is an edit."""+ out = merge_services(+ [{"port": 80, "protocol": "tcp", "service_name": "http", "icon": "Globe"}],+ [{"port": 80, "protocol": "tcp", "service_name": "http", "icon": "brand:pihole"}],+ )+ assert out[0]["icon"] == "brand:pihole"++ def test_services_keep_an_established_icon_when_incoming_has_none(self):+ """A blank field is silence, not a reset — mirrors merge_properties."""+ out = merge_services(+ [{"port": 80, "protocol": "tcp", "service_name": "http", "icon": "brand:pihole"}],+ [{"port": 80, "protocol": "tcp", "service_name": "http", "icon": None}],+ )+ assert out[0]["icon"] == "brand:pihole"++class TestChangedFacts:"""What a save is allowed to write: its edit, not its whole snapshot."""diff --git a/backend/tests/test_scanner.py b/backend/tests/test_scanner.pyindex bda20d8..e0a32c1 100644--- a/backend/tests/test_scanner.py+++ b/backend/tests/test_scanner.py@@ -1189,6 +1189,50 @@ async def test_run_device_scan_keeps_hand_added_services(mem_db):assert ports == {22, 9000}+async def test_scan_keeps_the_icon_the_user_picked_for_a_service(mem_db):+ """Regression: every scan used to repaint hand-picked service icons.++ The fingerprint guesses an icon from the port; the user's choice is the+ only one that means anything, so a rescan leaves it where it is.+ """+ from app.services.scanner import run_device_scan++ run_id = _make_run_id()+ curated = {+ "port": 22,+ "protocol": "tcp",+ "service_name": "ssh",+ "icon": "brand:openssh",+ "category": "remote",+ }+ async with mem_db() as session:+ session.add(ScanRun(id=run_id, status="running", kind="device", ranges=["192.168.1.9/32"]))+ session.add(InventoryDevice(id="d1", ip="192.168.1.9", status="approved", services=[curated]))+ await session.commit()++ def _scanned(host_dict, port_spec, bounded=False):+ host_dict["open_ports"] = [{"port": 22, "protocol": "tcp", "banner": "OpenSSH 9.2"}]+ return host_dict++ async with mem_db() as session:+ with patch("app.services.scanner._nmap_scan_single", side_effect=_scanned), \+ patch("app.api.routes.status.broadcast_scan_update", new_callable=AsyncMock):+ await run_device_scan("d1", session, run_id)++ async with mem_db() as session:+ device = await session.get(InventoryDevice, "d1")++ assert device is not None+ matches = [s for s in device.services if s.get("port") == 22]+ # Merged in place — the name key is case-insensitive, so "SSH" from the+ # signature does not append a second row next to the user's "ssh".+ assert len(matches) == 1+ ssh = matches[0]+ assert ssh["icon"] == "brand:openssh"+ assert ssh["category"] == "remote"++@pytest.mark.asyncioasync def test_run_device_scan_marks_run_error_when_device_has_no_ip(mem_db):from app.services.scanner import run_device_scan