Skip to content

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

fix(rack): stop the device modal losing cables, status and inventory rows

Pouzor8cafeee7438b
diff --git a/backend/app/api/routes/racks.py b/backend/app/api/routes/racks.py
index d5a69dc..1d00d30 100644
--- a/backend/app/api/routes/racks.py
+++ b/backend/app/api/routes/racks.py
@@ -59,6 +59,9 @@ def _service_name(device: PendingDevice) -> str | None:
if isinstance(s, dict)
and s.get("category")
and s.get("service_name")
+ # A service with no port is not a fingerprint the inventory names a
+ # device after either — and `None not in _COMMON_PORTS` is True.
+ and s.get("port") is not None
and s.get("port") not in _COMMON_PORTS
]
if not candidates:
diff --git a/backend/tests/test_racks.py b/backend/tests/test_racks.py
index c337c62..34911ec 100644
--- a/backend/tests/test_racks.py
+++ b/backend/tests/test_racks.py
@@ -241,6 +241,16 @@ class TestInventory:
)
)
db_session.add(PendingDevice(id="pd-bare", ip="192.168.1.64", suggested_type="server"))
+ # A portless service is no fingerprint: the inventory skips it, so must
+ # this — `None not in _COMMON_PORTS` is True and used to let it through.
+ db_session.add(
+ PendingDevice(
+ id="pd-portless",
+ ip="192.168.1.65",
+ services=[{"port": None, "category": "media", "service_name": "jellyfin"}],
+ suggested_type="server",
+ )
+ )
await db_session.commit()
items = (
@@ -249,6 +259,7 @@ class TestInventory:
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"
+ assert next(i for i in items if i["id"] == "pd-portless")["label"] == "192.168.1.65"
async def test_flags_devices_already_mounted(self, client: AsyncClient, headers):
design_id = await _design(client, headers)
diff --git a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
index 797b9f5..0987d6d 100644
--- a/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
+++ b/frontend/src/rack/__tests__/RackDeviceModal.test.tsx
@@ -3,7 +3,7 @@
* right rail — so everything the old inspector did has to work from here.
*/
import { describe, it, expect, beforeEach, vi } from 'vitest'
-import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'
import { RackDeviceModal } from '../components/RackDeviceModal'
import { useRackStore } from '../store'
@@ -58,6 +58,65 @@ describe('RackDeviceModal — adding', () => {
expect(store().deviceEditor).toBeNull()
})
+ it('keeps the preselected entry status instead of saving unknown over it', async () => {
+ store().openDeviceEditor()
+ const first = store().inventory.find((i) => !i.racked)!
+ useRackStore.setState({
+ inventory: store().inventory.map((i) =>
+ i.id === first.id ? { ...i, status: 'online' as const } : i,
+ ),
+ })
+ render(<RackDeviceModal />)
+
+ // The select preselects the first unracked entry, so submitting straight
+ // away is a real path — it used to commit `unknown` over the live status.
+ submit()
+
+ await waitFor(() => expect(store().deviceEditor).toBeNull())
+ expect(store().devices.find((d) => d.deviceId === first.id)!.status).toBe('online')
+ })
+
+ it('creates nothing in the inventory when the rack has no room', async () => {
+ store().openDeviceEditor()
+ const rack = store().racks[0]
+ // A 1U rack with its only slot taken: the mount cannot succeed.
+ useRackStore.setState({
+ racks: [{ ...rack, uHeight: 1 }],
+ devices: [
+ {
+ id: 'blocker',
+ rackId: rack.id,
+ deviceId: null,
+ nodeId: null,
+ label: 'blocker',
+ faceplateId: 'blank-1u',
+ uStart: 1,
+ uHeight: 1,
+ colStart: 0,
+ colSpan: 12,
+ status: 'unknown',
+ ports: [],
+ },
+ ],
+ cables: [],
+ })
+ const inventoryBefore = store().inventory.length
+ render(<RackDeviceModal />)
+
+ fireEvent.click(screen.getByRole('button', { name: 'New device' }))
+ fireEvent.change(screen.getByLabelText('Label'), { target: { value: 'orphan' } })
+ // The submit path is async (it may POST), so let it settle before asserting.
+ await act(async () => submit())
+
+ const { toast } = await import('sonner')
+ expect(toast.error).toHaveBeenCalled()
+ // The row is POSTed before the mount, so a late failure would strand it —
+ // and strand another one on every retry.
+ expect(createPending).not.toHaveBeenCalled()
+ expect(store().inventory).toHaveLength(inventoryBefore)
+ expect(store().deviceEditor).not.toBeNull()
+ })
+
it('labels inventory options without repeating the IP', () => {
store().openDeviceEditor()
useRackStore.setState({
@@ -197,6 +256,34 @@ describe('RackDeviceModal — editing', () => {
expect(device.uHeight).toBe(2)
})
+ it('keeps the ports and cables when the plate choice is reverted', async () => {
+ store().openDeviceEditor('dev-pve1')
+ render(<RackDeviceModal />)
+
+ const before = store().devices.find((d) => d.id === 'dev-pve1')!
+ const cablesBefore = store().cables.filter(
+ (c) => c.from.deviceId === 'dev-pve1' || c.to.deviceId === 'dev-pve1',
+ )
+ expect(cablesBefore.length).toBeGreaterThan(0)
+
+ // Browse away and back. The plate is unchanged, so `applyFaceplate` is
+ // skipped on save — reseeded port ids would then reach `setPorts` and take
+ // every cable on the device down with them, with no warning shown.
+ pickFaceplate('NAS 2U — 8 bays')
+ pickFaceplate('Server 2U — 8 bays')
+ expect(screen.queryByText(/replaces its ports/)).not.toBeInTheDocument()
+ submit()
+
+ await waitFor(() => expect(store().deviceEditor).toBeNull())
+ const after = store().devices.find((d) => d.id === 'dev-pve1')!
+ expect(after.ports.map((p) => p.id)).toEqual(before.ports.map((p) => p.id))
+ expect(
+ store().cables.filter(
+ (c) => c.from.deviceId === 'dev-pve1' || c.to.deviceId === 'dev-pve1',
+ ),
+ ).toHaveLength(cablesBefore.length)
+ })
+
it('edits the port list and commits it on save', async () => {
store().openDeviceEditor('dev-pve1')
render(<RackDeviceModal />)
diff --git a/frontend/src/rack/components/RackDeviceModal.tsx b/frontend/src/rack/components/RackDeviceModal.tsx
index cfb6ed5..b19c0d6 100644
--- a/frontend/src/rack/components/RackDeviceModal.tsx
+++ b/frontend/src/rack/components/RackDeviceModal.tsx
@@ -20,6 +20,7 @@ import { useRackStore } from '../store'
import { FaceplatePicker } from './FaceplatePicker'
import { Faceplate } from './Faceplate'
import { getFaceplate } from '../faceplates'
+import { findSlot } from '../layout'
import { generateUUID } from '@/utils/uuid'
import {
RACK_COLUMNS,
@@ -72,6 +73,7 @@ export function RackDeviceModal() {
function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: () => void }) {
const device = useRackStore((s) => s.devices.find((d) => d.id === deviceId))
const racks = useRackStore((s) => s.racks)
+ const devices = useRackStore((s) => s.devices)
const inventory = useRackStore((s) => s.inventory)
const mountFromInventory = useRackStore((s) => s.mountFromInventory)
const mountAccessory = useRackStore((s) => s.mountAccessory)
@@ -96,7 +98,12 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
const [uHeight, setUHeight] = useState(device?.uHeight ?? getFaceplate(faceplateId).uHeight)
const [colStart, setColStart] = useState(device?.colStart ?? 0)
const [colSpan, setColSpan] = useState(device?.colSpan ?? getFaceplate(faceplateId).colSpan)
- const [status, setStatus] = useState<DeviceStatus>(device?.status ?? 'unknown')
+ // The picker preselects the first unracked entry, so seed its status too:
+ // submitting without touching the select used to save `unknown` over the
+ // status the mount had just copied from the inventory.
+ const [status, setStatus] = useState<DeviceStatus>(
+ device?.status ?? unracked[0]?.status ?? 'unknown',
+ )
const [color, setColor] = useState<string | undefined>(device?.color)
const [ports, setLocalPorts] = useState<Port[]>(
device?.ports ?? getFaceplate(faceplateId).ports.map((p) => ({ ...p, id: generateUUID() })),
@@ -119,8 +126,14 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
setUHeight(plate.uHeight)
setColSpan(plate.colSpan)
setColStart((c) => Math.min(c, RACK_COLUMNS - plate.colSpan))
- setLocalPorts(plate.ports.map((p) => ({ ...p, id: generateUUID() })))
- setPlateChanged(true)
+ // Coming back to the plate the device already wears is not a change: keep
+ // its own ports, ids included. Reseeding them would hand `setPorts` a list
+ // of unknown ids on save and take every cable on the device down with it.
+ const reverted = device && id === device.faceplateId
+ setLocalPorts(
+ reverted ? device.ports : plate.ports.map((p) => ({ ...p, id: generateUUID() })),
+ )
+ setPlateChanged(!reverted)
}
/** Accessories and devices draw from disjoint halves of the catalog. */
@@ -187,6 +200,11 @@ function DeviceForm({ deviceId, onClose }: { deviceId: string | null; onClose: (
toast.error('Name the device first')
return null
}
+ // `createInventoryDevice` POSTs straight to the Device Inventory, so a
+ // mount that fails afterwards would leave a row behind — and a second one
+ // on every retry. Check the rack has a slot before creating anything.
+ const rack = racks.find((r) => r.id === rackId)
+ if (!rack || !findSlot(rack, devices, geometry)) return noRoom()
const created = await createInventoryDevice({ label: name, ip: newIp.trim() || null })
if (!created) {
toast.error('Could not add the device to the inventory')