Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

fix(rack): name inventory entries the way the Device Inventory does

Pouzorcfa296ef879a
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.py
index a6a0f7a..d5a69dc 100644
--- a/backend/app/api/routes/racks.py
+++ b/backend/app/api/routes/racks.py
@@ -44,6 +44,47 @@ _UNRACKABLE_TYPES = {
}
+_COMMON_PORTS = {22, 80, 443}
+
+
+def _service_name(device: PendingDevice) -> str | None:
+ """Name a device after the app it runs, the way the Device Inventory does.
+
+ Ports everyone exposes (ssh, http, https) say nothing, and the generic web
+ category loses to a real match, so "jellyfin" wins over "http".
+ """
+ candidates = [
+ s
+ for s in (device.services or [])
+ if isinstance(s, dict)
+ and s.get("category")
+ and s.get("service_name")
+ and s.get("port") not in _COMMON_PORTS
+ ]
+ if not candidates:
+ return None
+ named = next((s for s in candidates if str(s["category"]).lower() != "web"), candidates[0])
+ name = named.get("service_name")
+ return str(name) if name else None
+
+
+def _device_label(device: PendingDevice) -> str:
+ """Inventory naming, mirrored: friendly name, host, app, IP, IEEE, id.
+
+ Must stay in step with `deviceLabel` in `PendingDevicesModal.tsx` — a device
+ the user picked out of the inventory by one name should not turn up in the
+ rack picker under another.
+ """
+ return (
+ device.friendly_name
+ or device.hostname
+ or _service_name(device)
+ or device.ip
+ or device.ieee_address
+ or device.id
+ )
+
+
def _ip_tokens(ip: str | None) -> list[str]:
"""Split a device ``ip`` field into individual addresses.
@@ -211,7 +252,7 @@ async def rack_inventory(
items.append(
RackInventoryItem(
id=device.id,
- label=device.friendly_name or device.hostname or device.ip or device.id,
+ label=_device_label(device),
suggested_type=device.suggested_type,
ip=device.ip,
status=device.status,
diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.py
index 174e052..c337c62 100644
--- a/backend/tests/test_racks.py
+++ b/backend/tests/test_racks.py
@@ -1,6 +1,8 @@
import pytest
from httpx import AsyncClient
+from app.db.models import PendingDevice
+
pytestmark = pytest.mark.asyncio
@@ -218,6 +220,36 @@ class TestInventory:
assert "pve-01" in labels
assert "phone" not in labels
+ async def test_names_a_device_the_way_the_inventory_does(
+ self, client: AsyncClient, headers, db_session
+ ):
+ """A scan find with no hostname is named after the app it runs, not its IP.
+
+ The rack picker used to show "192.168.1.63 · 192.168.1.63" where the
+ Device Inventory showed "jellyfin".
+ """
+ design_id = await _design(client, headers)
+ db_session.add(
+ PendingDevice(
+ id="pd-services",
+ ip="192.168.1.63",
+ services=[
+ {"port": 443, "category": "web", "service_name": "https"},
+ {"port": 8096, "category": "media", "service_name": "jellyfin"},
+ ],
+ suggested_type="server",
+ )
+ )
+ db_session.add(PendingDevice(id="pd-bare", ip="192.168.1.64", suggested_type="server"))
+ await db_session.commit()
+
+ items = (
+ await client.get(f"/api/v1/racks/inventory?design_id={design_id}", headers=headers)
+ ).json()["items"]
+ assert next(i for i in items if i["id"] == "pd-services")["label"] == "jellyfin"
+ # Nothing better to say: the IP stays the label, and the UI stops doubling it.
+ assert next(i for i in items if i["id"] == "pd-bare")["label"] == "192.168.1.64"
+
async def test_flags_devices_already_mounted(self, client: AsyncClient, headers):
design_id = await _design(client, headers)
created = (
diff --git a/frontend/src/rack/README.md b/frontend/src/rack/README.md
index 86049b4..1ea8cc5 100644
--- a/frontend/src/rack/README.md
+++ b/frontend/src/rack/README.md
@@ -14,7 +14,7 @@ Create one from **New Canvas → Kind → Rack**.
| Vertical | `uStart` (1-based, **always counted from the bottom rail**) + `uHeight`. `numbering` only changes the printed labels. |
| Horizontal | 12-column grid (`RACK_COLUMNS`). Full = 12, half = 6, third = 4, quarter = 3 — so 2 or 3 machines share one U. |
| Collision | `canPlace` / `findSlot` in `layout.ts`. A drop snaps to the nearest free slot; an impossible drop shows a red preview. |
-| Inventory | A mount references a **Device Inventory** entry (`pending_devices`) via `deviceId`. Those rows survive approval *and* node deletion, so unracking never removes the device. Accessories (blank, shelf, cable manager) have `deviceId: null`. |
+| Inventory | A mount references a **Device Inventory** entry (`pending_devices`) via `deviceId`. Those rows survive approval *and* node deletion, so unracking never removes the device. Accessories (blank, shelf, cable manager) have `deviceId: null`. `label` comes from `_device_label` in `racks.py`, which mirrors `deviceLabel` in `PendingDevicesModal.tsx` (friendly name → host → app the ports say it runs → IP → IEEE → id) so a device is named the same in both lists. |
| Rack-created gear | A device created from this canvas is a normal inventory row with `discovery_source: "rack"`, so it inherits the inventory's search, filters, hide and delete. It shows under the **Rack devices** source filter, and both `POST /scan/pending/{id}/approve` and bulk-approve refuse it — a mount is not a host to document on a logical canvas. |
| Canvas node link | `nodeId` is a second, optional link to a logical-canvas node, resolved server-side by IEEE then IP. It supplies live status and lets the network-link import match endpoints. Never required. |
| Faceplates | Declarative templates in `faceplates.ts`, drawn as SVG in unit coordinates so a plate scales with U height and rack width. Applying a template seeds ports; the user edits them afterwards. `suggestFaceplate()` picks one from the device's discovery type. Chosen from `FaceplatePicker` — a visual catalog, not a `<select>`: every template is drawn with the canvas renderer at its real relative width and U height, grouped, searchable, and filterable by `kind` (accessories are offered only to accessories). |
diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
index d0f21eb..797b9f5 100644
--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
@@ -58,6 +58,41 @@ describe('RackDeviceModal — adding', () => {
expect(store().deviceEditor).toBeNull()
})
+ it('labels inventory options without repeating the IP', () => {
+ store().openDeviceEditor()
+ useRackStore.setState({
+ inventory: [
+ {
+ id: 'inv-ip',
+ label: '192.168.1.63',
+ type: 'server',
+ ip: '192.168.1.63',
+ status: 'unknown',
+ nodeId: null,
+ racked: false,
+ suggestedFaceplateId: 'server-1u',
+ },
+ {
+ id: 'inv-named',
+ label: 'pve-01',
+ type: 'proxmox',
+ ip: '192.168.1.10',
+ status: 'unknown',
+ nodeId: null,
+ racked: false,
+ suggestedFaceplateId: 'server-2u-bays',
+ },
+ ],
+ })
+ render(<RackDeviceModal />)
+
+ // Regression: an IP-labelled entry read "192.168.1.63 · 192.168.1.63".
+ expect(screen.getByRole('option', { name: '192.168.1.63 · server' })).toBeInTheDocument()
+ expect(
+ screen.getByRole('option', { name: 'pve-01 · 192.168.1.10 · proxmox' }),
+ ).toBeInTheDocument()
+ })
+
it('creates a brand new inventory entry from the canvas and mounts it', async () => {
createPending.mockResolvedValue({ data: { id: 'pending-1' } })
store().openDeviceEditor()
@@ -176,6 +211,19 @@ describe('RackDeviceModal — editing', () => {
)
})
+ it('keeps the port name field usable next to the type select', () => {
+ store().openDeviceEditor('dev-pve1')
+ render(<RackDeviceModal />)
+
+ // Regression: both carried `w-full`, so the select ate the row and the name
+ // field collapsed into an unlabelled box.
+ const port = store().devices.find((d) => d.id === 'dev-pve1')!.ports[0]
+ const name = screen.getByLabelText(`Port ${port.label} label`)
+ expect(name).toHaveClass('flex-1', 'min-w-0')
+ expect(name).not.toHaveClass('w-full')
+ expect(name).toHaveAttribute('placeholder', 'Port name')
+ })
+
it('unmounts without dropping the inventory entry', async () => {
store().openDeviceEditor('dev-pve1')
render(<RackDeviceModal />)
diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsx
index 72b8827..cfb6ed5 100644
--- a/frontend/src/rack/components/RackDeviceModal.tsx
+++ b/frontend/src/rack/components/RackDeviceModal.tsx
@@ -21,16 +21,37 @@ import { FaceplatePicker } from './FaceplatePicker'
import { Faceplate } from './Faceplate'
import { getFaceplate } from '../faceplates'
import { generateUUID } from '@/utils/uuid'
-import { RACK_COLUMNS, type DeviceStatus, type Port, type PortType } from '@/types'
+import {
+ RACK_COLUMNS,
+ type DeviceStatus,
+ type InventoryDevice,
+ type Port,
+ type PortType,
+} from '@/types'
const DEFAULT_COLOR = '#2b323c'
type Source = 'inventory' | 'new' | 'accessory'
-const inputClass =
- 'w-full rounded border border-[#30363d] bg-[#21262d] px-2 py-1 text-sm text-foreground outline-none focus:border-[#00d4ff]'
+const inputBase =
+ 'rounded border border-[#30363d] bg-[#21262d] px-2 py-1 text-sm text-foreground outline-none focus:border-[#00d4ff]'
+const inputClass = `w-full ${inputBase}`
const fieldLabel = 'text-xs text-muted-foreground'
+/**
+ * One line for the inventory picker.
+ *
+ * Entries with no hostname are already labelled with their IP by the backend, so
+ * appending it again printed "192.168.1.63 · 192.168.1.63". Show the IP only
+ * when it adds something, and the type as the tiebreaker between look-alikes.
+ */
+function inventoryOption(item: InventoryDevice): string {
+ const parts = [item.label]
+ if (item.ip && item.ip !== item.label) parts.push(item.ip)
+ if (item.type) parts.push(item.type)
+ return parts.join(' · ')
+}
+
function Field({ label, children }: { label: string; children: React.ReactNode }) {
return (
<div className="flex flex-col gap-1.5">
@@ -247,8 +268,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
<option value="">Select a device…</option>
{unracked.map((item) => (
<option key={item.id} value={item.id}>
- {item.label}
- {item.ip ? ` · ${item.ip}` : ''}
+ {inventoryOption(item)}
</option>
))}
</select>
@@ -438,8 +458,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
{ports.map((port) => (
<li key={port.id} className="flex items-center gap-1">
<input
- className={`${inputClass} flex-1`}
+ // `inputClass` is w-full: without min-w-0 the flex row lets the
+ // type select win the space and the name field collapses to a box.
+ className={`${inputBase} min-w-0 flex-1`}
aria-label={`Port ${port.label} label`}
+ placeholder="Port name"
value={port.label}
onChange={(e) =>
setLocalPorts((list) =>
@@ -448,7 +471,7 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
}
/>
<select
- className={`${inputClass} w-24`}
+ className={`${inputBase} w-24 shrink-0`}
aria-label={`Port ${port.label} type`}
value={port.type}
onChange={(e) =>