Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring
TypeScript diagramhomelabhomelab-infrastructure-observabilitynetworkproxmox-veself-hostedzigbeezwavezwave-js
feat(inventory): show and edit a device from the inventory
Pouzor4393ac92c6ff
diff --git a/backend/app/api/routes/scan.py b/backend/app/api/routes/scan.pyindex b626b98..378b624 100644--- a/backend/app/api/routes/scan.py+++ b/backend/app/api/routes/scan.py@@ -22,7 +22,12 @@ from app.db.models import (ScanRun,)from app.schemas.nodes import NodeCreate-from app.schemas.scan import InventoryDeviceCreate, InventoryDeviceResponse, ScanRunResponse+from app.schemas.scan import (+ InventoryDeviceCreate,+ InventoryDeviceResponse,+ InventoryDeviceUpdate,+ ScanRunResponse,+)from app.services.mac_utils import normalize_macfrom app.services.node_dedupe import dedupe_nodes_by_ieee, find_duplicate_nodefrom app.services.scanner import DeepScanOptions, _valid_port_range, request_cancel, run_scan@@ -355,6 +360,20 @@ async def create_pending(status="pending",discovery_source=body.discovery_source,discovery_sources=[body.discovery_source],+ os=body.os,+ services=body.services,+ friendly_name=body.friendly_name,+ device_subtype=body.device_subtype,+ label=body.label,+ type=body.type,+ notes=body.notes,+ cpu_count=body.cpu_count,+ cpu_model=body.cpu_model,+ ram_gb=body.ram_gb,+ disk_gb=body.disk_gb,+ show_hardware=body.show_hardware,+ check_method=body.check_method,+ check_target=body.check_target,)db.add(device)await db.commit()@@ -362,6 +381,37 @@ async def create_pending(return (await _with_canvas_counts(db, [device]))[0][email protected]("/pending/{device_id}", response_model=InventoryDeviceResponse)+async def update_pending(+ device_id: str,+ body: InventoryDeviceUpdate,+ db: AsyncSession = Depends(get_db),+ _: str = Depends(get_current_user),+) -> InventoryDevice:+ """Edit an inventory row — the device facts, not its lifecycle.++ The inventory row owns what a device *is*; a canvas node only owns how it is+ drawn. This is the write path behind the device detail modal, and applies+ only the fields the client actually sent.+ """+ device = (+ await db.execute(select(InventoryDevice).where(InventoryDevice.id == device_id))+ ).scalar_one_or_none()+ if not device:+ raise HTTPException(status_code=404, detail="Device not found")++ data = body.model_dump(exclude_unset=True)+ if "mac" in data:+ # Same reason as create_pending: dedup matches MACs by equality.+ data["mac"] = normalize_mac(data["mac"])+ for field, value in data.items():+ setattr(device, field, value)++ await db.commit()+ await db.refresh(device)+ return (await _with_canvas_counts(db, [device]))[0]++@router.delete("/pending", response_model=dict)async def clear_pending(db: AsyncSession = Depends(get_db),diff --git a/backend/app/db/database.py b/backend/app/db/database.pyindex e8c9fab..591449e 100644--- a/backend/app/db/database.py+++ b/backend/app/db/database.py@@ -426,6 +426,55 @@ async def init_db() -> None:await conn.exec_driver_sql("UPDATE nodes SET mac = lower(replace(mac, '-', ':')) WHERE mac IS NOT NULL")+ # 3.3.0 — the inventory row owns the device facts, the canvas node only+ # owns how it is drawn. These columns receive what used to live solely on+ # `nodes`. Additive here; `nodes` keeps its copies until the backfill has+ # run and been verified.+ inventory_device_migrations: list[tuple[str, str]] = [+ ("device_inventory.label", "ALTER TABLE device_inventory ADD COLUMN label TEXT"),+ ("device_inventory.type", "ALTER TABLE device_inventory ADD COLUMN type TEXT"),+ ("device_inventory.notes", "ALTER TABLE device_inventory ADD COLUMN notes TEXT"),+ ("device_inventory.cpu_count", "ALTER TABLE device_inventory ADD COLUMN cpu_count INTEGER"),+ ("device_inventory.cpu_model", "ALTER TABLE device_inventory ADD COLUMN cpu_model TEXT"),+ ("device_inventory.ram_gb", "ALTER TABLE device_inventory ADD COLUMN ram_gb FLOAT"),+ ("device_inventory.disk_gb", "ALTER TABLE device_inventory ADD COLUMN disk_gb FLOAT"),+ (+ "device_inventory.show_hardware",+ "ALTER TABLE device_inventory ADD COLUMN show_hardware BOOLEAN DEFAULT 0",+ ),+ ("device_inventory.check_method", "ALTER TABLE device_inventory ADD COLUMN check_method TEXT"),+ ("device_inventory.check_target", "ALTER TABLE device_inventory ADD COLUMN check_target TEXT"),+ (+ "device_inventory.status_live",+ "ALTER TABLE device_inventory ADD COLUMN status_live TEXT DEFAULT 'unknown'",+ ),+ ("device_inventory.last_seen", "ALTER TABLE device_inventory ADD COLUMN last_seen DATETIME"),+ ("device_inventory.last_scan", "ALTER TABLE device_inventory ADD COLUMN last_scan DATETIME"),+ (+ "device_inventory.response_time_ms",+ "ALTER TABLE device_inventory ADD COLUMN response_time_ms INTEGER",+ ),+ ("device_inventory.updated_at", "ALTER TABLE device_inventory ADD COLUMN updated_at DATETIME"),+ ]+ for label, sql in inventory_device_migrations:+ await _try_migrate(conn, sql, label=label)+ # Backfill the columns that carry a non-NULL default in the model, so a+ # legacy row round-trips through Pydantic without tripping the validators.+ for label, sql in (+ (+ "device_inventory.status_live.backfill",+ "UPDATE device_inventory SET status_live = 'unknown' WHERE status_live IS NULL",+ ),+ (+ "device_inventory.show_hardware.backfill",+ "UPDATE device_inventory SET show_hardware = 0 WHERE show_hardware IS NULL",+ ),+ (+ "device_inventory.updated_at.backfill",+ "UPDATE device_inventory SET updated_at = discovered_at WHERE updated_at IS NULL",+ ),+ ):+ await _try_migrate(conn, sql, label=label)async def get_db() -> AsyncGenerator[AsyncSession, None]:diff --git a/backend/app/db/models.py b/backend/app/db/models.pyindex 9fc193a..0e7f4cd 100644--- a/backend/app/db/models.py+++ b/backend/app/db/models.py@@ -236,6 +236,32 @@ class InventoryDevice(Base):properties: Mapped[list[Any]] = mapped_column(JSON, default=list)discovered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=_now)+ # --- Curated device facts (3.3.0) -------------------------------------+ # The inventory row, not the canvas node, owns what the device *is*. A node+ # only says how it is drawn. `label`/`type` supersede friendly_name/+ # suggested_type for a device that reached a canvas; the older pair is kept+ # so discovery imports and the source filters keep working unchanged.+ label: Mapped[str | None] = mapped_column(String, nullable=True)+ type: Mapped[str | None] = mapped_column(String, nullable=True)+ notes: Mapped[str | None] = mapped_column(Text, nullable=True)+ cpu_count: Mapped[int | None] = mapped_column(Integer, nullable=True)+ cpu_model: Mapped[str | None] = mapped_column(String, nullable=True)+ ram_gb: Mapped[float | None] = mapped_column(Float, nullable=True)+ disk_gb: Mapped[float | None] = mapped_column(Float, nullable=True)+ show_hardware: Mapped[bool] = mapped_column(Boolean, default=False)+ check_method: Mapped[str | None] = mapped_column(String, nullable=True)+ check_target: Mapped[str | None] = mapped_column(String, nullable=True)+ # Live reachability from the status checker. NOT `status` — that column holds+ # the inventory lifecycle (pending/approved/hidden) and the two must not be+ # conflated.+ status_live: Mapped[str] = mapped_column(String, default="unknown")+ last_seen: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ last_scan: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)+ response_time_ms: Mapped[int | None] = mapped_column(Integer, nullable=True)+ updated_at: Mapped[datetime] = mapped_column(+ DateTime(timezone=True), default=_now, onupdate=_now+ )+# Transient (not persisted): populated per-request by the scan routes to report# how many canvases this device already appears on. Not a mapped column.canvas_count: int = 0diff --git a/backend/app/schemas/scan.py b/backend/app/schemas/scan.pyindex 66a390b..d9cb31e 100644--- a/backend/app/schemas/scan.py+++ b/backend/app/schemas/scan.py@@ -27,6 +27,26 @@ class InventoryDeviceResponse(BaseModel):# the node on approve; empty for scan/mesh sources that don't set them.properties: list[Any] = []discovered_at: datetime+ # Curated device facts (3.3.0). `label`/`type` supersede friendly_name/+ # suggested_type once the user has named the device; the older pair stays for+ # discovery imports and the source filters.+ label: str | None = None+ type: str | None = None+ notes: str | None = None+ cpu_count: int | None = None+ cpu_model: str | None = None+ ram_gb: float | None = None+ disk_gb: float | None = None+ show_hardware: bool = False+ check_method: str | None = None+ check_target: str | None = None+ # Live reachability, distinct from `status` (the pending/approved/hidden+ # lifecycle).+ status_live: str = "unknown"+ last_seen: datetime | None = None+ last_scan: datetime | None = None+ response_time_ms: int | None = None+ updated_at: datetime | None = None# Number of distinct canvases (designs) this device already appears on,# correlated by ip / ieee_address against existing nodes. Computed per-request.canvas_count: int = 0@@ -38,12 +58,22 @@ class InventoryDeviceResponse(BaseModel):node_last_modified: datetime | None = Nonenode_last_seen: datetime | None = None- @field_validator("properties", "discovery_sources", mode="before")+ @field_validator("properties", "discovery_sources", "services", mode="before")@classmethoddef _coerce_list(cls, v: Any) -> list[Any]:# Legacy rows (columns added by migration) have these = NULL.return v if isinstance(v, list) else []+ @field_validator("status_live", mode="before")+ @classmethod+ def _coerce_status_live(cls, v: Any) -> str:+ return v if isinstance(v, str) and v else "unknown"++ @field_validator("show_hardware", mode="before")+ @classmethod+ def _coerce_show_hardware(cls, v: Any) -> bool:+ return bool(v)+model_config = {"from_attributes": True}@@ -73,6 +103,22 @@ class InventoryDeviceCreate(BaseModel):vendor: str | None = Noneproperties: list[Any] = []discovery_source: str = "manual"+ # Curated fields, so a hand-made entry can carry everything the edit modal+ # shows rather than needing a create-then-PATCH round trip.+ os: str | None = None+ services: list[Any] = []+ friendly_name: str | None = None+ device_subtype: str | None = None+ label: str | None = None+ type: str | None = None+ notes: str | None = None+ cpu_count: int | None = None+ cpu_model: str | None = None+ ram_gb: float | None = None+ disk_gb: float | None = None+ show_hardware: bool = False+ check_method: str | None = None+ check_target: str | None = None@field_validator("discovery_source")@classmethod@@ -82,6 +128,39 @@ class InventoryDeviceCreate(BaseModel):return v+class InventoryDeviceUpdate(BaseModel):+ """Partial edit of an inventory row — the write half of the detail modal.++ Every field is optional and only what the client sends is applied+ (`exclude_unset`), so a caller editing one field never clears the rest.+ Lifecycle (`status`) and discovery bookkeeping (`discovery_source(s)`,+ `discovered_at`, `ieee_address`) are deliberately not editable here: those+ are owned by the approve/hide routes and the importers.+ """++ ip: str | None = None+ mac: str | None = None+ hostname: str | None = None+ os: str | None = None+ label: str | None = None+ type: str | None = None+ suggested_type: str | None = None+ friendly_name: str | None = None+ device_subtype: str | None = None+ model: str | None = None+ vendor: str | None = None+ services: list[Any] | None = None+ properties: list[Any] | None = None+ notes: str | None = None+ cpu_count: int | None = None+ cpu_model: str | None = None+ ram_gb: float | None = None+ disk_gb: float | None = None+ show_hardware: bool | None = None+ check_method: str | None = None+ check_target: str | None = None++class ScanRunResponse(BaseModel):id: strstatus: strdiff --git a/backend/tests/scan/test_scan_inventory_edit.py b/backend/tests/scan/test_scan_inventory_edit.pynew file mode 100644index 0000000..4da4eed--- /dev/null+++ b/backend/tests/scan/test_scan_inventory_edit.py@@ -0,0 +1,165 @@+"""Editing an inventory row: PATCH /scan/pending/{id} and the widened create.++The inventory row owns the device facts, so it has to be editable on its own —+not only through a canvas node.+"""+import pytest+from httpx import AsyncClient++from app.db.models import InventoryDevice+++async def _seed(db_session, **kwargs) -> InventoryDevice:+ device = InventoryDevice(+ ip="192.168.1.10",+ mac="aa:bb:cc:11:22:33",+ hostname="nas",+ services=[{"port": 22, "protocol": "tcp", "service_name": "ssh"}],+ suggested_type="nas",+ status="pending",+ discovery_source="arp",+ discovery_sources=["arp"],+ properties=[{"key": "Rack", "value": "A1", "icon": None, "visible": True}],+ **kwargs,+ )+ db_session.add(device)+ await db_session.commit()+ return device+++async def test_update_pending_requires_auth(client: AsyncClient, db_session):+ device = await _seed(db_session)+ res = await client.patch(f"/api/v1/scan/pending/{device.id}", json={"hostname": "x"})+ assert res.status_code == 401+++async def test_update_pending_edits_curated_fields(client: AsyncClient, headers, db_session):+ device = await _seed(db_session)+ res = await client.patch(+ f"/api/v1/scan/pending/{device.id}",+ headers=headers,+ json={+ "label": "Big NAS",+ "type": "nas",+ "notes": "in the garage rack",+ "cpu_count": 4,+ "cpu_model": "N5105",+ "ram_gb": 16.0,+ "disk_gb": 4000.0,+ "show_hardware": True,+ "check_method": "http",+ "check_target": "http://192.168.1.10:5000",+ "properties": [+ {"key": "Rack", "value": "B2", "icon": None, "visible": True},+ {"key": "Owner", "value": "me", "icon": None, "visible": False},+ ],+ "services": [+ {"port": 22, "protocol": "tcp", "service_name": "ssh"},+ {"port": 5000, "protocol": "tcp", "service_name": "http"},+ ],+ },+ )+ assert res.status_code == 200+ data = res.json()+ assert data["label"] == "Big NAS"+ assert data["notes"] == "in the garage rack"+ assert data["cpu_count"] == 4+ assert data["ram_gb"] == 16.0+ assert data["show_hardware"] is True+ assert data["check_method"] == "http"+ assert len(data["properties"]) == 2+ assert len(data["services"]) == 2+++async def test_update_pending_is_partial(client: AsyncClient, headers, db_session):+ """Sending one field must not clear the others."""+ device = await _seed(db_session)+ res = await client.patch(+ f"/api/v1/scan/pending/{device.id}", headers=headers, json={"notes": "only this"}+ )+ assert res.status_code == 200+ data = res.json()+ assert data["notes"] == "only this"+ assert data["hostname"] == "nas"+ assert data["ip"] == "192.168.1.10"+ assert data["mac"] == "aa:bb:cc:11:22:33"+ assert data["suggested_type"] == "nas"+ assert len(data["services"]) == 1+ assert data["properties"][0]["key"] == "Rack"+++async def test_update_pending_normalizes_mac(client: AsyncClient, headers, db_session):+ device = await _seed(db_session)+ res = await client.patch(+ f"/api/v1/scan/pending/{device.id}", headers=headers, json={"mac": "AA-BB-CC-99-88-77"}+ )+ assert res.status_code == 200+ assert res.json()["mac"] == "aa:bb:cc:99:88:77"+++async def test_update_pending_leaves_lifecycle_alone(client: AsyncClient, headers, db_session):+ """`status` is owned by approve/hide, not by the edit modal."""+ device = await _seed(db_session)+ res = await client.patch(+ f"/api/v1/scan/pending/{device.id}",+ headers=headers,+ json={"label": "x", "status": "approved", "discovery_source": "manual"},+ )+ assert res.status_code == 200+ data = res.json()+ assert data["label"] == "x"+ assert data["status"] == "pending"+ assert data["discovery_source"] == "arp"+++async def test_update_pending_unknown_id(client: AsyncClient, headers):+ res = await client.patch("/api/v1/scan/pending/nope", headers=headers, json={"notes": "x"})+ assert res.status_code == 404+++async def test_create_pending_accepts_curated_fields(client: AsyncClient, headers):+ """A hand-made entry carries everything the modal shows, no PATCH round trip."""+ res = await client.post(+ "/api/v1/scan/pending",+ headers=headers,+ json={+ "hostname": "patch-panel",+ "os": "n/a",+ "label": "Patch panel 24p",+ "type": "switch",+ "notes": "passive",+ "services": [{"port": 80, "protocol": "tcp", "service_name": "http"}],+ "friendly_name": "PP-1",+ "device_subtype": "passive",+ "check_method": "none",+ "discovery_source": "manual",+ },+ )+ assert res.status_code == 201+ data = res.json()+ assert data["label"] == "Patch panel 24p"+ assert data["type"] == "switch"+ assert data["os"] == "n/a"+ assert data["notes"] == "passive"+ assert data["friendly_name"] == "PP-1"+ assert data["services"][0]["port"] == 80+ assert data["status"] == "pending"+++async def test_legacy_row_defaults_are_coerced(client: AsyncClient, headers, db_session):+ """Rows predating the 3.3.0 columns read back with defaults, not nulls."""+ device = await _seed(db_session)+ res = await client.get("/api/v1/scan/pending", headers=headers)+ assert res.status_code == 200+ row = next(d for d in res.json() if d["id"] == device.id)+ assert row["status_live"] == "unknown"+ assert row["show_hardware"] is False+ assert row["label"] is Nonediff --git a/frontend/src/api/client.ts b/frontend/src/api/client.tsindex f241700..9508feb 100644--- a/frontend/src/api/client.ts+++ b/frontend/src/api/client.ts@@ -1,6 +1,7 @@import axios from 'axios'import { useAuthStore } from '@/stores/authStore'import type { AuthMode, AuthUser } from '@/stores/authStore'+import type { InventoryEntry } from '@/types'export const api = axios.create({baseURL: '/api/v1',@@ -150,6 +151,13 @@ export const scanApi = {/** "manual" (default) or "rack" for gear created from a rack canvas. */discovery_source?: 'manual' | 'rack'}) => api.post<{ id: string; hostname: string | null }>('/scan/pending', data),+ /**+ * Edit an inventory row. Partial: only the keys sent are applied, so a caller+ * touching one field never clears the rest. Lifecycle (`status`) and discovery+ * bookkeeping are not editable — approve/hide own those.+ */+ updatePending: (id: string, data: Partial<Omit<InventoryEntry, 'id' | 'status' | 'discovered_at'>>) =>+ api.patch<InventoryEntry>(`/scan/pending/${id}`, data),hidden: () => api.get('/scan/hidden'),runs: () => api.get('/scan/runs'),clearPending: () => api.delete('/scan/pending'),diff --git a/frontend/src/components/modals/DeviceInventoryModal.tsx b/frontend/src/components/modals/DeviceInventoryModal.tsxindex e3314ba..cbce41c 100644--- a/frontend/src/components/modals/DeviceInventoryModal.tsx+++ b/frontend/src/components/modals/DeviceInventoryModal.tsx@@ -798,6 +798,12 @@ export function DeviceInventoryModal({ open, onClose, highlightId, initialStatusonApprove={handleApprove}onHide={handleHide}onIgnore={handleIgnore}+ onSaved={(saved) => {+ // Patch in place rather than refetch: the grid keeps its scroll+ // position and the open detail modal keeps showing the same device.+ setDevices((prev) => prev.map((d) => (d.id === saved.id ? saved : d)))+ setSelected(saved)+ }}/></>)diff --git a/frontend/src/components/modals/InventoryDeviceModal.tsx b/frontend/src/components/modals/InventoryDeviceModal.tsxindex bedb034..b395dff 100644--- a/frontend/src/components/modals/InventoryDeviceModal.tsx+++ b/frontend/src/components/modals/InventoryDeviceModal.tsx@@ -1,49 +1,30 @@-import { Globe, Router, Server, Layers, Box, Container, HardDrive, Cpu, Wifi, Circle, Network } from 'lucide-react'+/**+ * Device Inventory detail — show *and* edit.+ *+ * The inventory row owns what a device is; a canvas node only owns how it is+ * drawn. So everything a user can curate on a node — properties, services,+ * notes, hardware specs, check method — is editable here too, through the same+ * editors the canvas uses (`PropertyList`, `ServiceModal`).+ */+import { useEffect, useState } from 'react'+import { Globe, Router, Server, Layers, Box, Container, HardDrive, Cpu, Wifi, Circle, Network, Pencil, Plus, X } from 'lucide-react'+import { toast } from 'sonner'import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Textarea } from '@/components/ui/textarea'+import { Label } from '@/components/ui/label'+import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectSeparator, SelectTrigger, SelectValue } from '@/components/ui/select'+import { PropertyList } from '@/components/common/PropertyList'+import { ServiceModal } from './ServiceModal'+import { scanApi } from '@/api/client'import { isRackDevice } from '@/utils/deviceSources'-import type { NodeProperty } from '@/types'--interface Service {- port: number- protocol: string- service_name: string- icon?: string | null- category?: string | null-}+import { DEVICE_TYPE_GROUPS } from '@/utils/nodeTypeGroups'+import { serviceToForm, type ServiceFormData, type ServiceSubmitData } from '@/utils/serviceForm'+import { NODE_TYPE_LABELS, type CheckMethod, type InventoryEntry, type NodeProperty, type ServiceInfo } from '@/types'-export interface InventoryEntry {- id: string- ip: string | null- mac: string | null- hostname: string | null- os: string | null- services: Service[]- suggested_type: string | null- status: string- discovery_source: string | null- // All sources that have observed this device (e.g. ["arp", "proxmox"]). A- // merged device shows under every matching filter. Falls back to- // [discovery_source] when absent (older rows).- discovery_sources?: string[]- ieee_address?: string | null- friendly_name?: string | null- device_subtype?: string | null- model?: string | null- vendor?: string | null- lqi?: number | null- // Display properties carried from discovery (e.g. Proxmox specs).- properties?: NodeProperty[]- discovered_at: string- // How many canvases (designs) this device already appears on. Computed server-side.- canvas_count?: number- // Timestamps from the linked canvas node(s), correlated by ip/ieee_address.- // Null/absent when the device is not on any canvas yet.- node_created_at?: string | null- node_last_scan?: string | null- node_last_modified?: string | null- node_last_seen?: string | null-}+// Home is `@/types` now — re-exported because most call sites import it here.+export type { InventoryEntry } from '@/types'interface InventoryDeviceModalProps {device: InventoryEntry | null@@ -51,6 +32,8 @@ interface InventoryDeviceModalProps {onApprove: (device: InventoryEntry) => voidonHide: (device: InventoryEntry) => voidonIgnore: (device: InventoryEntry) => void+ /** Called with the saved row after an edit, so the list can refresh in place. */+ onSaved?: (device: InventoryEntry) => void}const TYPE_ICONS: Record<string, React.ElementType> = {@@ -81,11 +64,19 @@ const CATEGORY_COLORS: Record<string, string> = {iot: '#e3b341',}+const CHECK_METHODS: CheckMethod[] = ['ping', 'http', 'https', 'tcp', 'ssh', 'prometheus', 'health', 'none']+function categoryColor(category: string | null | undefined) {if (!category) return '#8b949e'return CATEGORY_COLORS[category.toLowerCase()] ?? '#8b949e'}+/** Server datetimes come back naive-UTC on legacy rows; pin the zone before parsing. */+function formatDate(value: string | null | undefined): string | null {+ if (!value) return null+ return new Date(value.endsWith('Z') ? value : value + 'Z').toLocaleString()+}+function InfoRow({ label, value }: { label: string; value: string }) {return (<div className="flex items-baseline gap-2 text-xs">@@ -95,21 +86,148 @@ function InfoRow({ label, value }: { label: string; value: string }) {)}-export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore }: InventoryDeviceModalProps) {+/** The editable subset of an inventory row, as strings for the form inputs. */+interface EditForm {+ label: string+ type: string+ hostname: string+ ip: string+ mac: string+ os: string+ vendor: string+ model: string+ friendly_name: string+ device_subtype: string+ notes: string+ cpu_count: string+ cpu_model: string+ ram_gb: string+ disk_gb: string+ show_hardware: boolean+ check_method: string+ check_target: string+}++function toForm(d: InventoryEntry): EditForm {+ return {+ label: d.label ?? '',+ // Falls back to the discovery guess, so a first edit adopts it rather than+ // silently clearing what the scanner suggested.+ type: d.type ?? d.suggested_type ?? '',+ hostname: d.hostname ?? '',+ ip: d.ip ?? '',+ mac: d.mac ?? '',+ os: d.os ?? '',+ vendor: d.vendor ?? '',+ model: d.model ?? '',+ friendly_name: d.friendly_name ?? '',+ device_subtype: d.device_subtype ?? '',+ notes: d.notes ?? '',+ cpu_count: d.cpu_count != null ? String(d.cpu_count) : '',+ cpu_model: d.cpu_model ?? '',+ ram_gb: d.ram_gb != null ? String(d.ram_gb) : '',+ disk_gb: d.disk_gb != null ? String(d.disk_gb) : '',+ show_hardware: d.show_hardware ?? false,+ check_method: d.check_method ?? '',+ check_target: d.check_target ?? '',+ }+}++const nullable = (v: string) => (v.trim() === '' ? null : v.trim())+const numeric = (v: string) => (v.trim() === '' ? null : Number(v))++export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnore, onSaved }: InventoryDeviceModalProps) {+ const [editing, setEditing] = useState(false)+ const [form, setForm] = useState<EditForm>(() => (device ? toForm(device) : toForm({} as InventoryEntry)))+ const [properties, setProperties] = useState<NodeProperty[]>(device?.properties ?? [])+ const [services, setServices] = useState<ServiceInfo[]>(device?.services ?? [])+ const [svcModal, setSvcModal] = useState<{ index: number | null; form?: ServiceFormData } | null>(null)+ const [saving, setSaving] = useState(false)++ // Reset the form whenever the modal is pointed at another device — the+ // component stays mounted across card clicks in the inventory grid.+ useEffect(() => {+ if (!device) return+ setForm(toForm(device))+ setProperties(device.properties ?? [])+ setServices(device.services ?? [])+ setEditing(false)+ setSvcModal(null)+ }, [device])+if (!device) return null- const TypeIcon = TYPE_ICONS[device.suggested_type ?? 'generic'] ?? Circle+ const TypeIcon = TYPE_ICONS[device.type ?? device.suggested_type ?? 'generic'] ?? Circleconst isZigbee = device.discovery_source === 'zigbee'const rackOnly = isRackDevice(device)- const titleLabel = device.friendly_name ?? device.hostname ?? device.ip ?? device.ieee_address ?? 'Pending device'+ const titleLabel = device.label ?? device.friendly_name ?? device.hostname ?? device.ip ?? device.ieee_address ?? 'Pending device'++ const set = <K extends keyof EditForm>(key: K, value: EditForm[K]) => setForm((f) => ({ ...f, [key]: value }))const handleApprove = () => { onApprove(device) }const handleHide = () => { onHide(device); onClose() }const handleIgnore = () => { onIgnore(device); onClose() }+ const handleSubmitService = (data: ServiceSubmitData) => {+ const svc: ServiceInfo = {+ ...(data.port != null ? { port: data.port } : {}),+ protocol: data.protocol,+ service_name: data.service_name,+ ...(data.path ? { path: data.path } : {}),+ ...(data.host ? { host: data.host } : {}),+ ...(data.icon ? { icon: data.icon } : {}),+ }+ setServices((prev) =>+ svcModal?.index == null ? [...prev, svc] : prev.map((s, i) => (i === svcModal.index ? { ...s, ...svc } : s))+ )+ }++ const handleSave = async () => {+ setSaving(true)+ try {+ const res = await scanApi.updatePending(device.id, {+ label: nullable(form.label),+ type: nullable(form.type),+ hostname: nullable(form.hostname),+ ip: nullable(form.ip),+ mac: nullable(form.mac),+ os: nullable(form.os),+ vendor: nullable(form.vendor),+ model: nullable(form.model),+ friendly_name: nullable(form.friendly_name),+ device_subtype: nullable(form.device_subtype),+ notes: nullable(form.notes),+ cpu_count: numeric(form.cpu_count),+ cpu_model: nullable(form.cpu_model),+ ram_gb: numeric(form.ram_gb),+ disk_gb: numeric(form.disk_gb),+ show_hardware: form.show_hardware,+ check_method: nullable(form.check_method) as CheckMethod | null,+ check_target: nullable(form.check_target),+ properties,+ services,+ })+ toast.success('Device updated')+ setEditing(false)+ onSaved?.(res.data)+ } catch {+ toast.error('Could not update device')+ } finally {+ setSaving(false)+ }+ }++ const discoveredAt = formatDate(device.discovered_at)+ const hardware = [+ device.cpu_count != null ? `${device.cpu_count} vCPU` : null,+ device.cpu_model,+ device.ram_gb != null ? `${device.ram_gb} GB RAM` : null,+ device.disk_gb != null ? `${device.disk_gb} GB disk` : null,+ ].filter(Boolean).join(' · ')+return (<Dialog open={!!device} onOpenChange={(o) => !o && onClose()}>- <DialogContent className="bg-[#161b22] border-[#30363d] text-foreground max-w-sm">+ <DialogContent className={`bg-[#161b22] border-[#30363d] text-foreground ${editing ? 'max-w-lg' : 'max-w-sm'} max-h-[85vh] overflow-y-auto`}><DialogHeader><DialogTitle className="flex items-center gap-2 text-sm font-semibold"><TypeIcon size={15} className="text-[#00d4ff] shrink-0" />@@ -122,6 +240,166 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn</DialogTitle></DialogHeader>+ {editing ? (+ <div className="flex flex-col gap-3 mt-1">+ <div className="grid grid-cols-2 gap-2">+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Name</Label>+ <Input value={form.label} onChange={(e) => set('label', e.target.value)} placeholder="Display name" className="bg-[#21262d] border-[#30363d] text-xs h-7" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Type</Label>+ <Select value={form.type || undefined} onValueChange={(v) => set('type', (v as string | null) ?? '')}>+ <SelectTrigger className="bg-[#21262d] border-[#30363d] text-xs h-7">+ <SelectValue placeholder="Pick a type" />+ </SelectTrigger>+ <SelectContent>+ {DEVICE_TYPE_GROUPS.map((group, i) => (+ <SelectGroup key={group.label}>+ {i > 0 && <SelectSeparator />}+ <SelectLabel className="text-[10px]">{group.label}</SelectLabel>+ {group.types.map((t) => (+ <SelectItem key={t} value={t} className="text-xs">+ {NODE_TYPE_LABELS[t] ?? t}+ </SelectItem>+ ))}+ </SelectGroup>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Hostname</Label>+ <Input value={form.hostname} onChange={(e) => set('hostname', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">IP</Label>+ <Input value={form.ip} onChange={(e) => set('ip', e.target.value)} placeholder="10.0.0.5, 10.0.1.5" className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">MAC</Label>+ <Input value={form.mac} onChange={(e) => set('mac', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">OS</Label>+ <Input value={form.os} onChange={(e) => set('os', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Vendor</Label>+ <Input value={form.vendor} onChange={(e) => set('vendor', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Model</Label>+ <Input value={form.model} onChange={(e) => set('model', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Check method</Label>+ <Select value={form.check_method || undefined} onValueChange={(v) => set('check_method', (v as string | null) ?? '')}>+ <SelectTrigger className="bg-[#21262d] border-[#30363d] text-xs h-7">+ <SelectValue placeholder="None" />+ </SelectTrigger>+ <SelectContent>+ {CHECK_METHODS.map((m) => (+ <SelectItem key={m} value={m} className="text-xs">{m}</SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Check target</Label>+ <Input value={form.check_target} onChange={(e) => set('check_target', e.target.value)} placeholder="host:port or URL" className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">vCPU</Label>+ <Input value={form.cpu_count} onChange={(e) => set('cpu_count', e.target.value.replace(/\D/g, ''))} className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">CPU model</Label>+ <Input value={form.cpu_model} onChange={(e) => set('cpu_model', e.target.value)} className="bg-[#21262d] border-[#30363d] text-xs h-7" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">RAM (GB)</Label>+ <Input value={form.ram_gb} onChange={(e) => set('ram_gb', e.target.value.replace(/[^\d.]/g, ''))} className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Disk (GB)</Label>+ <Input value={form.disk_gb} onChange={(e) => set('disk_gb', e.target.value.replace(/[^\d.]/g, ''))} className="bg-[#21262d] border-[#30363d] text-xs h-7 font-mono" />+ </div>+ </div>++ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={form.show_hardware}+ onChange={(e) => set('show_hardware', e.target.checked)}+ className="accent-[#00d4ff] w-3 h-3"+ />+ <span className="text-[10px] text-muted-foreground">Show hardware specs on the node</span>+ </label>++ <div className="flex flex-col gap-1">+ <Label className="text-[10px] text-muted-foreground">Notes</Label>+ <Textarea value={form.notes} onChange={(e) => set('notes', e.target.value)} rows={3} className="bg-[#21262d] border-[#30363d] text-xs" />+ </div>++ {/* Same editors as the canvas — one implementation, one behaviour. */}+ <div className="-mx-6">+ <PropertyList properties={properties} onChange={setProperties} visibleLabel="Show on node" />+ </div>++ <div className="border-t border-border pt-3">+ <div className="flex items-center justify-between mb-2">+ <span className="text-xs text-muted-foreground">Services{services.length > 0 ? ` (${services.length})` : ''}</span>+ <button onClick={() => setSvcModal({ index: null })} className="flex items-center gap-1 text-[10px] text-[#00d4ff] hover:text-[#00d4ff]/80 transition-colors cursor-pointer">+ <Plus size={10} /> Add+ </button>+ </div>+ {services.length === 0 ? (+ <p className="text-[10px] text-muted-foreground/50">No services — click Add to register one.</p>+ ) : (+ <div className="flex flex-col gap-1.5">+ {services.map((svc, i) => (+ <div key={`${svc.port ?? 'host'}-${svc.protocol}-${i}`} className="group flex items-center gap-2 px-2 py-1.5 rounded bg-[#21262d] border border-[#30363d] text-xs">+ <span className="font-mono text-[#00d4ff] w-10 shrink-0">{svc.port ?? '—'}</span>+ <span className="text-muted-foreground w-7 shrink-0">{svc.protocol}</span>+ <span className="text-foreground truncate">{svc.service_name}</span>+ <div className="ml-auto flex items-center gap-1 shrink-0">+ <button+ onClick={() => setSvcModal({ index: i, form: serviceToForm(svc) })}+ title="Edit service"+ className="text-[#8b949e] hover:text-[#00d4ff]"+ >+ <Pencil size={10} />+ </button>+ <button+ onClick={() => setServices((prev) => prev.filter((_, j) => j !== i))}+ title="Remove service"+ className="text-[#8b949e] hover:text-[#f85149]"+ >+ <X size={10} />+ </button>+ </div>+ </div>+ ))}+ </div>+ )}+ </div>++ <div className="flex gap-2 pt-1">+ <Button+ size="sm"+ className="flex-1 bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90"+ onClick={handleSave}+ disabled={saving}+ >+ {saving ? 'Saving…' : 'Save'}+ </Button>+ <Button size="sm" variant="ghost" className="flex-1" onClick={() => { setEditing(false); setForm(toForm(device)); setProperties(device.properties ?? []); setServices(device.services ?? []) }}>+ Cancel+ </Button>+ </div>+ </div>+ ) : (<div className="flex flex-col gap-4 mt-1">{/* Device info */}<div className="flex flex-col gap-1.5 p-3 rounded-md bg-[#21262d] border border-[#30363d]">@@ -137,15 +415,53 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn{device.model && <InfoRow label="Model" value={device.model} />}{device.device_subtype && <InfoRow label="Role" value={device.device_subtype} />}{device.lqi != null && <InfoRow label="LQI" value={String(device.lqi)} />}- {device.suggested_type && (- <InfoRow label="Type" value={device.suggested_type} />+ {(device.type ?? device.suggested_type) && (+ <InfoRow label="Type" value={(device.type ?? device.suggested_type) as string} />+ )}+ {hardware && <InfoRow label="Hardware" value={hardware} />}+ {device.check_method && (+ <InfoRow label="Check" value={device.check_target ? `${device.check_method} → ${device.check_target}` : device.check_method} />+ )}+ {device.status_live && device.status_live !== 'unknown' && (+ <InfoRow label="Live" value={device.status_live} />)}{device.discovery_source && (<InfoRow label="Source" value={device.discovery_source.toUpperCase()} />)}- <InfoRow label="Discovered" value={new Date(device.discovered_at.endsWith('Z') ? device.discovered_at : device.discovered_at + 'Z').toLocaleString()} />+ {device.canvas_count != null && device.canvas_count > 0 && (+ <InfoRow label="Canvases" value={String(device.canvas_count)} />+ )}+ {discoveredAt && <InfoRow label="Discovered" value={discoveredAt} />}+ {formatDate(device.node_last_scan) && <InfoRow label="Last scan" value={formatDate(device.node_last_scan) as string} />}+ {formatDate(device.node_last_seen) && <InfoRow label="Last seen" value={formatDate(device.node_last_seen) as string} />}+ {formatDate(device.node_last_modified) && <InfoRow label="Modified" value={formatDate(device.node_last_modified) as string} />}</div>+ {/* Properties */}+ {device.properties && device.properties.length > 0 && (+ <div>+ <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">+ Properties ({device.properties.length})+ </p>+ <div className="flex flex-col gap-1">+ {device.properties.map((prop, i) => (+ <div key={`${prop.key}-${i}`} className="flex items-baseline gap-2 px-2.5 py-1.5 rounded bg-[#21262d] border border-[#30363d] text-xs">+ <span className="text-muted-foreground shrink-0">{prop.key}</span>+ <span className="font-mono text-foreground break-all">{prop.value}</span>+ </div>+ ))}+ </div>+ </div>+ )}++ {/* Notes */}+ {device.notes && (+ <div>+ <p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">Notes</p>+ <p className="text-xs text-foreground/80 whitespace-pre-wrap">{device.notes}</p>+ </div>+ )}+{/* Services (skipped for Zigbee devices — they don't have IP services) */}{!isZigbee && <div><p className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-1.5">@@ -191,6 +507,14 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgnApprove</Button>)}+ <Button+ size="sm"+ variant="ghost"+ className="flex-1 text-[#00d4ff] hover:text-[#00d4ff] hover:bg-[#00d4ff]/10"+ onClick={() => setEditing(true)}+ >+ Edit+ </Button><Buttonsize="sm"variant="ghost"@@ -209,6 +533,19 @@ export function InventoryDeviceModal({ device, onClose, onApprove, onHide, onIgn</Button></div></div>+ )}++ {svcModal && (+ <ServiceModal+ key={`svc-${svcModal.index ?? 'new'}`}+ open+ onClose={() => setSvcModal(null)}+ onSubmit={handleSubmitService}+ initial={svcModal.form}+ title={svcModal.index === null ? 'Add Service' : 'Edit Service'}+ confirmLabel={svcModal.index === null ? 'Add' : 'Save'}+ />+ )}</DialogContent></Dialog>)diff --git a/frontend/src/components/modals/NodeModal.tsx b/frontend/src/components/modals/NodeModal.tsxindex 88ae47e..f5ab6ae 100644--- a/frontend/src/components/modals/NodeModal.tsx+++ b/frontend/src/components/modals/NodeModal.tsx@@ -14,17 +14,7 @@ import { ICON_REGISTRY, NODE_TYPE_DEFAULT_ICONS, isBrandIconKey, brandIconSlug,import { IconPickerPanel } from './IconPickerPanel'import { MAX_HANDLES, MIN_HANDLES, clampHandles, sideDefault, handleCountField, type Side } from '@/utils/handleUtils'import { isValidParentNode } from '@/utils/virtualEdgeParent'--const NODE_TYPE_GROUPS: { label: string; types: NodeType[] }[] = [- { label: 'Hardware', types: ['isp', 'router', 'firewall', 'switch', 'server', 'nas', 'kvm', 'ap', 'printer'] },- { label: 'Virtualization', types: ['proxmox', 'vm', 'lxc', 'docker_host', 'docker_container'] },- { label: 'IoT', types: ['iot', 'camera', 'cpl'] },- { label: 'Zigbee', types: ['zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice'] },- { label: 'Z-Wave', types: ['zwave_coordinator', 'zwave_router', 'zwave_enddevice'] },- { label: 'Personal', types: ['computer', 'laptop', 'mobile'] },- { label: 'Electrical', types: ['grid', 'ups', 'battery', 'generator', 'solar_panel', 'inverter', 'circuit_breaker', 'contactor', 'electrical_switch', 'socket', 'light', 'meter', 'transformer', 'load'] },- { label: 'Generic', types: ['generic', 'groupRect'] },-]+import { NODE_TYPE_GROUPS } from '@/utils/nodeTypeGroups'// Maps a side to its per-type default field on NodeTypeStyle.const SIDE_STYLE_KEY: Record<Side, keyof NodeTypeStyle> = {diff --git a/frontend/src/components/modals/__tests__/InventoryDeviceModalEdit.test.tsx b/frontend/src/components/modals/__tests__/InventoryDeviceModalEdit.test.tsxnew file mode 100644index 0000000..3c0e7f0--- /dev/null+++ b/frontend/src/components/modals/__tests__/InventoryDeviceModalEdit.test.tsx@@ -0,0 +1,194 @@+/**+ * Edit mode of the device detail modal — the write half of "the inventory row+ * owns the device facts".+ */+import { describe, it, expect, beforeEach, vi } from 'vitest'+import { render, screen, fireEvent, waitFor } from '@testing-library/react'+import { InventoryDeviceModal } from '../InventoryDeviceModal'+import type { InventoryEntry } from '@/types'++const mockUpdatePending = vi.fn()++vi.mock('@/api/client', () => ({+ scanApi: {+ updatePending: (...a: unknown[]) => mockUpdatePending(...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()+ mockUpdatePending.mockResolvedValue({ data: makeDevice({ label: 'Saved' }) })+})++describe('InventoryDeviceModal — view mode extras', () => {+ it('shows the curated fields the inventory row now owns', () => {+ render(+ <InventoryDeviceModal+ {...noop}+ device={makeDevice({+ notes: 'garage rack',+ cpu_count: 4,+ ram_gb: 16,+ check_method: 'http',+ check_target: 'http://192.168.1.100',+ properties: [{ key: 'Owner', value: 'me', icon: null, visible: true }],+ })}+ />+ )+ expect(screen.getByText('garage rack')).toBeInTheDocument()+ expect(screen.getByText('4 vCPU · 16 GB RAM')).toBeInTheDocument()+ expect(screen.getByText('http → http://192.168.1.100')).toBeInTheDocument()+ expect(screen.getByText('Owner')).toBeInTheDocument()+ expect(screen.getByText('me')).toBeInTheDocument()+ })++ it('prefers the curated label and type over the discovery guesses', () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice({ label: 'Big NAS', type: 'nas' })} />)+ expect(screen.getAllByText('Big NAS').length).toBeGreaterThan(0)+ expect(screen.getByText('nas')).toBeInTheDocument()+ expect(screen.queryByText('server')).toBeNull()+ })+})++describe('InventoryDeviceModal — edit mode', () => {+ it('switches to the form on Edit and back on Cancel', () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument()+ // Lifecycle buttons belong to the view; the form has Save / Cancel.+ expect(screen.queryByRole('button', { name: 'Approve' })).toBeNull()++ fireEvent.click(screen.getByRole('button', { name: 'Cancel' }))+ expect(screen.getByRole('button', { name: 'Approve' })).toBeInTheDocument()+ })++ it('seeds the form from the row, falling back to the discovery type', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice({ label: null, type: null })} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ expect((screen.getByDisplayValue('pve.local') as HTMLInputElement).value).toBe('pve.local')+ expect(screen.getByDisplayValue('192.168.1.100')).toBeInTheDocument()++ // The untouched type select adopts `suggested_type` rather than clearing it.+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))+ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ expect(mockUpdatePending.mock.calls[0][1].type).toBe('server')+ })++ it('PATCHes the edited fields and reports the saved row', async () => {+ const onSaved = vi.fn()+ render(<InventoryDeviceModal {...noop} onSaved={onSaved} device={makeDevice()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))++ fireEvent.change(screen.getByPlaceholderText('Display name'), { target: { value: 'Big NAS' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ const [id, body] = mockUpdatePending.mock.calls[0]+ expect(id).toBe('dev-1')+ expect(body.label).toBe('Big NAS')+ expect(body.hostname).toBe('pve.local')+ expect(body.properties).toEqual([])+ await waitFor(() => expect(onSaved).toHaveBeenCalledWith(expect.objectContaining({ label: 'Saved' })))+ })++ it('sends null rather than an empty string for a cleared field', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.change(screen.getByDisplayValue('192.168.1.100'), { target: { value: '' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ expect(mockUpdatePending.mock.calls[0][1].ip).toBeNull()+ })++ it('sends the numeric hardware fields as numbers', async () => {+ render(<InventoryDeviceModal {...noop} device={makeDevice({ cpu_count: 2, ram_gb: 8 })} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.change(screen.getByDisplayValue('8'), { target: { value: '32' } })+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ const body = mockUpdatePending.mock.calls[0][1]+ expect(body.ram_gb).toBe(32)+ expect(body.cpu_count).toBe(2)+ })++ it('edits properties through the shared PropertyList', async () => {+ render(+ <InventoryDeviceModal+ {...noop}+ device={makeDevice({ properties: [{ key: 'Rack', value: 'A1', icon: null, visible: true }] })}+ />+ )+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ // The shared editor renders the existing property with its remove control.+ expect(screen.getByText('Rack')).toBeInTheDocument()+ fireEvent.click(screen.getByTitle('Remove property'))+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ expect(mockUpdatePending.mock.calls[0][1].properties).toEqual([])+ })++ it('removes a service from the editable list', async () => {+ render(+ <InventoryDeviceModal+ {...noop}+ device={makeDevice({+ services: [+ { port: 80, protocol: 'tcp', service_name: 'HTTP' },+ { port: 443, protocol: 'tcp', service_name: 'HTTPS' },+ ],+ })}+ />+ )+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.click(screen.getAllByTitle('Remove service')[0])+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ expect(mockUpdatePending.mock.calls[0][1].services).toEqual([+ { port: 443, protocol: 'tcp', service_name: 'HTTPS' },+ ])+ })++ it('stays in edit mode when the save fails', async () => {+ mockUpdatePending.mockRejectedValueOnce(new Error('boom'))+ render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ fireEvent.click(screen.getByRole('button', { name: 'Save' }))++ await waitFor(() => expect(mockUpdatePending).toHaveBeenCalled())+ expect(screen.getByRole('button', { name: 'Save' })).toBeInTheDocument()+ })++ it('reseeds the form when pointed at another device', () => {+ const { rerender } = render(<InventoryDeviceModal {...noop} device={makeDevice()} />)+ fireEvent.click(screen.getByRole('button', { name: 'Edit' }))+ expect(screen.getByDisplayValue('pve.local')).toBeInTheDocument()++ rerender(<InventoryDeviceModal {...noop} device={makeDevice({ id: 'dev-2', hostname: 'other.local' })} />)+ // Back to the view of the new device, not the previous one's open form.+ expect(screen.queryByRole('button', { name: 'Save' })).toBeNull()+ expect(screen.getAllByText('other.local').length).toBeGreaterThan(0)+ })+})diff --git a/frontend/src/types/index.ts b/frontend/src/types/index.tsindex ce385b0..5614641 100644--- a/frontend/src/types/index.ts+++ b/frontend/src/types/index.ts@@ -108,6 +108,69 @@ export interface NodeProperty {visible: boolean}+/**+ * A Device Inventory row, as `/scan/pending` returns it.+ *+ * The inventory row — not the canvas node — owns what a device *is*: its+ * addresses, services, properties, notes and hardware. A node describes how+ * that device is drawn on one canvas. Re-exported from+ * `components/modals/InventoryDeviceModal` for the call sites that predate this+ * home.+ */+export interface InventoryEntry {+ id: string+ ip: string | null+ mac: string | null+ hostname: string | null+ os: string | null+ services: ServiceInfo[]+ suggested_type: string | null+ /** Inventory lifecycle: pending / approved / hidden. Not reachability. */+ status: string+ discovery_source?: string | null+ /**+ * All sources that have observed this device (e.g. ["arp", "proxmox"]). A+ * merged device shows under every matching filter. Falls back to+ * [discovery_source] when absent (older rows).+ */+ discovery_sources?: string[]+ ieee_address?: string | null+ friendly_name?: string | null+ device_subtype?: string | null+ model?: string | null+ vendor?: string | null+ lqi?: number | null+ properties?: NodeProperty[]+ discovered_at: string+ /** Curated facts, editable from the device detail modal. */+ label?: string | null+ type?: string | null+ notes?: string | null+ cpu_count?: number | null+ cpu_model?: string | null+ ram_gb?: number | null+ disk_gb?: number | null+ show_hardware?: boolean+ check_method?: CheckMethod | null+ check_target?: string | null+ /** Live reachability from the status checker — distinct from `status`. */+ status_live?: string+ last_seen?: string | null+ last_scan?: string | null+ response_time_ms?: number | null+ updated_at?: string | null+ /** How many canvases (designs) this device already appears on. Server-computed. */+ canvas_count?: number+ /**+ * Timestamps from the linked canvas node(s), correlated by ip/ieee_address.+ * Null/absent when the device is not on any canvas yet.+ */+ node_created_at?: string | null+ node_last_scan?: string | null+ node_last_modified?: string | null+ node_last_seen?: string | null+}+export interface NodeData extends Record<string, unknown> {label: stringtype: NodeTypediff --git a/frontend/src/utils/nodeTypeGroups.ts b/frontend/src/utils/nodeTypeGroups.tsnew file mode 100644index 0000000..fb08aa7--- /dev/null+++ b/frontend/src/utils/nodeTypeGroups.ts@@ -0,0 +1,25 @@+import type { NodeType } from '@/types'++/**+ * Node types offered by the type pickers, grouped for the select.+ *+ * Shared by `NodeModal` (canvas node) and `InventoryDeviceModal` (inventory+ * row) so a device gets the same vocabulary wherever it is typed. Canvas+ * furniture that is not a device (`group`, `text`) is deliberately absent —+ * those are created from the toolbar, never picked here.+ */+export const NODE_TYPE_GROUPS: { label: string; types: NodeType[] }[] = [+ { label: 'Hardware', types: ['isp', 'router', 'firewall', 'switch', 'server', 'nas', 'kvm', 'ap', 'printer'] },+ { label: 'Virtualization', types: ['proxmox', 'vm', 'lxc', 'docker_host', 'docker_container'] },+ { label: 'IoT', types: ['iot', 'camera', 'cpl'] },+ { label: 'Zigbee', types: ['zigbee_coordinator', 'zigbee_router', 'zigbee_enddevice'] },+ { label: 'Z-Wave', types: ['zwave_coordinator', 'zwave_router', 'zwave_enddevice'] },+ { label: 'Personal', types: ['computer', 'laptop', 'mobile'] },+ { label: 'Electrical', types: ['grid', 'ups', 'battery', 'generator', 'solar_panel', 'inverter', 'circuit_breaker', 'contactor', 'electrical_switch', 'socket', 'light', 'meter', 'transformer', 'load'] },+ { label: 'Generic', types: ['generic', 'groupRect'] },+]++/** Same list without `groupRect` — an inventory row describes real hardware. */+export const DEVICE_TYPE_GROUPS: { label: string; types: NodeType[] }[] = NODE_TYPE_GROUPS.map((g) =>+ g.types.includes('groupRect') ? { ...g, types: g.types.filter((t) => t !== 'groupRect') } : g+)