Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(scan): deep-rescan one device from the inventory detail
Pouzor1be96d10453a
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.pyindex fddfdd2..50107d1 100644--- a/backend/app/api/routes/scan.py+++ b/backend/app/api/routes/scan.py@@ -32,7 +32,13 @@ from app.services.discovery_sources import add_sourcefrom app.services.inventory_sync import find_device_for, merge_properties, merge_servicesfrom app.services.mac_utils import normalize_macfrom app.services.node_dedupe import dedupe_nodes_by_device, find_duplicate_node-from app.services.scanner import DeepScanOptions, _valid_port_range, request_cancel, run_scan+from app.services.scanner import (+ DeepScanOptions,+ _valid_port_range,+ request_cancel,+ run_device_scan,+ run_scan,+)from app.services.zigbee_service import (build_zigbee_properties,merge_zigbee_properties,@@ -180,6 +186,30 @@ async def _background_scan(await db.commit()+async def _background_device_scan(+ run_id: str,+ device_id: str,+ deep_scan: DeepScanOptions | None = None,+ full_ports: bool = True,+) -> None:+ async with AsyncSessionLocal() as db:+ try:+ await run_device_scan(+ device_id,+ db,+ run_id,+ deep_scan=deep_scan or DeepScanOptions(),+ full_ports=full_ports,+ )+ except Exception:+ logger.exception("Device scan run %s failed unexpectedly", run_id)+ await db.rollback()+ run = await db.get(ScanRun, run_id)+ if run and run.status == "running":+ run.status = "failed"+ await db.commit()++def _resolve_deep_scan(payload: TriggerScanRequest | None) -> DeepScanOptions:"""Merge per-scan overrides over persisted settings defaults."""p = payload or TriggerScanRequest()@@ -215,6 +245,63 @@ async def trigger_scan(return run+class RescanDeviceRequest(BaseModel):+ """Per-device deep rescan. Defaults to every TCP port — that is the point."""++ full_ports: bool = True+ http_probe_enabled: bool | None = None+ verify_tls: bool | None = None++[email protected]("/pending/{device_id}/rescan", response_model=ScanRunResponse)+async def rescan_device(+ device_id: str,+ background_tasks: BackgroundTasks,+ payload: RescanDeviceRequest | None = None,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> ScanRun:+ """Deep-rescan one known device to refresh its services (issue #350).++ Recorded as a ScanRun like any other scan, so progress, stop and history+ work unchanged. One run per device at a time — a second request while the+ first is still scanning is a 409, not a duplicate nmap over 65535 ports.+ """+ device = await db.get(InventoryDevice, device_id)+ if not device:+ raise HTTPException(status_code=404, detail="Device not found")+ if not device.ip:+ raise HTTPException(+ status_code=409, detail="Device has no IP address to scan"+ )+ if device.status == "hidden":+ raise HTTPException(status_code=409, detail="Device is hidden")++ target = f"{device.ip}/32"+ running = (await db.execute(+ select(ScanRun).where(ScanRun.status == "running", ScanRun.kind == "device")+ )).scalars().all()+ if any(target in (r.ranges or []) for r in running):+ raise HTTPException(+ status_code=409, detail="A scan is already running for this device"+ )++ p = payload or RescanDeviceRequest()+ deep_scan = _resolve_deep_scan(+ TriggerScanRequest(+ http_probe_enabled=p.http_probe_enabled, verify_tls=p.verify_tls+ )+ )+ run = ScanRun(status="running", kind="device", ranges=[target])+ db.add(run)+ await db.commit()+ await db.refresh(run)+ background_tasks.add_task(+ _background_device_scan, run.id, device_id, deep_scan, p.full_ports+ )+ return run++@router.post("/{run_id}/stop", response_model=dict)async def stop_scan(run_id: str,@@ -933,6 +1020,19 @@ async def list_runs(db: AsyncSession = Depends(get_db), _: str = Depends(get_curreturn list(result.scalars().all())[email protected]("/runs/{run_id}", response_model=ScanRunResponse)+async def get_run(+ run_id: str,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> ScanRun:+ """One run, for a caller waiting on a scan it started (the device rescan)."""+ run = await db.get(ScanRun, run_id)+ if not run:+ raise HTTPException(status_code=404, detail="Scan run not found")+ return run++@router.get("/config", response_model=ScanConfig)async def get_scan_config(_: str = Depends(get_current_user)) -> ScanConfig:return ScanConfig(diff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.pyindex d83ae17..4b86661 100644--- a/backend/app/services/scanner.py+++ b/backend/app/services/scanner.py@@ -62,8 +62,19 @@ def _valid_port_range(spec: str) -> bool:return len(parts) == 1 or parts[0] <= parts[1]-def _build_port_spec(http_ranges: list[str] | None) -> str:- """Combine the default port list with validated user ranges for nmap -p."""+# Every TCP port. Used by the per-device deep rescan, which trades minutes of+# nmap time for a service list that no curated port list can promise.+_FULL_PORTS = "1-65535"+++def _build_port_spec(http_ranges: list[str] | None, full: bool = False) -> str:+ """Combine the default port list with validated user ranges for nmap -p.++ ``full`` overrides everything with the whole TCP range — the deep rescan of+ a single device, where completeness beats speed.+ """+ if full:+ return _FULL_PORTSif not http_ranges:return _EXTRA_PORTSextra = [r.strip() for r in http_ranges if _valid_port_range(r.strip())]@@ -502,6 +513,108 @@ async def _dedupe_pending_by_ip(db: AsyncSession) -> int:return deleted+async def process_host(+ db: AsyncSession,+ host: dict[str, Any],+ *,+ hidden_ips: set[str],+ deep_scan: DeepScanOptions,+ discovery_source: str = "arp",+) -> str:+ """Fold one scanned host into ``device_inventory`` and commit.++ Shared by the range scan and the single-device deep rescan, so both apply+ the same matching, merge and de-duplication rules.++ Returns ``"skipped"`` (hidden by the user), ``"created"`` (a new inventory+ row) or ``"updated"`` (an existing row refreshed).+ """+ ip = host["ip"]++ # Skip only user-hidden devices. On-canvas devices are kept so they+ # surface in the inventory with a canvas-presence badge.+ if ip in hidden_ips:+ logger.debug("Skipping %s — hidden by user", ip)+ return "skipped"++ open_ports = host["open_ports"]+ # Deep-scan HTTP probe: enrich open ports with title/header signals so+ # fingerprint can confirm services on custom ports. No-op when disabled+ # or when the host has no open ports (e.g. mDNS-only discovery).+ if deep_scan.http_probe_enabled and open_ports:+ open_ports = await probe_open_ports(+ ip, open_ports, verify_tls=deep_scan.verify_tls+ )++ norm_mac = normalize_mac(host.get("mac"))+ services = fingerprint_ports(open_ports)+ suggested_type = suggest_node_type(open_ports, norm_mac)++ # One inventory row per device. Match by IP OR MAC across pending AND+ # approved so a re-scan refreshes the existing row instead of spawning+ # 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 = [InventoryDevice.ip == ip]+ if norm_mac:+ match_cond.append(InventoryDevice.mac == norm_mac)+ existing_rows = (await db.execute(+ select(InventoryDevice)+ .where(or_(*match_cond), InventoryDevice.status != "hidden")+ .order_by(InventoryDevice.discovered_at)+ )).scalars().all()++ if existing_rows:+ # Prefer an approved row (it owns the canvas link semantics),+ # otherwise the oldest. Collapse any leftover duplicates created+ # by earlier scans.+ keep = next((r for r in existing_rows if r.status == "approved"), existing_rows[0])+ for dup in existing_rows:+ if dup is not keep:+ await db.delete(dup)+ keep.ip = keep.ip or ip # fill an IP a Proxmox import lacked+ keep.mac = norm_mac or keep.mac+ keep.hostname = host.get("hostname") or keep.hostname+ keep.os = host.get("os") or keep.os+ # Union, never replace. Since 3.3.0 the row is the only copy of+ # a device's services — every canvas drawing it reads this list+ # — so overwriting it with the fingerprint would delete services+ # the user added by hand, on every canvas at once. What a scan+ # 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)+ # 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-"):+ keep.suggested_type = suggested_type+ # Merged row carries both sources (e.g. ["proxmox", "arp"]).+ keep.discovery_sources = add_source(keep.discovery_sources, discovery_source)+ # status preserved — an approved device stays approved.+ # Stamp last_scan on the row so every canvas drawing the device+ # shows when the scanner last observed it. The row is the one+ # place that fact belongs; a node only draws it.+ keep.last_scan = datetime.now(timezone.utc)+ outcome = "updated"+ else:+ db.add(InventoryDevice(+ ip=ip,+ mac=norm_mac,+ hostname=host.get("hostname"),+ os=host.get("os"),+ services=services,+ suggested_type=suggested_type,+ status="pending",+ discovery_source=discovery_source,+ discovery_sources=[discovery_source],+ last_scan=datetime.now(timezone.utc),+ ))+ outcome = "created"++ await db.commit()+ return outcome++async def run_scan(ranges: list[str],db: AsyncSession,@@ -545,88 +658,17 @@ async def run_scan(async def _process_host(host: dict[str, Any], discovery_source: str = "arp") -> None:nonlocal devices_found- ip = host["ip"]-- # Skip only user-hidden devices. On-canvas devices are kept so they- # surface in the inventory with a canvas-presence badge.- if ip in hidden_ips:- logger.debug("Skipping %s — hidden by user", ip)+ outcome = await process_host(+ db,+ host,+ hidden_ips=hidden_ips,+ deep_scan=deep_scan,+ discovery_source=discovery_source,+ )+ if outcome == "skipped":return-- open_ports = host["open_ports"]- # Deep-scan HTTP probe: enrich open ports with title/header signals so- # fingerprint can confirm services on custom ports. No-op when disabled- # or when the host has no open ports (e.g. mDNS-only discovery).- if deep_scan.http_probe_enabled and open_ports:- open_ports = await probe_open_ports(- ip, open_ports, verify_tls=deep_scan.verify_tls- )-- norm_mac = normalize_mac(host.get("mac"))- services = fingerprint_ports(open_ports)- suggested_type = suggest_node_type(open_ports, norm_mac)-- # One inventory row per device. Match by IP OR MAC across pending AND- # approved so a re-scan refreshes the existing row instead of spawning- # 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 = [InventoryDevice.ip == ip]- if norm_mac:- match_cond.append(InventoryDevice.mac == norm_mac)- existing_rows = (await db.execute(- select(InventoryDevice)- .where(or_(*match_cond), InventoryDevice.status != "hidden")- .order_by(InventoryDevice.discovered_at)- )).scalars().all()-- if existing_rows:- # Prefer an approved row (it owns the canvas link semantics),- # otherwise the oldest. Collapse any leftover duplicates created- # by earlier scans.- keep = next((r for r in existing_rows if r.status == "approved"), existing_rows[0])- for dup in existing_rows:- if dup is not keep:- await db.delete(dup)- keep.ip = keep.ip or ip # fill an IP a Proxmox import lacked- keep.mac = norm_mac or keep.mac- keep.hostname = host.get("hostname") or keep.hostname- keep.os = host.get("os") or keep.os- # Union, never replace. Since 3.3.0 the row is the only copy of- # a device's services — every canvas drawing it reads this list- # — so overwriting it with the fingerprint would delete services- # the user added by hand, on every canvas at once. What a scan- # 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)- # 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-"):- keep.suggested_type = suggested_type- # Merged row carries both sources (e.g. ["proxmox", "arp"]).- keep.discovery_sources = add_source(keep.discovery_sources, discovery_source)- # status preserved — an approved device stays approved.- # Stamp last_scan on the row so every canvas drawing the device- # shows when the scanner last observed it. The row is the one- # place that fact belongs; a node only draws it.- keep.last_scan = datetime.now(timezone.utc)- else:- db.add(InventoryDevice(- ip=ip,- mac=norm_mac,- hostname=host.get("hostname"),- os=host.get("os"),- services=services,- suggested_type=suggested_type,- status="pending",- discovery_source=discovery_source,- discovery_sources=[discovery_source],- last_scan=datetime.now(timezone.utc),- ))+ if outcome == "created":devices_found += 1-- await db.commit()await broadcast_scan_update(run_id=run_id, devices_found=devices_found)# nmap scan per CIDR — results stream in progressively@@ -680,3 +722,71 @@ async def run_scan(finally:with _cancelled_lock:_cancelled_runs.discard(run_id)+++async def run_device_scan(+ device_id: str,+ db: AsyncSession,+ run_id: str,+ deep_scan: DeepScanOptions | None = None,+ full_ports: bool = True,+) -> None:+ """Deep-rescan one known device and refresh its inventory row.++ No ping sweep and no mDNS: the device is already known, so the IP goes+ straight to the phase-2 port scan (``-Pn``). ``full_ports`` scans all 65535+ TCP ports, which is the point of the feature — a device added before the+ scanner knew a service, or listening on a port no curated list covers.+ Minutes, not seconds; the run is cancellable like any other.+ """+ from app.api.routes.status import broadcast_scan_update++ deep_scan = deep_scan or DeepScanOptions()+ port_spec = _build_port_spec(deep_scan.http_ranges, full=full_ports)++ try:+ device = await db.get(InventoryDevice, device_id)+ if device is None or not device.ip:+ raise ValueError("Device has no IP to scan")++ host: dict[str, Any] = {+ "ip": device.ip,+ "mac": device.mac,+ "hostname": device.hostname,+ "os": device.os,+ "open_ports": [],+ }++ if not _is_cancelled(run_id):+ host = await asyncio.to_thread(_nmap_scan_single, host, port_spec)++ devices_found = 0+ if not _is_cancelled(run_id):+ # The row is being rescanned on the user's request, so it is never+ # "hidden" from itself — the route rejects hidden devices upfront.+ outcome = await process_host(+ db, host, hidden_ips=set(), deep_scan=deep_scan, discovery_source="arp"+ )+ if outcome == "created":+ devices_found = 1+ await broadcast_scan_update(run_id=run_id, devices_found=devices_found)++ run = await db.get(ScanRun, run_id)+ if run:+ run.status = "cancelled" if _is_cancelled(run_id) else "done"+ run.devices_found = devices_found+ run.finished_at = datetime.now(timezone.utc)+ await db.commit()++ except Exception as exc:+ logger.error("Device scan failed: %s", exc)+ await db.rollback()+ run = await db.get(ScanRun, run_id)+ if run:+ run.status = "error"+ run.error = str(exc)+ run.finished_at = datetime.now(timezone.utc)+ await db.commit()+ finally:+ with _cancelled_lock:+ _cancelled_runs.discard(run_id)diff --git a/backend/tests/scan/test_scan_routes.py b/backend/tests/scan/test_scan_routes.pyindex a8aa1eb..376fdaf 100644--- a/backend/tests/scan/test_scan_routes.py+++ b/backend/tests/scan/test_scan_routes.py@@ -414,3 +414,110 @@ async def test_delete_pending_refuses_a_mounted_device(client: AsyncClient, headassert res.status_code == 409listed = (await client.get("/api/v1/scan/pending", headers=headers)).json()assert [d["id"] for d in listed] == [pending_device.id]+++# ---------------------------------------------------------------------------+# Per-device deep rescan (issue #350)+# ---------------------------------------------------------------------------++async def test_rescan_device_requires_auth(client: AsyncClient, pending_device):+ res = await client.post(f"/api/v1/scan/pending/{pending_device.id}/rescan")+ assert res.status_code == 401+++async def test_rescan_device_creates_run_for_that_ip(client: AsyncClient, headers, pending_device):+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock) as bg:+ res = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ assert res.status_code == 200, res.text+ data = res.json()+ assert data["status"] == "running"+ assert data["kind"] == "device"+ # One host, not the configured ranges — the scan targets this device only.+ assert data["ranges"] == ["192.168.1.100/32"]+ bg.assert_called_once()+ assert bg.call_args.args[1] == pending_device.id+ # Full range unless the caller says otherwise.+ assert bg.call_args.args[3] is True+++async def test_rescan_device_unknown_id_404(client: AsyncClient, headers):+ res = await client.post(f"/api/v1/scan/pending/{uuid.uuid4()}/rescan", headers=headers)+ assert res.status_code == 404+++async def test_rescan_device_without_ip_409(client: AsyncClient, headers, db_session):+ device = InventoryDevice(id=str(uuid.uuid4()), ip=None, hostname="zigbee-lamp", status="pending")+ db_session.add(device)+ await db_session.commit()++ res = await client.post(f"/api/v1/scan/pending/{device.id}/rescan", headers=headers)+ assert res.status_code == 409+ assert "IP" in res.json()["detail"]+++async def test_rescan_device_hidden_409(client: AsyncClient, headers, db_session):+ device = InventoryDevice(id=str(uuid.uuid4()), ip="192.168.1.77", status="hidden")+ db_session.add(device)+ await db_session.commit()++ res = await client.post(f"/api/v1/scan/pending/{device.id}/rescan", headers=headers)+ assert res.status_code == 409+++async def test_rescan_device_serialized_per_device(client: AsyncClient, headers, pending_device):+ """A second rescan while the first still runs is refused, not duplicated."""+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock):+ first = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ second = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ assert first.status_code == 200+ assert second.status_code == 409+ assert "already running" in second.json()["detail"]+++async def test_rescan_device_allows_a_new_run_once_the_first_finished(+ client: AsyncClient, headers, pending_device+):+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock):+ first = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ assert first.status_code == 200+ run_id = first.json()["id"]+ stopped = await client.post(f"/api/v1/scan/{run_id}/stop", headers=headers)+ assert stopped.status_code == 200+ again = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ assert again.status_code == 200+++async def test_get_run_returns_status(client: AsyncClient, headers, pending_device):+ with patch("app.api.routes.scan._background_device_scan", new_callable=AsyncMock):+ started = await client.post(+ f"/api/v1/scan/pending/{pending_device.id}/rescan", headers=headers+ )+ run_id = started.json()["id"]+ res = await client.get(f"/api/v1/scan/runs/{run_id}", headers=headers)+ assert res.status_code == 200+ assert res.json()["id"] == run_id+ assert res.json()["status"] == "running"+++async def test_get_run_unknown_id_404(client: AsyncClient, headers):+ res = await client.get(f"/api/v1/scan/runs/{uuid.uuid4()}", headers=headers)+ assert res.status_code == 404diff --git a/backend/tests/test_scanner.py b/backend/tests/test_scanner.pyindex 6885073..3fca83c 100644--- a/backend/tests/test_scanner.py+++ b/backend/tests/test_scanner.py@@ -1030,3 +1030,131 @@ async def test_run_scan_no_probe_when_disabled(mem_db):await run_scan(["192.168.1.0/24"], session, run_id)probe.assert_not_called()+++# ---------------------------------------------------------------------------+# run_device_scan — per-device deep rescan (issue #350)+# ---------------------------------------------------------------------------++def test_build_port_spec_full_covers_every_tcp_port():+ from app.services.scanner import _build_port_spec++ # full wins over the curated list *and* over user ranges — the deep rescan+ # is only worth its minutes if it really scans everything.+ assert _build_port_spec(None, full=True) == "1-65535"+ assert _build_port_spec(["8000-8100"], full=True) == "1-65535"+++async def test_run_device_scan_refreshes_services_and_marks_run_done(mem_db):+ from app.services.scanner import run_device_scan++ run_id = _make_run_id()+ 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=[]))+ await session.commit()++ def _scanned(host_dict, port_spec):+ assert port_spec == "1-65535"+ 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")+ run = await session.get(ScanRun, run_id)++ assert device is not None and run is not None+ assert run.status == "done"+ assert device.last_scan is not None+ assert any(s.get("port") == 22 for s in device.services)+ # A rescan refreshes an existing row; it never spawns a second one.+ assert device.status == "approved"+++async def test_run_device_scan_keeps_hand_added_services(mem_db):+ """Regression: the rescan unions, it does not replace.++ Services the user typed in by hand are the only copy that exists — every+ canvas drawing the device reads this list.+ """+ from app.services.scanner import run_device_scan++ run_id = _make_run_id()+ hand_added = {"port": 9000, "protocol": "tcp", "service_name": "My App"}+ 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="pending", services=[hand_added]))+ await session.commit()++ def _scanned(host_dict, port_spec):+ 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+ ports = {s.get("port") for s in device.services}+ assert ports == {22, 9000}+++async def test_run_device_scan_marks_run_error_when_device_has_no_ip(mem_db):+ from app.services.scanner import run_device_scan++ run_id = _make_run_id()+ async with mem_db() as session:+ session.add(ScanRun(id=run_id, status="running", kind="device", ranges=["/32"]))+ session.add(InventoryDevice(id="d1", ip=None, status="pending", services=[]))+ await session.commit()++ async with mem_db() as session:+ with 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:+ run = await session.get(ScanRun, run_id)++ assert run is not None+ assert run.status == "error"+ assert run.error is not None+++async def test_run_device_scan_skips_nmap_when_cancelled(mem_db):+ from app.services.scanner import _cancelled_runs, request_cancel, run_device_scan++ run_id = _make_run_id()+ 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="pending", services=[]))+ await session.commit()++ request_cancel(run_id)+ single = MagicMock()++ async with mem_db() as session:+ with patch("app.services.scanner._nmap_scan_single", new=single), \+ 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:+ run = await session.get(ScanRun, run_id)++ single.assert_not_called()+ assert run is not None+ assert run.status == "cancelled"+ # The run cleans up its cancellation flag on the way out.+ assert run_id not in _cancelled_runsdiff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex 9508feb..73edb64 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -109,6 +109,18 @@ export interface DeepScanConfig {export type ScanConfigData = { ranges: string[] } & DeepScanConfig+/** A row of `scan_runs` — what `/scan/runs` and the device rescan return. */+export interface ScanRunSummary {+ id: string+ status: 'running' | 'done' | 'cancelled' | 'error' | 'failed'+ kind: string+ ranges: string[]+ devices_found: number+ started_at: string+ finished_at: string | null+ error: string | null+}+// A device the backend refused to place because an equivalent node already// exists on the target design (same ip/mac/ieee). `existing_node_id` points at// the node already there so the UI can link to it.@@ -158,8 +170,17 @@ export const scanApi = {*/updatePending: (id: string, data: Partial<Omit<InventoryEntry, 'id' | 'status' | 'discovered_at'>>) =>api.patch<InventoryEntry>(`/scan/pending/${id}`, data),+ /**+ * Deep-rescan one known device: every TCP port, then re-fingerprint. Answers+ * "this device predates the scanner knowing that service" (issue #350).+ * Returns the ScanRun, so the caller polls `run` and can `stop` it.+ * 409 when the device has no IP, is hidden, or is already being rescanned.+ */+ rescanDevice: (id: string, opts?: { full_ports?: boolean; http_probe_enabled?: boolean; verify_tls?: boolean }) =>+ api.post<ScanRunSummary>(`/scan/pending/${id}/rescan`, opts ?? {}),hidden: () => api.get('/scan/hidden'),runs: () => api.get('/scan/runs'),+ run: (runId: string) => api.get<ScanRunSummary>(`/scan/runs/${runId}`),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}`),diff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsxindex 29ef1a1..dd68221 100644--- a/frontend/src/components/modals/InventoryDeviceModal.tsx+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx@@ -14,7 +14,7 @@* badges, then three columns — identity / operations / curation — so a device* reads in one screen instead of a scrolling column of key-value pairs.*/-import { useEffect, useState } from 'react'+import { useEffect, useRef, useState } from 'react'import {Check,Copy,@@ -23,9 +23,11 @@ import {HeartPulse,History,Layers,+ Loader2,Network,Pencil,Plus,+ Radar,StickyNote,Tags,X,@@ -263,7 +265,16 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnconst [services, setServices] = useState<ServiceInfo[]>(device?.services ?? [])const [svcModal, setSvcModal] = useState<{ index: number | null; form?: ServiceFormData } | null>(null)const [saving, setSaving] = useState(false)+ // The id of the deep rescan this modal started, while it is still running.+ const [rescanRunId, setRescanRunId] = useState<string | null>(null)+ const [rescanStarting, setRescanStarting] = useState(false)const activeTheme = useThemeStore((s) => s.activeTheme)+ // Kept in a ref so the poll effect below doesn't restart — and lose its+ // timer — every time the parent re-renders with a new callback identity.+ const onSavedRef = useRef(onSaved)+ onSavedRef.current = onSaved+ const editingRef = useRef(editing)+ editingRef.current = editing// Reset the form whenever the modal is pointed at another device — the// component stays mounted across card clicks in the inventory grid.@@ -274,8 +285,49 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnsetServices(device.services ?? [])setEditing(false)setSvcModal(null)+ setRescanRunId(null)}, [device])+ // Wait on a running deep rescan. A full 65535-port scan takes minutes, so the+ // run is polled rather than awaited — the user can close the modal, and the+ // scan keeps going and still shows under Scan History.+ const deviceId = device?.id ?? null+ useEffect(() => {+ if (!rescanRunId || !deviceId) return+ let stopped = false+ const timer = window.setInterval(async () => {+ try {+ const { data: run } = await scanApi.run(rescanRunId)+ if (stopped || run.status === 'running') return+ setRescanRunId(null)+ if (run.status === 'error' || run.status === 'failed') {+ toast.error(`Scan failed: ${run.error ?? 'unknown error'}`)+ return+ }+ if (run.status === 'cancelled') {+ toast.info('Scan stopped')+ return+ }+ const { data: rows } = await scanApi.pending()+ const fresh = (rows as InventoryEntry[]).find((d) => d.id === deviceId)+ if (!fresh || stopped) return+ // Never clobber an edit in progress — the user's unsaved services win.+ if (!editingRef.current) setServices(fresh.services ?? [])+ useCanvasStore.getState().applyDeviceFacts(fresh.id, deviceFactsToNodeData(fresh))+ useCanvasStore.getState().notifyScanDeviceFound()+ onSavedRef.current?.(fresh)+ const n = fresh.services?.length ?? 0+ toast.success(`Scan done — ${n} service${n !== 1 ? 's' : ''}`)+ } catch {+ // Transient failure: keep polling, the run is still on the server.+ }+ }, 3000)+ return () => {+ stopped = true+ window.clearInterval(timer)+ }+ }, [rescanRunId, deviceId])+if (!device) return nullconst resolvedType = (device.type ?? device.suggested_type ?? 'generic') as NodeType@@ -301,6 +353,30 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnsetServices(device.services ?? [])}+ const handleRescan = async () => {+ if (!device.ip || rescanRunId || rescanStarting) return+ setRescanStarting(true)+ try {+ const res = await scanApi.rescanDevice(device.id, { full_ports: true })+ setRescanRunId(res.data.id)+ toast.info('Deep scan started — all 65535 ports, this takes a few minutes')+ } catch (err) {+ const detail = (err as { response?: { data?: { detail?: string } } }).response?.data?.detail+ toast.error(detail ?? 'Could not start the scan')+ } finally {+ setRescanStarting(false)+ }+ }++ const handleStopRescan = async () => {+ if (!rescanRunId) return+ try {+ await scanApi.stop(rescanRunId)+ } catch {+ toast.error('Could not stop the scan')+ }+ }+const handleSubmitService = (data: ServiceSubmitData) => {const svc: ServiceInfo = {...(data.port != null ? { port: data.port } : {}),@@ -606,7 +682,36 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn{/* Zigbee devices have no IP services — the section would always be empty. */}{!isZigbee && (- <Section title={`Services found (${device.services.length})`} icon={Network}>+ <Section+ title={`Services found (${device.services.length})`}+ icon={Network}+ action={+ // Deep rescan: the fix for a device added before the+ // scanner knew its services, or one listening on a port+ // no curated list covers (issue #350). Needs an IP.+ device.ip ? (+ rescanRunId ? (+ <button+ onClick={handleStopRescan}+ data-testid="device-rescan-stop"+ className="flex items-center gap-1 text-[10px] text-[#f85149] hover:text-[#f85149]/80 transition-colors cursor-pointer"+ >+ <Loader2 size={10} className="animate-spin" /> Scanning — stop+ </button>+ ) : (+ <button+ onClick={handleRescan}+ disabled={rescanStarting}+ data-testid="device-rescan"+ title="Scan all 65535 TCP ports and refresh the services"+ className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer disabled:opacity-50 disabled:cursor-not-allowed"+ >+ <Radar size={10} /> Deep scan+ </button>+ )+ ) : undefined+ }+ >{device.services.length === 0 ? (<Empty>No services detected</Empty>) : (diff --git a/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsxnew file mode 100644index 0000000..bb07120--- /dev/null+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModalRescan.test.tsx@@ -0,0 +1,142 @@+/**+ * Per-device deep rescan (issue #350) — the detail modal starts a full-port+ * scan of one device, waits on the run, and folds the fresh services back in.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'+import { InventoryDeviceModal } from '../InventoryDeviceModal'+import type { InventoryEntry } from '@/types'++const mockRescanDevice = vi.fn()+const mockRun = vi.fn()+const mockPending = vi.fn()+const mockStop = vi.fn()++vi.mock('@/api/client', () => ({+ scanApi: {+ updatePending: vi.fn(),+ rescanDevice: (...a: unknown[]) => mockRescanDevice(...a),+ run: (...a: unknown[]) => mockRun(...a),+ pending: (...a: unknown[]) => mockPending(...a),+ stop: (...a: unknown[]) => mockStop(...a),+ },+}))++vi.mock('sonner', async () => (await import('@/test/mocks')).mockSonner())++function makeDevice(overrides: Partial<InventoryEntry> = {}): InventoryEntry {+ return {+ id: 'dev-1',+ ip: '192.168.1.100',+ mac: 'aa:bb:cc:dd:ee:ff',+ hostname: 'pve.local',+ os: 'Linux',+ services: [],+ suggested_type: 'server',+ status: 'pending',+ discovered_at: '2024-01-15T10:30:00Z',+ ...overrides,+ }+}++const noop = { onClose: vi.fn(), onApprove: vi.fn(), onHide: vi.fn(), onIgnore: vi.fn() }++beforeEach(() => {+ vi.clearAllMocks()+ mockRescanDevice.mockResolvedValue({ data: { id: 'run-1', status: 'running' } })+ mockRun.mockResolvedValue({ data: { id: 'run-1', status: 'running', error: null } })+ mockPending.mockResolvedValue({ data: [] })+ mockStop.mockResolvedValue({ data: {} })+})++afterEach(() => {+ vi.useRealTimers()+})++describe('InventoryDeviceModal — deep rescan', () => {+ it('offers the deep scan only when the device has an IP', () => {+ const { rerender } = render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ expect(screen.getByTestId('device-rescan')).toBeInTheDocument()++ rerender(<InventoryDeviceModal {...noop} device={makeDevice({ id: 'dev-2', ip: null })} />)+ expect(screen.queryByTestId('device-rescan')).toBeNull()+ })++ it('is absent for a Zigbee device — it has no IP services at all', () => {+ render(+ <InventoryDeviceModal+ {...noop}+ device={makeDevice({ discovery_source: 'zigbee', ieee_address: '0x00124b' })}+ />+ )+ expect(screen.queryByTestId('device-rescan')).toBeNull()+ })++ it('scans every port and swaps to a stop control while it runs', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))++ await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())+ expect(mockRescanDevice).toHaveBeenCalledWith('dev-1', { full_ports: true })+ expect(screen.queryByTestId('device-rescan')).toBeNull()+ })++ it('stops the run through the same ScanRun the header uses', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))+ await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())++ fireEvent.click(screen.getByTestId('device-rescan-stop'))+ await waitFor(() => expect(mockStop).toHaveBeenCalledWith('run-1'))+ })++ it('keeps the button enabled again when the start is refused', async () => {+ mockRescanDevice.mockRejectedValue({+ response: { data: { detail: 'A scan is already running for this device' } },+ })+ const { toast } = await import('sonner')+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))++ await waitFor(() =>+ expect(toast.error).toHaveBeenCalledWith('A scan is already running for this device')+ )+ expect(screen.getByTestId('device-rescan')).toBeInTheDocument()+ })++ it('folds the freshly found services back into the open modal', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const onSaved = vi.fn()+ const fresh = makeDevice({+ services: [{ port: 8096, protocol: 'tcp', service_name: 'Jellyfin' }],+ })+ render(<InventoryDeviceModal {...noop} onSaved={onSaved} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))+ await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())++ mockRun.mockResolvedValue({ data: { id: 'run-1', status: 'done', error: null } })+ mockPending.mockResolvedValue({ data: [fresh] })+ await act(async () => { await vi.advanceTimersByTimeAsync(3100) })++ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(fresh))+ // Polling ends with the run — no second request once it is done.+ const calls = mockRun.mock.calls.length+ await act(async () => { await vi.advanceTimersByTimeAsync(6000) })+ expect(mockRun.mock.calls.length).toBe(calls)+ })++ it('surfaces a failed run instead of silently ending', async () => {+ vi.useFakeTimers({ shouldAdvanceTime: true })+ const { toast } = await import('sonner')+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByTestId('device-rescan'))+ await waitFor(() => expect(screen.getByTestId('device-rescan-stop')).toBeInTheDocument())++ mockRun.mockResolvedValue({ data: { id: 'run-1', status: 'error', error: 'nmap missing' } })+ await act(async () => { await vi.advanceTimersByTimeAsync(3100) })++ await waitFor(() => expect(toast.error).toHaveBeenCalledWith('Scan failed: nmap missing'))+ expect(mockPending).not.toHaveBeenCalled()+ await waitFor(() => expect(screen.getByTestId('device-rescan')).toBeInTheDocument())+ })+})